xref: /linux/drivers/iio/adc/at91-sama5d2_adc.c (revision 2cc699b3c2fe5ea84081059c88c46373cbebe630)
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/clk.h>
13 #include <linux/delay.h>
14 #include <linux/dma-mapping.h>
15 #include <linux/dmaengine.h>
16 #include <linux/interrupt.h>
17 #include <linux/io.h>
18 #include <linux/module.h>
19 #include <linux/mod_devicetable.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 /*
589  * Buffer size requirements:
590  * No channels * bytes_per_channel(2) + timestamp bytes (8)
591  * Divided by 2 because we need half words.
592  * We assume 32 channels for now, has to be increased if needed.
593  * Nobody minds a buffer being too big.
594  */
595 #define AT91_BUFFER_MAX_HWORDS ((32 * 2 + 8) / 2)
596 
597 struct at91_adc_state {
598 	void __iomem			*base;
599 	int				irq;
600 	struct clk			*per_clk;
601 	struct regulator		*reg;
602 	struct regulator		*vref;
603 	int				vref_uv;
604 	unsigned int			current_sample_rate;
605 	struct iio_trigger		*trig;
606 	const struct at91_adc_trigger	*selected_trig;
607 	const struct iio_chan_spec	*chan;
608 	bool				conversion_done;
609 	u32				conversion_value;
610 	unsigned int			oversampling_ratio;
611 	struct at91_adc_soc_info	soc_info;
612 	wait_queue_head_t		wq_data_available;
613 	struct at91_adc_dma		dma_st;
614 	struct at91_adc_touch		touch_st;
615 	struct at91_adc_temp		temp_st;
616 	struct iio_dev			*indio_dev;
617 	struct device			*dev;
618 	/* Ensure naturally aligned timestamp */
619 	u16				buffer[AT91_BUFFER_MAX_HWORDS] __aligned(8);
620 	/*
621 	 * lock to prevent concurrent 'single conversion' requests through
622 	 * sysfs.
623 	 */
624 	struct mutex			lock;
625 };
626 
627 static const struct at91_adc_trigger at91_adc_trigger_list[] = {
628 	{
629 		.name = "external_rising",
630 		.trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_RISE,
631 		.edge_type = IRQ_TYPE_EDGE_RISING,
632 		.hw_trig = true,
633 	},
634 	{
635 		.name = "external_falling",
636 		.trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_FALL,
637 		.edge_type = IRQ_TYPE_EDGE_FALLING,
638 		.hw_trig = true,
639 	},
640 	{
641 		.name = "external_any",
642 		.trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_ANY,
643 		.edge_type = IRQ_TYPE_EDGE_BOTH,
644 		.hw_trig = true,
645 	},
646 	{
647 		.name = "software",
648 		.trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_NO_TRIGGER,
649 		.edge_type = IRQ_TYPE_NONE,
650 		.hw_trig = false,
651 	},
652 };
653 
654 static const struct iio_chan_spec at91_sama5d2_adc_channels[] = {
655 	AT91_SAMA5D2_CHAN_SINGLE(0, 0, 0x50),
656 	AT91_SAMA5D2_CHAN_SINGLE(1, 1, 0x54),
657 	AT91_SAMA5D2_CHAN_SINGLE(2, 2, 0x58),
658 	AT91_SAMA5D2_CHAN_SINGLE(3, 3, 0x5c),
659 	AT91_SAMA5D2_CHAN_SINGLE(4, 4, 0x60),
660 	AT91_SAMA5D2_CHAN_SINGLE(5, 5, 0x64),
661 	AT91_SAMA5D2_CHAN_SINGLE(6, 6, 0x68),
662 	AT91_SAMA5D2_CHAN_SINGLE(7, 7, 0x6c),
663 	AT91_SAMA5D2_CHAN_SINGLE(8, 8, 0x70),
664 	AT91_SAMA5D2_CHAN_SINGLE(9, 9, 0x74),
665 	AT91_SAMA5D2_CHAN_SINGLE(10, 10, 0x78),
666 	AT91_SAMA5D2_CHAN_SINGLE(11, 11, 0x7c),
667 	/* original ABI has the differential channels with a gap in between */
668 	AT91_SAMA5D2_CHAN_DIFF(12, 0, 1, 0x50),
669 	AT91_SAMA5D2_CHAN_DIFF(14, 2, 3, 0x58),
670 	AT91_SAMA5D2_CHAN_DIFF(16, 4, 5, 0x60),
671 	AT91_SAMA5D2_CHAN_DIFF(18, 6, 7, 0x68),
672 	AT91_SAMA5D2_CHAN_DIFF(20, 8, 9, 0x70),
673 	AT91_SAMA5D2_CHAN_DIFF(22, 10, 11, 0x78),
674 	IIO_CHAN_SOFT_TIMESTAMP(23),
675 	AT91_SAMA5D2_CHAN_TOUCH(24, "x", IIO_MOD_X),
676 	AT91_SAMA5D2_CHAN_TOUCH(25, "y", IIO_MOD_Y),
677 	AT91_SAMA5D2_CHAN_PRESSURE(26, "pressure"),
678 };
679 
680 static const struct iio_chan_spec at91_sama7g5_adc_channels[] = {
681 	AT91_SAMA7G5_CHAN_SINGLE(0, 0, 0x60),
682 	AT91_SAMA7G5_CHAN_SINGLE(1, 1, 0x64),
683 	AT91_SAMA7G5_CHAN_SINGLE(2, 2, 0x68),
684 	AT91_SAMA7G5_CHAN_SINGLE(3, 3, 0x6c),
685 	AT91_SAMA7G5_CHAN_SINGLE(4, 4, 0x70),
686 	AT91_SAMA7G5_CHAN_SINGLE(5, 5, 0x74),
687 	AT91_SAMA7G5_CHAN_SINGLE(6, 6, 0x78),
688 	AT91_SAMA7G5_CHAN_SINGLE(7, 7, 0x7c),
689 	AT91_SAMA7G5_CHAN_SINGLE(8, 8, 0x80),
690 	AT91_SAMA7G5_CHAN_SINGLE(9, 9, 0x84),
691 	AT91_SAMA7G5_CHAN_SINGLE(10, 10, 0x88),
692 	AT91_SAMA7G5_CHAN_SINGLE(11, 11, 0x8c),
693 	AT91_SAMA7G5_CHAN_SINGLE(12, 12, 0x90),
694 	AT91_SAMA7G5_CHAN_SINGLE(13, 13, 0x94),
695 	AT91_SAMA7G5_CHAN_SINGLE(14, 14, 0x98),
696 	AT91_SAMA7G5_CHAN_SINGLE(15, 15, 0x9c),
697 	AT91_SAMA7G5_CHAN_DIFF(16, 0, 1, 0x60),
698 	AT91_SAMA7G5_CHAN_DIFF(17, 2, 3, 0x68),
699 	AT91_SAMA7G5_CHAN_DIFF(18, 4, 5, 0x70),
700 	AT91_SAMA7G5_CHAN_DIFF(19, 6, 7, 0x78),
701 	AT91_SAMA7G5_CHAN_DIFF(20, 8, 9, 0x80),
702 	AT91_SAMA7G5_CHAN_DIFF(21, 10, 11, 0x88),
703 	AT91_SAMA7G5_CHAN_DIFF(22, 12, 13, 0x90),
704 	AT91_SAMA7G5_CHAN_DIFF(23, 14, 15, 0x98),
705 	IIO_CHAN_SOFT_TIMESTAMP(24),
706 	AT91_SAMA5D2_CHAN_TEMP(AT91_SAMA7G5_ADC_TEMP_CHANNEL, "temp", 0xdc),
707 };
708 
709 static const struct at91_adc_platform sama5d2_platform = {
710 	.layout = &sama5d2_layout,
711 	.adc_channels = &at91_sama5d2_adc_channels,
712 #define AT91_SAMA5D2_SINGLE_CHAN_CNT 12
713 #define AT91_SAMA5D2_DIFF_CHAN_CNT 6
714 	.nr_channels = AT91_SAMA5D2_SINGLE_CHAN_CNT +
715 		       AT91_SAMA5D2_DIFF_CHAN_CNT,
716 #define AT91_SAMA5D2_TOUCH_X_CHAN_IDX	(AT91_SAMA5D2_SINGLE_CHAN_CNT + \
717 					AT91_SAMA5D2_DIFF_CHAN_CNT * 2)
718 	.touch_chan_x = AT91_SAMA5D2_TOUCH_X_CHAN_IDX,
719 #define AT91_SAMA5D2_TOUCH_Y_CHAN_IDX	(AT91_SAMA5D2_TOUCH_X_CHAN_IDX + 1)
720 	.touch_chan_y = AT91_SAMA5D2_TOUCH_Y_CHAN_IDX,
721 #define AT91_SAMA5D2_TOUCH_P_CHAN_IDX	(AT91_SAMA5D2_TOUCH_Y_CHAN_IDX + 1)
722 	.touch_chan_p = AT91_SAMA5D2_TOUCH_P_CHAN_IDX,
723 #define AT91_SAMA5D2_MAX_CHAN_IDX	AT91_SAMA5D2_TOUCH_P_CHAN_IDX
724 	.max_channels = ARRAY_SIZE(at91_sama5d2_adc_channels),
725 	.max_index = AT91_SAMA5D2_MAX_CHAN_IDX,
726 #define AT91_SAMA5D2_HW_TRIG_CNT	3
727 	.hw_trig_cnt = AT91_SAMA5D2_HW_TRIG_CNT,
728 	.osr_mask = GENMASK(17, 16),
729 	.oversampling_avail = { 1, 4, 16, },
730 	.oversampling_avail_no = 3,
731 	.chan_realbits = 14,
732 };
733 
734 static const struct at91_adc_platform sama7g5_platform = {
735 	.layout = &sama7g5_layout,
736 	.adc_channels = &at91_sama7g5_adc_channels,
737 #define AT91_SAMA7G5_SINGLE_CHAN_CNT	16
738 #define AT91_SAMA7G5_DIFF_CHAN_CNT	8
739 #define AT91_SAMA7G5_TEMP_CHAN_CNT	1
740 	.nr_channels = AT91_SAMA7G5_SINGLE_CHAN_CNT +
741 		       AT91_SAMA7G5_DIFF_CHAN_CNT +
742 		       AT91_SAMA7G5_TEMP_CHAN_CNT,
743 #define AT91_SAMA7G5_MAX_CHAN_IDX	(AT91_SAMA7G5_SINGLE_CHAN_CNT + \
744 					AT91_SAMA7G5_DIFF_CHAN_CNT + \
745 					AT91_SAMA7G5_TEMP_CHAN_CNT)
746 	.max_channels = ARRAY_SIZE(at91_sama7g5_adc_channels),
747 	.max_index = AT91_SAMA7G5_MAX_CHAN_IDX,
748 #define AT91_SAMA7G5_HW_TRIG_CNT	3
749 	.hw_trig_cnt = AT91_SAMA7G5_HW_TRIG_CNT,
750 	.osr_mask = GENMASK(18, 16),
751 	.oversampling_avail = { 1, 4, 16, 64, 256, },
752 	.oversampling_avail_no = 5,
753 	.chan_realbits = 16,
754 	.temp_sensor = true,
755 	.temp_chan = AT91_SAMA7G5_ADC_TEMP_CHANNEL,
756 };
757 
at91_adc_chan_xlate(struct iio_dev * indio_dev,int chan)758 static int at91_adc_chan_xlate(struct iio_dev *indio_dev, int chan)
759 {
760 	int i;
761 
762 	for (i = 0; i < indio_dev->num_channels; i++) {
763 		if (indio_dev->channels[i].scan_index == chan)
764 			return i;
765 	}
766 	return -EINVAL;
767 }
768 
769 static inline struct iio_chan_spec const *
at91_adc_chan_get(struct iio_dev * indio_dev,int chan)770 at91_adc_chan_get(struct iio_dev *indio_dev, int chan)
771 {
772 	int index = at91_adc_chan_xlate(indio_dev, chan);
773 
774 	if (index < 0)
775 		return NULL;
776 	return indio_dev->channels + index;
777 }
778 
at91_adc_fwnode_xlate(struct iio_dev * indio_dev,const struct fwnode_reference_args * iiospec)779 static inline int at91_adc_fwnode_xlate(struct iio_dev *indio_dev,
780 					const struct fwnode_reference_args *iiospec)
781 {
782 	return at91_adc_chan_xlate(indio_dev, iiospec->args[0]);
783 }
784 
at91_adc_active_scan_mask_to_reg(struct iio_dev * indio_dev)785 static unsigned int at91_adc_active_scan_mask_to_reg(struct iio_dev *indio_dev)
786 {
787 	u32 mask = 0;
788 	u8 bit;
789 	struct at91_adc_state *st = iio_priv(indio_dev);
790 
791 	for_each_set_bit(bit, indio_dev->active_scan_mask,
792 			 indio_dev->num_channels) {
793 		struct iio_chan_spec const *chan =
794 			 at91_adc_chan_get(indio_dev, bit);
795 		mask |= BIT(chan->channel);
796 	}
797 
798 	return mask & GENMASK(st->soc_info.platform->nr_channels, 0);
799 }
800 
at91_adc_cor(struct at91_adc_state * st,struct iio_chan_spec const * chan)801 static void at91_adc_cor(struct at91_adc_state *st,
802 			 struct iio_chan_spec const *chan)
803 {
804 	u32 cor, cur_cor;
805 
806 	cor = BIT(chan->channel) | BIT(chan->channel2);
807 
808 	cur_cor = at91_adc_readl(st, COR);
809 	cor <<= st->soc_info.platform->layout->COR_diff_offset;
810 	if (chan->differential)
811 		at91_adc_writel(st, COR, cur_cor | cor);
812 	else
813 		at91_adc_writel(st, COR, cur_cor & ~cor);
814 }
815 
at91_adc_irq_status(struct at91_adc_state * st,u32 * status,u32 * eoc)816 static void at91_adc_irq_status(struct at91_adc_state *st, u32 *status,
817 				u32 *eoc)
818 {
819 	*status = at91_adc_readl(st, ISR);
820 	if (st->soc_info.platform->layout->EOC_ISR)
821 		*eoc = at91_adc_readl(st, EOC_ISR);
822 	else
823 		*eoc = *status;
824 }
825 
at91_adc_irq_mask(struct at91_adc_state * st,u32 * status,u32 * eoc)826 static void at91_adc_irq_mask(struct at91_adc_state *st, u32 *status, u32 *eoc)
827 {
828 	*status = at91_adc_readl(st, IMR);
829 	if (st->soc_info.platform->layout->EOC_IMR)
830 		*eoc = at91_adc_readl(st, EOC_IMR);
831 	else
832 		*eoc = *status;
833 }
834 
at91_adc_eoc_dis(struct at91_adc_state * st,unsigned int channel)835 static void at91_adc_eoc_dis(struct at91_adc_state *st, unsigned int channel)
836 {
837 	/*
838 	 * On some products having the EOC bits in a separate register,
839 	 * errata recommends not writing this register (EOC_IDR).
840 	 * On products having the EOC bits in the IDR register, it's fine to write it.
841 	 */
842 	if (!st->soc_info.platform->layout->EOC_IDR)
843 		at91_adc_writel(st, IDR, BIT(channel));
844 }
845 
at91_adc_eoc_ena(struct at91_adc_state * st,unsigned int channel)846 static void at91_adc_eoc_ena(struct at91_adc_state *st, unsigned int channel)
847 {
848 	if (!st->soc_info.platform->layout->EOC_IDR)
849 		at91_adc_writel(st, IER, BIT(channel));
850 	else
851 		at91_adc_writel(st, EOC_IER, BIT(channel));
852 }
853 
at91_adc_config_emr(struct at91_adc_state * st,u32 oversampling_ratio,u32 trackx)854 static int at91_adc_config_emr(struct at91_adc_state *st,
855 			       u32 oversampling_ratio, u32 trackx)
856 {
857 	/* configure the extended mode register */
858 	unsigned int emr, osr;
859 	unsigned int osr_mask = st->soc_info.platform->osr_mask;
860 	int i, ret;
861 
862 	/* Check against supported oversampling values. */
863 	for (i = 0; i < st->soc_info.platform->oversampling_avail_no; i++) {
864 		if (oversampling_ratio == st->soc_info.platform->oversampling_avail[i])
865 			break;
866 	}
867 	if (i == st->soc_info.platform->oversampling_avail_no)
868 		return -EINVAL;
869 
870 	/* select oversampling ratio from configuration */
871 	switch (oversampling_ratio) {
872 	case 1:
873 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_1SAMPLES,
874 					   osr_mask);
875 		break;
876 	case 4:
877 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_4SAMPLES,
878 					   osr_mask);
879 		break;
880 	case 16:
881 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_16SAMPLES,
882 					   osr_mask);
883 		break;
884 	case 64:
885 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_64SAMPLES,
886 					   osr_mask);
887 		break;
888 	case 256:
889 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_256SAMPLES,
890 					   osr_mask);
891 		break;
892 	}
893 
894 	ret = pm_runtime_resume_and_get(st->dev);
895 	if (ret < 0)
896 		return ret;
897 
898 	emr = at91_adc_readl(st, EMR);
899 	/* select oversampling per single trigger event */
900 	emr |= AT91_SAMA5D2_EMR_ASTE(1);
901 	/* delete leftover content if it's the case */
902 	emr &= ~(osr_mask | AT91_SAMA5D2_TRACKX_MASK);
903 	/* Update osr and trackx. */
904 	emr |= osr | AT91_SAMA5D2_TRACKX(trackx);
905 	at91_adc_writel(st, EMR, emr);
906 
907 	pm_runtime_mark_last_busy(st->dev);
908 	pm_runtime_put_autosuspend(st->dev);
909 
910 	st->oversampling_ratio = oversampling_ratio;
911 
912 	return 0;
913 }
914 
at91_adc_adjust_val_osr(struct at91_adc_state * st,int * val)915 static int at91_adc_adjust_val_osr(struct at91_adc_state *st, int *val)
916 {
917 	int nbits, diff;
918 
919 	if (st->oversampling_ratio == 1)
920 		nbits = 12;
921 	else if (st->oversampling_ratio == 4)
922 		nbits = 13;
923 	else if (st->oversampling_ratio == 16)
924 		nbits = 14;
925 	else if (st->oversampling_ratio == 64)
926 		nbits = 15;
927 	else if (st->oversampling_ratio == 256)
928 		nbits = 16;
929 	else
930 		/* Should not happen. */
931 		return -EINVAL;
932 
933 	/*
934 	 * We have nbits of real data and channel is registered as
935 	 * st->soc_info.platform->chan_realbits, so shift left diff bits.
936 	 */
937 	diff = st->soc_info.platform->chan_realbits - nbits;
938 	*val <<= diff;
939 
940 	return IIO_VAL_INT;
941 }
942 
at91_adc_adjust_val_osr_array(struct at91_adc_state * st,void * buf,int len)943 static void at91_adc_adjust_val_osr_array(struct at91_adc_state *st, void *buf,
944 					  int len)
945 {
946 	int i = 0, val;
947 	u16 *buf_u16 = (u16 *) buf;
948 
949 	/*
950 	 * We are converting each two bytes (each sample).
951 	 * First convert the byte based array to u16, and convert each sample
952 	 * separately.
953 	 * Each value is two bytes in an array of chars, so to not shift
954 	 * more than we need, save the value separately.
955 	 * len is in bytes, so divide by two to get number of samples.
956 	 */
957 	while (i < len / 2) {
958 		val = buf_u16[i];
959 		at91_adc_adjust_val_osr(st, &val);
960 		buf_u16[i] = val;
961 		i++;
962 	}
963 }
964 
at91_adc_configure_touch(struct at91_adc_state * st,bool state)965 static int at91_adc_configure_touch(struct at91_adc_state *st, bool state)
966 {
967 	u32 clk_khz = st->current_sample_rate / 1000;
968 	int i = 0, ret;
969 	u16 pendbc;
970 	u32 tsmr, acr;
971 
972 	if (state) {
973 		ret = pm_runtime_resume_and_get(st->dev);
974 		if (ret < 0)
975 			return ret;
976 	} else {
977 		/* disabling touch IRQs and setting mode to no touch enabled */
978 		at91_adc_writel(st, IDR,
979 				AT91_SAMA5D2_IER_PEN | AT91_SAMA5D2_IER_NOPEN);
980 		at91_adc_writel(st, TSMR, 0);
981 
982 		pm_runtime_mark_last_busy(st->dev);
983 		pm_runtime_put_autosuspend(st->dev);
984 		return 0;
985 	}
986 	/*
987 	 * debounce time is in microseconds, we need it in milliseconds to
988 	 * multiply with kilohertz, so, divide by 1000, but after the multiply.
989 	 * round up to make sure pendbc is at least 1
990 	 */
991 	pendbc = round_up(AT91_SAMA5D2_TOUCH_PEN_DETECT_DEBOUNCE_US *
992 			  clk_khz / 1000, 1);
993 
994 	/* get the required exponent */
995 	while (pendbc >> i++)
996 		;
997 
998 	pendbc = i;
999 
1000 	tsmr = AT91_SAMA5D2_TSMR_TSMODE_4WIRE_PRESS;
1001 
1002 	tsmr |= AT91_SAMA5D2_TSMR_TSAV(2) & AT91_SAMA5D2_TSMR_TSAV_MASK;
1003 	tsmr |= AT91_SAMA5D2_TSMR_PENDBC(pendbc) &
1004 		AT91_SAMA5D2_TSMR_PENDBC_MASK;
1005 	tsmr |= AT91_SAMA5D2_TSMR_NOTSDMA;
1006 	tsmr |= AT91_SAMA5D2_TSMR_PENDET_ENA;
1007 	tsmr |= AT91_SAMA5D2_TSMR_TSFREQ(2) & AT91_SAMA5D2_TSMR_TSFREQ_MASK;
1008 
1009 	at91_adc_writel(st, TSMR, tsmr);
1010 
1011 	acr =  at91_adc_readl(st, ACR);
1012 	acr &= ~AT91_SAMA5D2_ACR_PENDETSENS_MASK;
1013 	acr |= 0x02 & AT91_SAMA5D2_ACR_PENDETSENS_MASK;
1014 	at91_adc_writel(st, ACR, acr);
1015 
1016 	/* Sample Period Time = (TRGPER + 1) / ADCClock */
1017 	st->touch_st.sample_period_val =
1018 				 round_up((AT91_SAMA5D2_TOUCH_SAMPLE_PERIOD_US *
1019 				 clk_khz / 1000) - 1, 1);
1020 	/* enable pen detect IRQ */
1021 	at91_adc_writel(st, IER, AT91_SAMA5D2_IER_PEN);
1022 
1023 	return 0;
1024 }
1025 
at91_adc_touch_pos(struct at91_adc_state * st,int reg)1026 static u16 at91_adc_touch_pos(struct at91_adc_state *st, int reg)
1027 {
1028 	u32 val = 0;
1029 	u32 scale, result, pos;
1030 
1031 	/*
1032 	 * to obtain the actual position we must divide by scale
1033 	 * and multiply with max, where
1034 	 * max = 2^AT91_SAMA5D2_MAX_POS_BITS - 1
1035 	 */
1036 	/* first half of register is the x or y, second half is the scale */
1037 	if (reg == st->soc_info.platform->layout->XPOSR)
1038 		val = at91_adc_readl(st, XPOSR);
1039 	else if (reg == st->soc_info.platform->layout->YPOSR)
1040 		val = at91_adc_readl(st, YPOSR);
1041 
1042 	if (!val)
1043 		dev_dbg(&st->indio_dev->dev, "pos is 0\n");
1044 
1045 	pos = val & AT91_SAMA5D2_XYZ_MASK;
1046 	result = (pos << AT91_SAMA5D2_MAX_POS_BITS) - pos;
1047 	scale = (val >> 16) & AT91_SAMA5D2_XYZ_MASK;
1048 	if (scale == 0) {
1049 		dev_err(&st->indio_dev->dev, "scale is 0\n");
1050 		return 0;
1051 	}
1052 	result /= scale;
1053 
1054 	return result;
1055 }
1056 
at91_adc_touch_x_pos(struct at91_adc_state * st)1057 static u16 at91_adc_touch_x_pos(struct at91_adc_state *st)
1058 {
1059 	st->touch_st.x_pos = at91_adc_touch_pos(st, st->soc_info.platform->layout->XPOSR);
1060 	return st->touch_st.x_pos;
1061 }
1062 
at91_adc_touch_y_pos(struct at91_adc_state * st)1063 static u16 at91_adc_touch_y_pos(struct at91_adc_state *st)
1064 {
1065 	return at91_adc_touch_pos(st, st->soc_info.platform->layout->YPOSR);
1066 }
1067 
at91_adc_touch_pressure(struct at91_adc_state * st)1068 static u16 at91_adc_touch_pressure(struct at91_adc_state *st)
1069 {
1070 	u32 val;
1071 	u32 z1, z2;
1072 	u32 pres;
1073 	u32 rxp = 1;
1074 	u32 factor = 1000;
1075 
1076 	/* calculate the pressure */
1077 	val = at91_adc_readl(st, PRESSR);
1078 	z1 = val & AT91_SAMA5D2_XYZ_MASK;
1079 	z2 = (val >> 16) & AT91_SAMA5D2_XYZ_MASK;
1080 
1081 	if (z1 != 0)
1082 		pres = rxp * (st->touch_st.x_pos * factor / 1024) *
1083 			(z2 * factor / z1 - factor) /
1084 			factor;
1085 	else
1086 		pres = 0xFFFF;       /* no pen contact */
1087 
1088 	/*
1089 	 * The pressure from device grows down, minimum is 0xFFFF, maximum 0x0.
1090 	 * We compute it this way, but let's return it in the expected way,
1091 	 * growing from 0 to 0xFFFF.
1092 	 */
1093 	return 0xFFFF - pres;
1094 }
1095 
at91_adc_read_position(struct at91_adc_state * st,int chan,u16 * val)1096 static int at91_adc_read_position(struct at91_adc_state *st, int chan, u16 *val)
1097 {
1098 	*val = 0;
1099 	if (!st->touch_st.touching)
1100 		return -ENODATA;
1101 	if (chan == st->soc_info.platform->touch_chan_x)
1102 		*val = at91_adc_touch_x_pos(st);
1103 	else if (chan == st->soc_info.platform->touch_chan_y)
1104 		*val = at91_adc_touch_y_pos(st);
1105 	else
1106 		return -ENODATA;
1107 
1108 	return IIO_VAL_INT;
1109 }
1110 
at91_adc_read_pressure(struct at91_adc_state * st,int chan,u16 * val)1111 static int at91_adc_read_pressure(struct at91_adc_state *st, int chan, u16 *val)
1112 {
1113 	*val = 0;
1114 	if (!st->touch_st.touching)
1115 		return -ENODATA;
1116 	if (chan == st->soc_info.platform->touch_chan_p)
1117 		*val = at91_adc_touch_pressure(st);
1118 	else
1119 		return -ENODATA;
1120 
1121 	return IIO_VAL_INT;
1122 }
1123 
at91_adc_configure_trigger_registers(struct at91_adc_state * st,bool state)1124 static void at91_adc_configure_trigger_registers(struct at91_adc_state *st,
1125 						 bool state)
1126 {
1127 	u32 status = at91_adc_readl(st, TRGR);
1128 
1129 	/* clear TRGMOD */
1130 	status &= ~AT91_SAMA5D2_TRGR_TRGMOD_MASK;
1131 
1132 	if (state)
1133 		status |= st->selected_trig->trgmod_value;
1134 
1135 	/* set/unset hw trigger */
1136 	at91_adc_writel(st, TRGR, status);
1137 }
1138 
at91_adc_configure_trigger(struct iio_trigger * trig,bool state)1139 static int at91_adc_configure_trigger(struct iio_trigger *trig, bool state)
1140 {
1141 	struct iio_dev *indio = iio_trigger_get_drvdata(trig);
1142 	struct at91_adc_state *st = iio_priv(indio);
1143 	int ret;
1144 
1145 	if (state) {
1146 		ret = pm_runtime_resume_and_get(st->dev);
1147 		if (ret < 0)
1148 			return ret;
1149 	}
1150 
1151 	at91_adc_configure_trigger_registers(st, state);
1152 
1153 	if (!state) {
1154 		pm_runtime_mark_last_busy(st->dev);
1155 		pm_runtime_put_autosuspend(st->dev);
1156 	}
1157 
1158 	return 0;
1159 }
1160 
at91_adc_reenable_trigger(struct iio_trigger * trig)1161 static void at91_adc_reenable_trigger(struct iio_trigger *trig)
1162 {
1163 	struct iio_dev *indio = iio_trigger_get_drvdata(trig);
1164 	struct at91_adc_state *st = iio_priv(indio);
1165 
1166 	/* if we are using DMA, we must not reenable irq after each trigger */
1167 	if (st->dma_st.dma_chan)
1168 		return;
1169 
1170 	enable_irq(st->irq);
1171 
1172 	/* Needed to ACK the DRDY interruption */
1173 	at91_adc_readl(st, LCDR);
1174 }
1175 
1176 static const struct iio_trigger_ops at91_adc_trigger_ops = {
1177 	.set_trigger_state = &at91_adc_configure_trigger,
1178 	.reenable = &at91_adc_reenable_trigger,
1179 	.validate_device = iio_trigger_validate_own_device,
1180 };
1181 
at91_adc_dma_size_done(struct at91_adc_state * st)1182 static int at91_adc_dma_size_done(struct at91_adc_state *st)
1183 {
1184 	struct dma_tx_state state;
1185 	enum dma_status status;
1186 	int i, size;
1187 
1188 	status = dmaengine_tx_status(st->dma_st.dma_chan,
1189 				     st->dma_st.dma_chan->cookie,
1190 				     &state);
1191 	if (status != DMA_IN_PROGRESS)
1192 		return 0;
1193 
1194 	/* Transferred length is size in bytes from end of buffer */
1195 	i = st->dma_st.rx_buf_sz - state.residue;
1196 
1197 	/* Return available bytes */
1198 	if (i >= st->dma_st.buf_idx)
1199 		size = i - st->dma_st.buf_idx;
1200 	else
1201 		size = st->dma_st.rx_buf_sz + i - st->dma_st.buf_idx;
1202 	return size;
1203 }
1204 
at91_dma_buffer_done(void * data)1205 static void at91_dma_buffer_done(void *data)
1206 {
1207 	struct iio_dev *indio_dev = data;
1208 
1209 	iio_trigger_poll_nested(indio_dev->trig);
1210 }
1211 
at91_adc_dma_start(struct iio_dev * indio_dev)1212 static int at91_adc_dma_start(struct iio_dev *indio_dev)
1213 {
1214 	struct at91_adc_state *st = iio_priv(indio_dev);
1215 	struct dma_async_tx_descriptor *desc;
1216 	dma_cookie_t cookie;
1217 	int ret;
1218 	u8 bit;
1219 
1220 	if (!st->dma_st.dma_chan)
1221 		return 0;
1222 
1223 	/* we start a new DMA, so set buffer index to start */
1224 	st->dma_st.buf_idx = 0;
1225 
1226 	/*
1227 	 * compute buffer size w.r.t. watermark and enabled channels.
1228 	 * scan_bytes is aligned so we need an exact size for DMA
1229 	 */
1230 	st->dma_st.rx_buf_sz = 0;
1231 
1232 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1233 			 indio_dev->num_channels) {
1234 		struct iio_chan_spec const *chan =
1235 					 at91_adc_chan_get(indio_dev, bit);
1236 
1237 		if (!chan)
1238 			continue;
1239 
1240 		st->dma_st.rx_buf_sz += chan->scan_type.storagebits / 8;
1241 	}
1242 	st->dma_st.rx_buf_sz *= st->dma_st.watermark;
1243 
1244 	/* Prepare a DMA cyclic transaction */
1245 	desc = dmaengine_prep_dma_cyclic(st->dma_st.dma_chan,
1246 					 st->dma_st.rx_dma_buf,
1247 					 st->dma_st.rx_buf_sz,
1248 					 st->dma_st.rx_buf_sz / 2,
1249 					 DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT);
1250 
1251 	if (!desc) {
1252 		dev_err(&indio_dev->dev, "cannot prepare DMA cyclic\n");
1253 		return -EBUSY;
1254 	}
1255 
1256 	desc->callback = at91_dma_buffer_done;
1257 	desc->callback_param = indio_dev;
1258 
1259 	cookie = dmaengine_submit(desc);
1260 	ret = dma_submit_error(cookie);
1261 	if (ret) {
1262 		dev_err(&indio_dev->dev, "cannot submit DMA cyclic\n");
1263 		dmaengine_terminate_async(st->dma_st.dma_chan);
1264 		return ret;
1265 	}
1266 
1267 	/* enable general overrun error signaling */
1268 	at91_adc_writel(st, IER, AT91_SAMA5D2_IER_GOVRE);
1269 	/* Issue pending DMA requests */
1270 	dma_async_issue_pending(st->dma_st.dma_chan);
1271 
1272 	/* consider current time as DMA start time for timestamps */
1273 	st->dma_st.dma_ts = iio_get_time_ns(indio_dev);
1274 
1275 	dev_dbg(&indio_dev->dev, "DMA cyclic started\n");
1276 
1277 	return 0;
1278 }
1279 
at91_adc_buffer_check_use_irq(struct iio_dev * indio,struct at91_adc_state * st)1280 static bool at91_adc_buffer_check_use_irq(struct iio_dev *indio,
1281 					  struct at91_adc_state *st)
1282 {
1283 	/* if using DMA, we do not use our own IRQ (we use DMA-controller) */
1284 	if (st->dma_st.dma_chan)
1285 		return false;
1286 	/* if the trigger is not ours, then it has its own IRQ */
1287 	if (iio_trigger_validate_own_device(indio->trig, indio))
1288 		return false;
1289 	return true;
1290 }
1291 
at91_adc_current_chan_is_touch(struct iio_dev * indio_dev)1292 static bool at91_adc_current_chan_is_touch(struct iio_dev *indio_dev)
1293 {
1294 	struct at91_adc_state *st = iio_priv(indio_dev);
1295 
1296 	return !!bitmap_subset(indio_dev->active_scan_mask,
1297 			       &st->touch_st.channels_bitmask,
1298 			       st->soc_info.platform->max_index + 1);
1299 }
1300 
at91_adc_buffer_prepare(struct iio_dev * indio_dev)1301 static int at91_adc_buffer_prepare(struct iio_dev *indio_dev)
1302 {
1303 	int ret;
1304 	u8 bit;
1305 	struct at91_adc_state *st = iio_priv(indio_dev);
1306 
1307 	/* check if we are enabling triggered buffer or the touchscreen */
1308 	if (at91_adc_current_chan_is_touch(indio_dev))
1309 		return at91_adc_configure_touch(st, true);
1310 
1311 	/* if we are not in triggered mode, we cannot enable the buffer. */
1312 	if (!(iio_device_get_current_mode(indio_dev) & INDIO_ALL_TRIGGERED_MODES))
1313 		return -EINVAL;
1314 
1315 	ret = pm_runtime_resume_and_get(st->dev);
1316 	if (ret < 0)
1317 		return ret;
1318 
1319 	/* we continue with the triggered buffer */
1320 	ret = at91_adc_dma_start(indio_dev);
1321 	if (ret) {
1322 		dev_err(&indio_dev->dev, "buffer prepare failed\n");
1323 		goto pm_runtime_put;
1324 	}
1325 
1326 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1327 			 indio_dev->num_channels) {
1328 		struct iio_chan_spec const *chan =
1329 					at91_adc_chan_get(indio_dev, bit);
1330 		if (!chan)
1331 			continue;
1332 		/* these channel types cannot be handled by this trigger */
1333 		if (chan->type == IIO_POSITIONRELATIVE ||
1334 		    chan->type == IIO_PRESSURE ||
1335 		    chan->type == IIO_TEMP)
1336 			continue;
1337 
1338 		at91_adc_cor(st, chan);
1339 
1340 		at91_adc_writel(st, CHER, BIT(chan->channel));
1341 	}
1342 
1343 	if (at91_adc_buffer_check_use_irq(indio_dev, st))
1344 		at91_adc_writel(st, IER, AT91_SAMA5D2_IER_DRDY);
1345 
1346 pm_runtime_put:
1347 	pm_runtime_mark_last_busy(st->dev);
1348 	pm_runtime_put_autosuspend(st->dev);
1349 	return ret;
1350 }
1351 
at91_adc_buffer_postdisable(struct iio_dev * indio_dev)1352 static int at91_adc_buffer_postdisable(struct iio_dev *indio_dev)
1353 {
1354 	struct at91_adc_state *st = iio_priv(indio_dev);
1355 	int ret;
1356 	u8 bit;
1357 
1358 	/* check if we are disabling triggered buffer or the touchscreen */
1359 	if (at91_adc_current_chan_is_touch(indio_dev))
1360 		return at91_adc_configure_touch(st, false);
1361 
1362 	/* if we are not in triggered mode, nothing to do here */
1363 	if (!(iio_device_get_current_mode(indio_dev) & INDIO_ALL_TRIGGERED_MODES))
1364 		return -EINVAL;
1365 
1366 	ret = pm_runtime_resume_and_get(st->dev);
1367 	if (ret < 0)
1368 		return ret;
1369 
1370 	/*
1371 	 * For each enable channel we must disable it in hardware.
1372 	 * In the case of DMA, we must read the last converted value
1373 	 * to clear EOC status and not get a possible interrupt later.
1374 	 * This value is being read by DMA from LCDR anyway, so it's not lost.
1375 	 */
1376 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1377 			 indio_dev->num_channels) {
1378 		struct iio_chan_spec const *chan =
1379 					at91_adc_chan_get(indio_dev, bit);
1380 
1381 		if (!chan)
1382 			continue;
1383 		/* these channel types are virtual, no need to do anything */
1384 		if (chan->type == IIO_POSITIONRELATIVE ||
1385 		    chan->type == IIO_PRESSURE ||
1386 		    chan->type == IIO_TEMP)
1387 			continue;
1388 
1389 		at91_adc_writel(st, CHDR, BIT(chan->channel));
1390 
1391 		if (st->dma_st.dma_chan)
1392 			at91_adc_read_chan(st, chan->address);
1393 	}
1394 
1395 	if (at91_adc_buffer_check_use_irq(indio_dev, st))
1396 		at91_adc_writel(st, IDR, AT91_SAMA5D2_IER_DRDY);
1397 
1398 	/* read overflow register to clear possible overflow status */
1399 	at91_adc_readl(st, OVER);
1400 
1401 	/* if we are using DMA we must clear registers and end DMA */
1402 	if (st->dma_st.dma_chan)
1403 		dmaengine_terminate_sync(st->dma_st.dma_chan);
1404 
1405 	pm_runtime_mark_last_busy(st->dev);
1406 	pm_runtime_put_autosuspend(st->dev);
1407 
1408 	return 0;
1409 }
1410 
1411 static const struct iio_buffer_setup_ops at91_buffer_setup_ops = {
1412 	.postdisable = &at91_adc_buffer_postdisable,
1413 };
1414 
at91_adc_allocate_trigger(struct iio_dev * indio,char * trigger_name)1415 static struct iio_trigger *at91_adc_allocate_trigger(struct iio_dev *indio,
1416 						     char *trigger_name)
1417 {
1418 	struct iio_trigger *trig;
1419 	int ret;
1420 
1421 	trig = devm_iio_trigger_alloc(&indio->dev, "%s-dev%d-%s", indio->name,
1422 				iio_device_id(indio), trigger_name);
1423 	if (!trig)
1424 		return ERR_PTR(-ENOMEM);
1425 
1426 	trig->dev.parent = indio->dev.parent;
1427 	iio_trigger_set_drvdata(trig, indio);
1428 	trig->ops = &at91_adc_trigger_ops;
1429 
1430 	ret = devm_iio_trigger_register(&indio->dev, trig);
1431 	if (ret)
1432 		return ERR_PTR(ret);
1433 
1434 	return trig;
1435 }
1436 
at91_adc_trigger_handler_nodma(struct iio_dev * indio_dev,struct iio_poll_func * pf)1437 static void at91_adc_trigger_handler_nodma(struct iio_dev *indio_dev,
1438 					   struct iio_poll_func *pf)
1439 {
1440 	struct at91_adc_state *st = iio_priv(indio_dev);
1441 	int i = 0;
1442 	int val;
1443 	u8 bit;
1444 	u32 mask = at91_adc_active_scan_mask_to_reg(indio_dev);
1445 	unsigned int timeout = 50;
1446 	u32 status, imr, eoc = 0, eoc_imr;
1447 
1448 	/*
1449 	 * Check if the conversion is ready. If not, wait a little bit, and
1450 	 * in case of timeout exit with an error.
1451 	 */
1452 	while (((eoc & mask) != mask) && timeout) {
1453 		at91_adc_irq_status(st, &status, &eoc);
1454 		at91_adc_irq_mask(st, &imr, &eoc_imr);
1455 		usleep_range(50, 100);
1456 		timeout--;
1457 	}
1458 
1459 	/* Cannot read data, not ready. Continue without reporting data */
1460 	if (!timeout)
1461 		return;
1462 
1463 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1464 			 indio_dev->num_channels) {
1465 		struct iio_chan_spec const *chan =
1466 					at91_adc_chan_get(indio_dev, bit);
1467 
1468 		if (!chan)
1469 			continue;
1470 		/*
1471 		 * Our external trigger only supports the voltage channels.
1472 		 * In case someone requested a different type of channel
1473 		 * just put zeroes to buffer.
1474 		 * This should not happen because we check the scan mode
1475 		 * and scan mask when we enable the buffer, and we don't allow
1476 		 * the buffer to start with a mixed mask (voltage and something
1477 		 * else).
1478 		 * Thus, emit a warning.
1479 		 */
1480 		if (chan->type == IIO_VOLTAGE) {
1481 			val = at91_adc_read_chan(st, chan->address);
1482 			at91_adc_adjust_val_osr(st, &val);
1483 			st->buffer[i] = val;
1484 		} else {
1485 			st->buffer[i] = 0;
1486 			WARN(true, "This trigger cannot handle this type of channel");
1487 		}
1488 		i++;
1489 	}
1490 	iio_push_to_buffers_with_timestamp(indio_dev, st->buffer,
1491 					   pf->timestamp);
1492 }
1493 
at91_adc_trigger_handler_dma(struct iio_dev * indio_dev)1494 static void at91_adc_trigger_handler_dma(struct iio_dev *indio_dev)
1495 {
1496 	struct at91_adc_state *st = iio_priv(indio_dev);
1497 	int transferred_len = at91_adc_dma_size_done(st);
1498 	s64 ns = iio_get_time_ns(indio_dev);
1499 	s64 interval;
1500 	int sample_index = 0, sample_count, sample_size;
1501 
1502 	u32 status = at91_adc_readl(st, ISR);
1503 	/* if we reached this point, we cannot sample faster */
1504 	if (status & AT91_SAMA5D2_IER_GOVRE)
1505 		pr_info_ratelimited("%s: conversion overrun detected\n",
1506 				    indio_dev->name);
1507 
1508 	sample_size = div_s64(st->dma_st.rx_buf_sz, st->dma_st.watermark);
1509 
1510 	sample_count = div_s64(transferred_len, sample_size);
1511 
1512 	/*
1513 	 * interval between samples is total time since last transfer handling
1514 	 * divided by the number of samples (total size divided by sample size)
1515 	 */
1516 	interval = div_s64((ns - st->dma_st.dma_ts), sample_count);
1517 
1518 	while (transferred_len >= sample_size) {
1519 		/*
1520 		 * for all the values in the current sample,
1521 		 * adjust the values inside the buffer for oversampling
1522 		 */
1523 		at91_adc_adjust_val_osr_array(st,
1524 					&st->dma_st.rx_buf[st->dma_st.buf_idx],
1525 					sample_size);
1526 
1527 		iio_push_to_buffers_with_timestamp(indio_dev,
1528 				(st->dma_st.rx_buf + st->dma_st.buf_idx),
1529 				(st->dma_st.dma_ts + interval * sample_index));
1530 		/* adjust remaining length */
1531 		transferred_len -= sample_size;
1532 		/* adjust buffer index */
1533 		st->dma_st.buf_idx += sample_size;
1534 		/* in case of reaching end of buffer, reset index */
1535 		if (st->dma_st.buf_idx >= st->dma_st.rx_buf_sz)
1536 			st->dma_st.buf_idx = 0;
1537 		sample_index++;
1538 	}
1539 	/* adjust saved time for next transfer handling */
1540 	st->dma_st.dma_ts = iio_get_time_ns(indio_dev);
1541 }
1542 
at91_adc_trigger_handler(int irq,void * p)1543 static irqreturn_t at91_adc_trigger_handler(int irq, void *p)
1544 {
1545 	struct iio_poll_func *pf = p;
1546 	struct iio_dev *indio_dev = pf->indio_dev;
1547 	struct at91_adc_state *st = iio_priv(indio_dev);
1548 
1549 	/*
1550 	 * If it's not our trigger, start a conversion now, as we are
1551 	 * actually polling the trigger now.
1552 	 */
1553 	if (iio_trigger_validate_own_device(indio_dev->trig, indio_dev))
1554 		at91_adc_writel(st, CR, AT91_SAMA5D2_CR_START);
1555 
1556 	if (st->dma_st.dma_chan)
1557 		at91_adc_trigger_handler_dma(indio_dev);
1558 	else
1559 		at91_adc_trigger_handler_nodma(indio_dev, pf);
1560 
1561 	iio_trigger_notify_done(indio_dev->trig);
1562 
1563 	return IRQ_HANDLED;
1564 }
1565 
at91_adc_startup_time(unsigned startup_time_min,unsigned adc_clk_khz)1566 static unsigned at91_adc_startup_time(unsigned startup_time_min,
1567 				      unsigned adc_clk_khz)
1568 {
1569 	static const unsigned int startup_lookup[] = {
1570 		  0,   8,  16,  24,
1571 		 64,  80,  96, 112,
1572 		512, 576, 640, 704,
1573 		768, 832, 896, 960
1574 		};
1575 	unsigned ticks_min, i;
1576 
1577 	/*
1578 	 * Since the adc frequency is checked before, there is no reason
1579 	 * to not meet the startup time constraint.
1580 	 */
1581 
1582 	ticks_min = startup_time_min * adc_clk_khz / 1000;
1583 	for (i = 0; i < ARRAY_SIZE(startup_lookup); i++)
1584 		if (startup_lookup[i] > ticks_min)
1585 			break;
1586 
1587 	return i;
1588 }
1589 
at91_adc_setup_samp_freq(struct iio_dev * indio_dev,unsigned freq,unsigned int startup_time,unsigned int tracktim)1590 static void at91_adc_setup_samp_freq(struct iio_dev *indio_dev, unsigned freq,
1591 				     unsigned int startup_time,
1592 				     unsigned int tracktim)
1593 {
1594 	struct at91_adc_state *st = iio_priv(indio_dev);
1595 	unsigned f_per, prescal, startup, mr;
1596 	int ret;
1597 
1598 	f_per = clk_get_rate(st->per_clk);
1599 	prescal = (f_per / (2 * freq)) - 1;
1600 
1601 	startup = at91_adc_startup_time(startup_time, freq / 1000);
1602 
1603 	ret = pm_runtime_resume_and_get(st->dev);
1604 	if (ret < 0)
1605 		return;
1606 
1607 	mr = at91_adc_readl(st, MR);
1608 	mr &= ~(AT91_SAMA5D2_MR_STARTUP_MASK | AT91_SAMA5D2_MR_PRESCAL_MASK);
1609 	mr |= AT91_SAMA5D2_MR_STARTUP(startup);
1610 	mr |= AT91_SAMA5D2_MR_PRESCAL(prescal);
1611 	mr |= AT91_SAMA5D2_MR_TRACKTIM(tracktim);
1612 	at91_adc_writel(st, MR, mr);
1613 
1614 	pm_runtime_mark_last_busy(st->dev);
1615 	pm_runtime_put_autosuspend(st->dev);
1616 
1617 	dev_dbg(&indio_dev->dev, "freq: %u, startup: %u, prescal: %u, tracktim=%u\n",
1618 		freq, startup, prescal, tracktim);
1619 	st->current_sample_rate = freq;
1620 }
1621 
at91_adc_get_sample_freq(struct at91_adc_state * st)1622 static inline unsigned at91_adc_get_sample_freq(struct at91_adc_state *st)
1623 {
1624 	return st->current_sample_rate;
1625 }
1626 
at91_adc_touch_data_handler(struct iio_dev * indio_dev)1627 static void at91_adc_touch_data_handler(struct iio_dev *indio_dev)
1628 {
1629 	struct at91_adc_state *st = iio_priv(indio_dev);
1630 	u8 bit;
1631 	u16 val;
1632 	int i = 0;
1633 
1634 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1635 			 st->soc_info.platform->max_index + 1) {
1636 		struct iio_chan_spec const *chan =
1637 					 at91_adc_chan_get(indio_dev, bit);
1638 
1639 		if (chan->type == IIO_POSITIONRELATIVE)
1640 			at91_adc_read_position(st, chan->channel, &val);
1641 		else if (chan->type == IIO_PRESSURE)
1642 			at91_adc_read_pressure(st, chan->channel, &val);
1643 		else
1644 			continue;
1645 		st->buffer[i] = val;
1646 		i++;
1647 	}
1648 	/*
1649 	 * Schedule work to push to buffers.
1650 	 * This is intended to push to the callback buffer that another driver
1651 	 * registered. We are still in a handler from our IRQ. If we push
1652 	 * directly, it means the other driver has it's callback called
1653 	 * from our IRQ context. Which is something we better avoid.
1654 	 * Let's schedule it after our IRQ is completed.
1655 	 */
1656 	schedule_work(&st->touch_st.workq);
1657 }
1658 
at91_adc_pen_detect_interrupt(struct at91_adc_state * st)1659 static void at91_adc_pen_detect_interrupt(struct at91_adc_state *st)
1660 {
1661 	at91_adc_writel(st, IDR, AT91_SAMA5D2_IER_PEN);
1662 	at91_adc_writel(st, IER, AT91_SAMA5D2_IER_NOPEN |
1663 			AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1664 			AT91_SAMA5D2_IER_PRDY);
1665 	at91_adc_writel(st, TRGR, AT91_SAMA5D2_TRGR_TRGMOD_PERIODIC |
1666 			AT91_SAMA5D2_TRGR_TRGPER(st->touch_st.sample_period_val));
1667 	st->touch_st.touching = true;
1668 }
1669 
at91_adc_no_pen_detect_interrupt(struct iio_dev * indio_dev)1670 static void at91_adc_no_pen_detect_interrupt(struct iio_dev *indio_dev)
1671 {
1672 	struct at91_adc_state *st = iio_priv(indio_dev);
1673 
1674 	at91_adc_writel(st, TRGR, AT91_SAMA5D2_TRGR_TRGMOD_NO_TRIGGER);
1675 	at91_adc_writel(st, IDR, AT91_SAMA5D2_IER_NOPEN |
1676 			AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1677 			AT91_SAMA5D2_IER_PRDY);
1678 	st->touch_st.touching = false;
1679 
1680 	at91_adc_touch_data_handler(indio_dev);
1681 
1682 	at91_adc_writel(st, IER, AT91_SAMA5D2_IER_PEN);
1683 }
1684 
at91_adc_workq_handler(struct work_struct * workq)1685 static void at91_adc_workq_handler(struct work_struct *workq)
1686 {
1687 	struct at91_adc_touch *touch_st = container_of(workq,
1688 					struct at91_adc_touch, workq);
1689 	struct at91_adc_state *st = container_of(touch_st,
1690 					struct at91_adc_state, touch_st);
1691 	struct iio_dev *indio_dev = st->indio_dev;
1692 
1693 	iio_push_to_buffers(indio_dev, st->buffer);
1694 }
1695 
at91_adc_interrupt(int irq,void * private)1696 static irqreturn_t at91_adc_interrupt(int irq, void *private)
1697 {
1698 	struct iio_dev *indio = private;
1699 	struct at91_adc_state *st = iio_priv(indio);
1700 	u32 status, eoc, imr, eoc_imr;
1701 	u32 rdy_mask = AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1702 			AT91_SAMA5D2_IER_PRDY;
1703 
1704 	at91_adc_irq_status(st, &status, &eoc);
1705 	at91_adc_irq_mask(st, &imr, &eoc_imr);
1706 
1707 	if (!(status & imr) && !(eoc & eoc_imr))
1708 		return IRQ_NONE;
1709 	if (status & AT91_SAMA5D2_IER_PEN) {
1710 		/* pen detected IRQ */
1711 		at91_adc_pen_detect_interrupt(st);
1712 	} else if ((status & AT91_SAMA5D2_IER_NOPEN)) {
1713 		/* nopen detected IRQ */
1714 		at91_adc_no_pen_detect_interrupt(indio);
1715 	} else if ((status & AT91_SAMA5D2_ISR_PENS) &&
1716 		   ((status & rdy_mask) == rdy_mask)) {
1717 		/* periodic trigger IRQ - during pen sense */
1718 		at91_adc_touch_data_handler(indio);
1719 	} else if (status & AT91_SAMA5D2_ISR_PENS) {
1720 		/*
1721 		 * touching, but the measurements are not ready yet.
1722 		 * read and ignore.
1723 		 */
1724 		status = at91_adc_readl(st, XPOSR);
1725 		status = at91_adc_readl(st, YPOSR);
1726 		status = at91_adc_readl(st, PRESSR);
1727 	} else if (iio_buffer_enabled(indio) &&
1728 		   (status & AT91_SAMA5D2_IER_DRDY)) {
1729 		/* triggered buffer without DMA */
1730 		disable_irq_nosync(irq);
1731 		iio_trigger_poll(indio->trig);
1732 	} else if (iio_buffer_enabled(indio) && st->dma_st.dma_chan) {
1733 		/* triggered buffer with DMA - should not happen */
1734 		disable_irq_nosync(irq);
1735 		WARN(true, "Unexpected irq occurred\n");
1736 	} else if (!iio_buffer_enabled(indio)) {
1737 		/* software requested conversion */
1738 		st->conversion_value = at91_adc_read_chan(st, st->chan->address);
1739 		st->conversion_done = true;
1740 		wake_up_interruptible(&st->wq_data_available);
1741 	}
1742 	return IRQ_HANDLED;
1743 }
1744 
1745 /* 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)1746 static int at91_adc_read_info_raw(struct iio_dev *indio_dev,
1747 				  struct iio_chan_spec const *chan, int *val)
1748 {
1749 	struct at91_adc_state *st = iio_priv(indio_dev);
1750 	u16 tmp_val;
1751 	int ret;
1752 
1753 	ret = pm_runtime_resume_and_get(st->dev);
1754 	if (ret < 0)
1755 		return ret;
1756 
1757 	/*
1758 	 * Keep in mind that we cannot use software trigger or touchscreen
1759 	 * if external trigger is enabled
1760 	 */
1761 	if (chan->type == IIO_POSITIONRELATIVE) {
1762 		ret = at91_adc_read_position(st, chan->channel,
1763 					     &tmp_val);
1764 		*val = tmp_val;
1765 		if (ret > 0)
1766 			ret = at91_adc_adjust_val_osr(st, val);
1767 
1768 		goto pm_runtime_put;
1769 	}
1770 	if (chan->type == IIO_PRESSURE) {
1771 		ret = at91_adc_read_pressure(st, chan->channel,
1772 					     &tmp_val);
1773 		*val = tmp_val;
1774 		if (ret > 0)
1775 			ret = at91_adc_adjust_val_osr(st, val);
1776 
1777 		goto pm_runtime_put;
1778 	}
1779 
1780 	/* in this case we have a voltage or temperature channel */
1781 
1782 	st->chan = chan;
1783 
1784 	at91_adc_cor(st, chan);
1785 	at91_adc_writel(st, CHER, BIT(chan->channel));
1786 	/*
1787 	 * TEMPMR.TEMPON needs to update after CHER otherwise if none
1788 	 * of the channels are enabled and TEMPMR.TEMPON = 1 will
1789 	 * trigger DRDY interruption while preparing for temperature read.
1790 	 */
1791 	if (chan->type == IIO_TEMP)
1792 		at91_adc_writel(st, TEMPMR, AT91_SAMA5D2_TEMPMR_TEMPON);
1793 	at91_adc_eoc_ena(st, chan->channel);
1794 	at91_adc_writel(st, CR, AT91_SAMA5D2_CR_START);
1795 
1796 	ret = wait_event_interruptible_timeout(st->wq_data_available,
1797 					       st->conversion_done,
1798 					       msecs_to_jiffies(1000));
1799 	if (ret == 0)
1800 		ret = -ETIMEDOUT;
1801 
1802 	if (ret > 0) {
1803 		*val = st->conversion_value;
1804 		ret = at91_adc_adjust_val_osr(st, val);
1805 		if (chan->scan_type.sign == 's')
1806 			*val = sign_extend32(*val,
1807 					     chan->scan_type.realbits - 1);
1808 		st->conversion_done = false;
1809 	}
1810 
1811 	at91_adc_eoc_dis(st, st->chan->channel);
1812 	if (chan->type == IIO_TEMP)
1813 		at91_adc_writel(st, TEMPMR, 0U);
1814 	at91_adc_writel(st, CHDR, BIT(chan->channel));
1815 
1816 	/* Needed to ACK the DRDY interruption */
1817 	at91_adc_readl(st, LCDR);
1818 
1819 pm_runtime_put:
1820 	pm_runtime_mark_last_busy(st->dev);
1821 	pm_runtime_put_autosuspend(st->dev);
1822 	return ret;
1823 }
1824 
at91_adc_read_info_locked(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val)1825 static int at91_adc_read_info_locked(struct iio_dev *indio_dev,
1826 				     struct iio_chan_spec const *chan, int *val)
1827 {
1828 	struct at91_adc_state *st = iio_priv(indio_dev);
1829 	int ret;
1830 
1831 	ret = iio_device_claim_direct_mode(indio_dev);
1832 	if (ret)
1833 		return ret;
1834 
1835 	mutex_lock(&st->lock);
1836 	ret = at91_adc_read_info_raw(indio_dev, chan, val);
1837 	mutex_unlock(&st->lock);
1838 
1839 	iio_device_release_direct_mode(indio_dev);
1840 
1841 	return ret;
1842 }
1843 
at91_adc_temp_sensor_configure(struct at91_adc_state * st,bool start)1844 static void at91_adc_temp_sensor_configure(struct at91_adc_state *st,
1845 					   bool start)
1846 {
1847 	u32 sample_rate, oversampling_ratio;
1848 	u32 startup_time, tracktim, trackx;
1849 
1850 	if (start) {
1851 		/*
1852 		 * Configure the sensor for best accuracy: 10MHz frequency,
1853 		 * oversampling rate of 256, tracktim=0xf and trackx=1.
1854 		 */
1855 		sample_rate = 10 * MEGA;
1856 		oversampling_ratio = 256;
1857 		startup_time = AT91_SAMA5D2_MR_STARTUP_TS_MIN;
1858 		tracktim = AT91_SAMA5D2_MR_TRACKTIM_TS;
1859 		trackx = AT91_SAMA5D2_TRACKX_TS;
1860 
1861 		st->temp_st.saved_sample_rate = st->current_sample_rate;
1862 		st->temp_st.saved_oversampling = st->oversampling_ratio;
1863 	} else {
1864 		/* Go back to previous settings. */
1865 		sample_rate = st->temp_st.saved_sample_rate;
1866 		oversampling_ratio = st->temp_st.saved_oversampling;
1867 		startup_time = st->soc_info.startup_time;
1868 		tracktim = 0;
1869 		trackx = 0;
1870 	}
1871 
1872 	at91_adc_setup_samp_freq(st->indio_dev, sample_rate, startup_time,
1873 				 tracktim);
1874 	at91_adc_config_emr(st, oversampling_ratio, trackx);
1875 }
1876 
at91_adc_read_temp(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val)1877 static int at91_adc_read_temp(struct iio_dev *indio_dev,
1878 			      struct iio_chan_spec const *chan, int *val)
1879 {
1880 	struct at91_adc_state *st = iio_priv(indio_dev);
1881 	struct at91_adc_temp_sensor_clb *clb = &st->soc_info.temp_sensor_clb;
1882 	u64 div1, div2;
1883 	u32 tmp;
1884 	int ret, vbg, vtemp;
1885 
1886 	ret = iio_device_claim_direct_mode(indio_dev);
1887 	if (ret)
1888 		return ret;
1889 	mutex_lock(&st->lock);
1890 
1891 	ret = pm_runtime_resume_and_get(st->dev);
1892 	if (ret < 0)
1893 		goto unlock;
1894 
1895 	at91_adc_temp_sensor_configure(st, true);
1896 
1897 	/* Read VBG. */
1898 	tmp = at91_adc_readl(st, ACR);
1899 	tmp |= AT91_SAMA5D2_ACR_SRCLCH;
1900 	at91_adc_writel(st, ACR, tmp);
1901 	ret = at91_adc_read_info_raw(indio_dev, chan, &vbg);
1902 	if (ret < 0)
1903 		goto restore_config;
1904 
1905 	/* Read VTEMP. */
1906 	tmp &= ~AT91_SAMA5D2_ACR_SRCLCH;
1907 	at91_adc_writel(st, ACR, tmp);
1908 	ret = at91_adc_read_info_raw(indio_dev, chan, &vtemp);
1909 
1910 restore_config:
1911 	/* Revert previous settings. */
1912 	at91_adc_temp_sensor_configure(st, false);
1913 	pm_runtime_mark_last_busy(st->dev);
1914 	pm_runtime_put_autosuspend(st->dev);
1915 unlock:
1916 	mutex_unlock(&st->lock);
1917 	iio_device_release_direct_mode(indio_dev);
1918 	if (ret < 0)
1919 		return ret;
1920 
1921 	/*
1922 	 * Temp[milli] = p1[milli] + (vtemp * clb->p6 - clb->p4 * vbg)/
1923 	 *			     (vbg * AT91_ADC_TS_VTEMP_DT)
1924 	 */
1925 	div1 = DIV_ROUND_CLOSEST_ULL(((u64)vtemp * clb->p6), vbg);
1926 	div1 = DIV_ROUND_CLOSEST_ULL((div1 * 1000), AT91_ADC_TS_VTEMP_DT);
1927 	div2 = DIV_ROUND_CLOSEST_ULL((u64)clb->p4, AT91_ADC_TS_VTEMP_DT);
1928 	div2 *= 1000;
1929 	*val = clb->p1 + (int)div1 - (int)div2;
1930 
1931 	return ret;
1932 }
1933 
at91_adc_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)1934 static int at91_adc_read_raw(struct iio_dev *indio_dev,
1935 			     struct iio_chan_spec const *chan,
1936 			     int *val, int *val2, long mask)
1937 {
1938 	struct at91_adc_state *st = iio_priv(indio_dev);
1939 
1940 	switch (mask) {
1941 	case IIO_CHAN_INFO_RAW:
1942 		return at91_adc_read_info_locked(indio_dev, chan, val);
1943 
1944 	case IIO_CHAN_INFO_SCALE:
1945 		*val = st->vref_uv / 1000;
1946 		if (chan->differential)
1947 			*val *= 2;
1948 		*val2 = chan->scan_type.realbits;
1949 		return IIO_VAL_FRACTIONAL_LOG2;
1950 
1951 	case IIO_CHAN_INFO_PROCESSED:
1952 		if (chan->type != IIO_TEMP)
1953 			return -EINVAL;
1954 		return at91_adc_read_temp(indio_dev, chan, val);
1955 
1956 	case IIO_CHAN_INFO_SAMP_FREQ:
1957 		*val = at91_adc_get_sample_freq(st);
1958 		return IIO_VAL_INT;
1959 
1960 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1961 		*val = st->oversampling_ratio;
1962 		return IIO_VAL_INT;
1963 
1964 	default:
1965 		return -EINVAL;
1966 	}
1967 }
1968 
at91_adc_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)1969 static int at91_adc_write_raw(struct iio_dev *indio_dev,
1970 			      struct iio_chan_spec const *chan,
1971 			      int val, int val2, long mask)
1972 {
1973 	struct at91_adc_state *st = iio_priv(indio_dev);
1974 	int ret;
1975 
1976 	switch (mask) {
1977 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1978 		/* if no change, optimize out */
1979 		if (val == st->oversampling_ratio)
1980 			return 0;
1981 
1982 		ret = iio_device_claim_direct_mode(indio_dev);
1983 		if (ret)
1984 			return ret;
1985 		mutex_lock(&st->lock);
1986 		/* update ratio */
1987 		ret = at91_adc_config_emr(st, val, 0);
1988 		mutex_unlock(&st->lock);
1989 		iio_device_release_direct_mode(indio_dev);
1990 		return ret;
1991 	case IIO_CHAN_INFO_SAMP_FREQ:
1992 		if (val < st->soc_info.min_sample_rate ||
1993 		    val > st->soc_info.max_sample_rate)
1994 			return -EINVAL;
1995 
1996 		ret = iio_device_claim_direct_mode(indio_dev);
1997 		if (ret)
1998 			return ret;
1999 		mutex_lock(&st->lock);
2000 		at91_adc_setup_samp_freq(indio_dev, val,
2001 					 st->soc_info.startup_time, 0);
2002 		mutex_unlock(&st->lock);
2003 		iio_device_release_direct_mode(indio_dev);
2004 		return 0;
2005 	default:
2006 		return -EINVAL;
2007 	}
2008 }
2009 
at91_adc_read_avail(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,const int ** vals,int * type,int * length,long mask)2010 static int at91_adc_read_avail(struct iio_dev *indio_dev,
2011 			       struct iio_chan_spec const *chan,
2012 			       const int **vals, int *type, int *length,
2013 			       long mask)
2014 {
2015 	struct at91_adc_state *st = iio_priv(indio_dev);
2016 
2017 	switch (mask) {
2018 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
2019 		*vals = (int *)st->soc_info.platform->oversampling_avail;
2020 		*type = IIO_VAL_INT;
2021 		*length = st->soc_info.platform->oversampling_avail_no;
2022 		return IIO_AVAIL_LIST;
2023 	default:
2024 		return -EINVAL;
2025 	}
2026 }
2027 
at91_adc_dma_init(struct at91_adc_state * st)2028 static void at91_adc_dma_init(struct at91_adc_state *st)
2029 {
2030 	struct device *dev = &st->indio_dev->dev;
2031 	struct dma_slave_config config = {0};
2032 	/* we have 2 bytes for each channel */
2033 	unsigned int sample_size = st->soc_info.platform->nr_channels * 2;
2034 	/*
2035 	 * We make the buffer double the size of the fifo,
2036 	 * such that DMA uses one half of the buffer (full fifo size)
2037 	 * and the software uses the other half to read/write.
2038 	 */
2039 	unsigned int pages = DIV_ROUND_UP(AT91_HWFIFO_MAX_SIZE *
2040 					  sample_size * 2, PAGE_SIZE);
2041 
2042 	if (st->dma_st.dma_chan)
2043 		return;
2044 
2045 	st->dma_st.dma_chan = dma_request_chan(dev, "rx");
2046 	if (IS_ERR(st->dma_st.dma_chan))  {
2047 		dev_info(dev, "can't get DMA channel\n");
2048 		st->dma_st.dma_chan = NULL;
2049 		goto dma_exit;
2050 	}
2051 
2052 	st->dma_st.rx_buf = dma_alloc_coherent(st->dma_st.dma_chan->device->dev,
2053 					       pages * PAGE_SIZE,
2054 					       &st->dma_st.rx_dma_buf,
2055 					       GFP_KERNEL);
2056 	if (!st->dma_st.rx_buf) {
2057 		dev_info(dev, "can't allocate coherent DMA area\n");
2058 		goto dma_chan_disable;
2059 	}
2060 
2061 	/* Configure DMA channel to read data register */
2062 	config.direction = DMA_DEV_TO_MEM;
2063 	config.src_addr = (phys_addr_t)(st->dma_st.phys_addr
2064 			  + st->soc_info.platform->layout->LCDR);
2065 	config.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
2066 	config.src_maxburst = 1;
2067 	config.dst_maxburst = 1;
2068 
2069 	if (dmaengine_slave_config(st->dma_st.dma_chan, &config)) {
2070 		dev_info(dev, "can't configure DMA slave\n");
2071 		goto dma_free_area;
2072 	}
2073 
2074 	dev_info(dev, "using %s for rx DMA transfers\n",
2075 		 dma_chan_name(st->dma_st.dma_chan));
2076 
2077 	return;
2078 
2079 dma_free_area:
2080 	dma_free_coherent(st->dma_st.dma_chan->device->dev, pages * PAGE_SIZE,
2081 			  st->dma_st.rx_buf, st->dma_st.rx_dma_buf);
2082 dma_chan_disable:
2083 	dma_release_channel(st->dma_st.dma_chan);
2084 	st->dma_st.dma_chan = NULL;
2085 dma_exit:
2086 	dev_info(dev, "continuing without DMA support\n");
2087 }
2088 
at91_adc_dma_disable(struct at91_adc_state * st)2089 static void at91_adc_dma_disable(struct at91_adc_state *st)
2090 {
2091 	struct device *dev = &st->indio_dev->dev;
2092 	/* we have 2 bytes for each channel */
2093 	unsigned int sample_size = st->soc_info.platform->nr_channels * 2;
2094 	unsigned int pages = DIV_ROUND_UP(AT91_HWFIFO_MAX_SIZE *
2095 					  sample_size * 2, PAGE_SIZE);
2096 
2097 	/* if we are not using DMA, just return */
2098 	if (!st->dma_st.dma_chan)
2099 		return;
2100 
2101 	/* wait for all transactions to be terminated first*/
2102 	dmaengine_terminate_sync(st->dma_st.dma_chan);
2103 
2104 	dma_free_coherent(st->dma_st.dma_chan->device->dev, pages * PAGE_SIZE,
2105 			  st->dma_st.rx_buf, st->dma_st.rx_dma_buf);
2106 	dma_release_channel(st->dma_st.dma_chan);
2107 	st->dma_st.dma_chan = NULL;
2108 
2109 	dev_info(dev, "continuing without DMA support\n");
2110 }
2111 
at91_adc_set_watermark(struct iio_dev * indio_dev,unsigned int val)2112 static int at91_adc_set_watermark(struct iio_dev *indio_dev, unsigned int val)
2113 {
2114 	struct at91_adc_state *st = iio_priv(indio_dev);
2115 	int ret;
2116 
2117 	if (val > AT91_HWFIFO_MAX_SIZE)
2118 		val = AT91_HWFIFO_MAX_SIZE;
2119 
2120 	if (!st->selected_trig->hw_trig) {
2121 		dev_dbg(&indio_dev->dev, "we need hw trigger for DMA\n");
2122 		return 0;
2123 	}
2124 
2125 	dev_dbg(&indio_dev->dev, "new watermark is %u\n", val);
2126 	st->dma_st.watermark = val;
2127 
2128 	/*
2129 	 * The logic here is: if we have watermark 1, it means we do
2130 	 * each conversion with it's own IRQ, thus we don't need DMA.
2131 	 * If the watermark is higher, we do DMA to do all the transfers in bulk
2132 	 */
2133 
2134 	if (val == 1)
2135 		at91_adc_dma_disable(st);
2136 	else if (val > 1)
2137 		at91_adc_dma_init(st);
2138 
2139 	/*
2140 	 * We can start the DMA only after setting the watermark and
2141 	 * having the DMA initialization completed
2142 	 */
2143 	ret = at91_adc_buffer_prepare(indio_dev);
2144 	if (ret)
2145 		at91_adc_dma_disable(st);
2146 
2147 	return ret;
2148 }
2149 
at91_adc_update_scan_mode(struct iio_dev * indio_dev,const unsigned long * scan_mask)2150 static int at91_adc_update_scan_mode(struct iio_dev *indio_dev,
2151 				     const unsigned long *scan_mask)
2152 {
2153 	struct at91_adc_state *st = iio_priv(indio_dev);
2154 
2155 	if (bitmap_subset(scan_mask, &st->touch_st.channels_bitmask,
2156 			  st->soc_info.platform->max_index + 1))
2157 		return 0;
2158 	/*
2159 	 * if the new bitmap is a combination of touchscreen and regular
2160 	 * channels, then we are not fine
2161 	 */
2162 	if (bitmap_intersects(&st->touch_st.channels_bitmask, scan_mask,
2163 			      st->soc_info.platform->max_index + 1))
2164 		return -EINVAL;
2165 	return 0;
2166 }
2167 
at91_adc_hw_init(struct iio_dev * indio_dev)2168 static void at91_adc_hw_init(struct iio_dev *indio_dev)
2169 {
2170 	struct at91_adc_state *st = iio_priv(indio_dev);
2171 
2172 	at91_adc_writel(st, CR, AT91_SAMA5D2_CR_SWRST);
2173 	if (st->soc_info.platform->layout->EOC_IDR)
2174 		at91_adc_writel(st, EOC_IDR, 0xffffffff);
2175 	at91_adc_writel(st, IDR, 0xffffffff);
2176 	/*
2177 	 * Transfer field must be set to 2 according to the datasheet and
2178 	 * allows different analog settings for each channel.
2179 	 */
2180 	at91_adc_writel(st, MR,
2181 			AT91_SAMA5D2_MR_TRANSFER(2) | AT91_SAMA5D2_MR_ANACH);
2182 
2183 	at91_adc_setup_samp_freq(indio_dev, st->soc_info.min_sample_rate,
2184 				 st->soc_info.startup_time, 0);
2185 
2186 	/* configure extended mode register */
2187 	at91_adc_config_emr(st, st->oversampling_ratio, 0);
2188 }
2189 
at91_adc_get_fifo_state(struct device * dev,struct device_attribute * attr,char * buf)2190 static ssize_t at91_adc_get_fifo_state(struct device *dev,
2191 				       struct device_attribute *attr, char *buf)
2192 {
2193 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
2194 	struct at91_adc_state *st = iio_priv(indio_dev);
2195 
2196 	return sysfs_emit(buf, "%d\n", !!st->dma_st.dma_chan);
2197 }
2198 
at91_adc_get_watermark(struct device * dev,struct device_attribute * attr,char * buf)2199 static ssize_t at91_adc_get_watermark(struct device *dev,
2200 				      struct device_attribute *attr, char *buf)
2201 {
2202 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
2203 	struct at91_adc_state *st = iio_priv(indio_dev);
2204 
2205 	return sysfs_emit(buf, "%d\n", st->dma_st.watermark);
2206 }
2207 
2208 static IIO_DEVICE_ATTR(hwfifo_enabled, 0444,
2209 		       at91_adc_get_fifo_state, NULL, 0);
2210 static IIO_DEVICE_ATTR(hwfifo_watermark, 0444,
2211 		       at91_adc_get_watermark, NULL, 0);
2212 
2213 IIO_STATIC_CONST_DEVICE_ATTR(hwfifo_watermark_min, "2");
2214 IIO_STATIC_CONST_DEVICE_ATTR(hwfifo_watermark_max, AT91_HWFIFO_MAX_SIZE_STR);
2215 
2216 static const struct iio_dev_attr *at91_adc_fifo_attributes[] = {
2217 	&iio_dev_attr_hwfifo_watermark_min,
2218 	&iio_dev_attr_hwfifo_watermark_max,
2219 	&iio_dev_attr_hwfifo_watermark,
2220 	&iio_dev_attr_hwfifo_enabled,
2221 	NULL,
2222 };
2223 
2224 static const struct iio_info at91_adc_info = {
2225 	.read_avail = &at91_adc_read_avail,
2226 	.read_raw = &at91_adc_read_raw,
2227 	.write_raw = &at91_adc_write_raw,
2228 	.update_scan_mode = &at91_adc_update_scan_mode,
2229 	.fwnode_xlate = &at91_adc_fwnode_xlate,
2230 	.hwfifo_set_watermark = &at91_adc_set_watermark,
2231 };
2232 
at91_adc_buffer_and_trigger_init(struct device * dev,struct iio_dev * indio)2233 static int at91_adc_buffer_and_trigger_init(struct device *dev,
2234 					    struct iio_dev *indio)
2235 {
2236 	struct at91_adc_state *st = iio_priv(indio);
2237 	const struct iio_dev_attr **fifo_attrs;
2238 	int ret;
2239 
2240 	if (st->selected_trig->hw_trig)
2241 		fifo_attrs = at91_adc_fifo_attributes;
2242 	else
2243 		fifo_attrs = NULL;
2244 
2245 	ret = devm_iio_triggered_buffer_setup_ext(&indio->dev, indio,
2246 		&iio_pollfunc_store_time, &at91_adc_trigger_handler,
2247 		IIO_BUFFER_DIRECTION_IN, &at91_buffer_setup_ops, fifo_attrs);
2248 	if (ret < 0) {
2249 		dev_err(dev, "couldn't initialize the buffer.\n");
2250 		return ret;
2251 	}
2252 
2253 	if (!st->selected_trig->hw_trig)
2254 		return 0;
2255 
2256 	st->trig = at91_adc_allocate_trigger(indio, st->selected_trig->name);
2257 	if (IS_ERR(st->trig)) {
2258 		dev_err(dev, "could not allocate trigger\n");
2259 		return PTR_ERR(st->trig);
2260 	}
2261 
2262 	/*
2263 	 * Initially the iio buffer has a length of 2 and
2264 	 * a watermark of 1
2265 	 */
2266 	st->dma_st.watermark = 1;
2267 
2268 	return 0;
2269 }
2270 
at91_adc_temp_sensor_init(struct at91_adc_state * st,struct device * dev)2271 static int at91_adc_temp_sensor_init(struct at91_adc_state *st,
2272 				     struct device *dev)
2273 {
2274 	struct at91_adc_temp_sensor_clb *clb = &st->soc_info.temp_sensor_clb;
2275 	struct nvmem_cell *temp_calib;
2276 	u32 *buf;
2277 	size_t len;
2278 	int ret = 0;
2279 
2280 	if (!st->soc_info.platform->temp_sensor)
2281 		return 0;
2282 
2283 	/* Get the calibration data from NVMEM. */
2284 	temp_calib = devm_nvmem_cell_get(dev, "temperature_calib");
2285 	if (IS_ERR(temp_calib)) {
2286 		ret = PTR_ERR(temp_calib);
2287 		if (ret != -ENOENT)
2288 			dev_err(dev, "Failed to get temperature_calib cell!\n");
2289 		return ret;
2290 	}
2291 
2292 	buf = nvmem_cell_read(temp_calib, &len);
2293 	if (IS_ERR(buf)) {
2294 		dev_err(dev, "Failed to read calibration data!\n");
2295 		return PTR_ERR(buf);
2296 	}
2297 	if (len < AT91_ADC_TS_CLB_IDX_MAX * 4) {
2298 		dev_err(dev, "Invalid calibration data!\n");
2299 		ret = -EINVAL;
2300 		goto free_buf;
2301 	}
2302 
2303 	/* Store calibration data for later use. */
2304 	clb->p1 = buf[AT91_ADC_TS_CLB_IDX_P1];
2305 	clb->p4 = buf[AT91_ADC_TS_CLB_IDX_P4];
2306 	clb->p6 = buf[AT91_ADC_TS_CLB_IDX_P6];
2307 
2308 	/*
2309 	 * We prepare here the conversion to milli to avoid doing it on hotpath.
2310 	 */
2311 	clb->p1 = clb->p1 * 1000;
2312 
2313 free_buf:
2314 	kfree(buf);
2315 	return ret;
2316 }
2317 
at91_adc_probe(struct platform_device * pdev)2318 static int at91_adc_probe(struct platform_device *pdev)
2319 {
2320 	struct device *dev = &pdev->dev;
2321 	struct iio_dev *indio_dev;
2322 	struct at91_adc_state *st;
2323 	struct resource	*res;
2324 	int ret, i, num_channels;
2325 	u32 edge_type = IRQ_TYPE_NONE;
2326 
2327 	indio_dev = devm_iio_device_alloc(&pdev->dev, sizeof(*st));
2328 	if (!indio_dev)
2329 		return -ENOMEM;
2330 
2331 	st = iio_priv(indio_dev);
2332 	st->indio_dev = indio_dev;
2333 
2334 	st->soc_info.platform = device_get_match_data(dev);
2335 
2336 	ret = at91_adc_temp_sensor_init(st, &pdev->dev);
2337 	/* Don't register temperature channel if initialization failed. */
2338 	if (ret)
2339 		num_channels = st->soc_info.platform->max_channels - 1;
2340 	else
2341 		num_channels = st->soc_info.platform->max_channels;
2342 
2343 	indio_dev->name = dev_name(&pdev->dev);
2344 	indio_dev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
2345 	indio_dev->info = &at91_adc_info;
2346 	indio_dev->channels = *st->soc_info.platform->adc_channels;
2347 	indio_dev->num_channels = num_channels;
2348 
2349 	bitmap_set(&st->touch_st.channels_bitmask,
2350 		   st->soc_info.platform->touch_chan_x, 1);
2351 	bitmap_set(&st->touch_st.channels_bitmask,
2352 		   st->soc_info.platform->touch_chan_y, 1);
2353 	bitmap_set(&st->touch_st.channels_bitmask,
2354 		   st->soc_info.platform->touch_chan_p, 1);
2355 
2356 	st->oversampling_ratio = 1;
2357 
2358 	ret = device_property_read_u32(dev, "atmel,min-sample-rate-hz",
2359 				       &st->soc_info.min_sample_rate);
2360 	if (ret) {
2361 		dev_err(&pdev->dev,
2362 			"invalid or missing value for atmel,min-sample-rate-hz\n");
2363 		return ret;
2364 	}
2365 
2366 	ret = device_property_read_u32(dev, "atmel,max-sample-rate-hz",
2367 				       &st->soc_info.max_sample_rate);
2368 	if (ret) {
2369 		dev_err(&pdev->dev,
2370 			"invalid or missing value for atmel,max-sample-rate-hz\n");
2371 		return ret;
2372 	}
2373 
2374 	ret = device_property_read_u32(dev, "atmel,startup-time-ms",
2375 				       &st->soc_info.startup_time);
2376 	if (ret) {
2377 		dev_err(&pdev->dev,
2378 			"invalid or missing value for atmel,startup-time-ms\n");
2379 		return ret;
2380 	}
2381 
2382 	ret = device_property_read_u32(dev, "atmel,trigger-edge-type",
2383 				       &edge_type);
2384 	if (ret) {
2385 		dev_dbg(&pdev->dev,
2386 			"atmel,trigger-edge-type not specified, only software trigger available\n");
2387 	}
2388 
2389 	st->selected_trig = NULL;
2390 
2391 	/* find the right trigger, or no trigger at all */
2392 	for (i = 0; i < st->soc_info.platform->hw_trig_cnt + 1; i++)
2393 		if (at91_adc_trigger_list[i].edge_type == edge_type) {
2394 			st->selected_trig = &at91_adc_trigger_list[i];
2395 			break;
2396 		}
2397 
2398 	if (!st->selected_trig) {
2399 		dev_err(&pdev->dev, "invalid external trigger edge value\n");
2400 		return -EINVAL;
2401 	}
2402 
2403 	init_waitqueue_head(&st->wq_data_available);
2404 	mutex_init(&st->lock);
2405 	INIT_WORK(&st->touch_st.workq, at91_adc_workq_handler);
2406 
2407 	st->base = devm_platform_get_and_ioremap_resource(pdev, 0, &res);
2408 	if (IS_ERR(st->base))
2409 		return PTR_ERR(st->base);
2410 
2411 	/* if we plan to use DMA, we need the physical address of the regs */
2412 	st->dma_st.phys_addr = res->start;
2413 
2414 	st->irq = platform_get_irq(pdev, 0);
2415 	if (st->irq < 0)
2416 		return st->irq;
2417 
2418 	st->per_clk = devm_clk_get(&pdev->dev, "adc_clk");
2419 	if (IS_ERR(st->per_clk))
2420 		return PTR_ERR(st->per_clk);
2421 
2422 	st->reg = devm_regulator_get(&pdev->dev, "vddana");
2423 	if (IS_ERR(st->reg))
2424 		return PTR_ERR(st->reg);
2425 
2426 	st->vref = devm_regulator_get(&pdev->dev, "vref");
2427 	if (IS_ERR(st->vref))
2428 		return PTR_ERR(st->vref);
2429 
2430 	ret = devm_request_irq(&pdev->dev, st->irq, at91_adc_interrupt, 0,
2431 			       pdev->dev.driver->name, indio_dev);
2432 	if (ret)
2433 		return ret;
2434 
2435 	ret = regulator_enable(st->reg);
2436 	if (ret)
2437 		return ret;
2438 
2439 	ret = regulator_enable(st->vref);
2440 	if (ret)
2441 		goto reg_disable;
2442 
2443 	st->vref_uv = regulator_get_voltage(st->vref);
2444 	if (st->vref_uv <= 0) {
2445 		ret = -EINVAL;
2446 		goto vref_disable;
2447 	}
2448 
2449 	ret = clk_prepare_enable(st->per_clk);
2450 	if (ret)
2451 		goto vref_disable;
2452 
2453 	platform_set_drvdata(pdev, indio_dev);
2454 	st->dev = &pdev->dev;
2455 	pm_runtime_set_autosuspend_delay(st->dev, 500);
2456 	pm_runtime_use_autosuspend(st->dev);
2457 	pm_runtime_set_active(st->dev);
2458 	pm_runtime_enable(st->dev);
2459 	pm_runtime_get_noresume(st->dev);
2460 
2461 	at91_adc_hw_init(indio_dev);
2462 
2463 	ret = at91_adc_buffer_and_trigger_init(&pdev->dev, indio_dev);
2464 	if (ret < 0)
2465 		goto err_pm_disable;
2466 
2467 	if (dma_coerce_mask_and_coherent(&indio_dev->dev, DMA_BIT_MASK(32)))
2468 		dev_info(&pdev->dev, "cannot set DMA mask to 32-bit\n");
2469 
2470 	ret = iio_device_register(indio_dev);
2471 	if (ret < 0)
2472 		goto dma_disable;
2473 
2474 	if (st->selected_trig->hw_trig)
2475 		dev_info(&pdev->dev, "setting up trigger as %s\n",
2476 			 st->selected_trig->name);
2477 
2478 	dev_info(&pdev->dev, "version: %x\n",
2479 		 readl_relaxed(st->base + st->soc_info.platform->layout->VERSION));
2480 
2481 	pm_runtime_mark_last_busy(st->dev);
2482 	pm_runtime_put_autosuspend(st->dev);
2483 
2484 	return 0;
2485 
2486 dma_disable:
2487 	at91_adc_dma_disable(st);
2488 err_pm_disable:
2489 	pm_runtime_put_noidle(st->dev);
2490 	pm_runtime_disable(st->dev);
2491 	pm_runtime_set_suspended(st->dev);
2492 	pm_runtime_dont_use_autosuspend(st->dev);
2493 	clk_disable_unprepare(st->per_clk);
2494 vref_disable:
2495 	regulator_disable(st->vref);
2496 reg_disable:
2497 	regulator_disable(st->reg);
2498 	return ret;
2499 }
2500 
at91_adc_remove(struct platform_device * pdev)2501 static void at91_adc_remove(struct platform_device *pdev)
2502 {
2503 	struct iio_dev *indio_dev = platform_get_drvdata(pdev);
2504 	struct at91_adc_state *st = iio_priv(indio_dev);
2505 
2506 	iio_device_unregister(indio_dev);
2507 
2508 	at91_adc_dma_disable(st);
2509 
2510 	pm_runtime_disable(st->dev);
2511 	pm_runtime_set_suspended(st->dev);
2512 	clk_disable_unprepare(st->per_clk);
2513 
2514 	regulator_disable(st->vref);
2515 	regulator_disable(st->reg);
2516 }
2517 
at91_adc_suspend(struct device * dev)2518 static int at91_adc_suspend(struct device *dev)
2519 {
2520 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2521 	struct at91_adc_state *st = iio_priv(indio_dev);
2522 	int ret;
2523 
2524 	ret = pm_runtime_resume_and_get(st->dev);
2525 	if (ret < 0)
2526 		return ret;
2527 
2528 	if (iio_buffer_enabled(indio_dev))
2529 		at91_adc_buffer_postdisable(indio_dev);
2530 
2531 	/*
2532 	 * Do a sofware reset of the ADC before we go to suspend.
2533 	 * this will ensure that all pins are free from being muxed by the ADC
2534 	 * and can be used by for other devices.
2535 	 * Otherwise, ADC will hog them and we can't go to suspend mode.
2536 	 */
2537 	at91_adc_writel(st, CR, AT91_SAMA5D2_CR_SWRST);
2538 
2539 	pm_runtime_mark_last_busy(st->dev);
2540 	pm_runtime_put_noidle(st->dev);
2541 	clk_disable_unprepare(st->per_clk);
2542 	regulator_disable(st->vref);
2543 	regulator_disable(st->reg);
2544 
2545 	return pinctrl_pm_select_sleep_state(dev);
2546 }
2547 
at91_adc_resume(struct device * dev)2548 static int at91_adc_resume(struct device *dev)
2549 {
2550 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2551 	struct at91_adc_state *st = iio_priv(indio_dev);
2552 	int ret;
2553 
2554 	ret = pinctrl_pm_select_default_state(dev);
2555 	if (ret)
2556 		goto resume_failed;
2557 
2558 	ret = regulator_enable(st->reg);
2559 	if (ret)
2560 		goto resume_failed;
2561 
2562 	ret = regulator_enable(st->vref);
2563 	if (ret)
2564 		goto reg_disable_resume;
2565 
2566 	ret = clk_prepare_enable(st->per_clk);
2567 	if (ret)
2568 		goto vref_disable_resume;
2569 
2570 	pm_runtime_get_noresume(st->dev);
2571 
2572 	at91_adc_hw_init(indio_dev);
2573 
2574 	/* reconfiguring trigger hardware state */
2575 	if (iio_buffer_enabled(indio_dev)) {
2576 		ret = at91_adc_buffer_prepare(indio_dev);
2577 		if (ret)
2578 			goto pm_runtime_put;
2579 
2580 		at91_adc_configure_trigger_registers(st, true);
2581 	}
2582 
2583 	pm_runtime_mark_last_busy(st->dev);
2584 	pm_runtime_put_autosuspend(st->dev);
2585 
2586 	return 0;
2587 
2588 pm_runtime_put:
2589 	pm_runtime_mark_last_busy(st->dev);
2590 	pm_runtime_put_noidle(st->dev);
2591 	clk_disable_unprepare(st->per_clk);
2592 vref_disable_resume:
2593 	regulator_disable(st->vref);
2594 reg_disable_resume:
2595 	regulator_disable(st->reg);
2596 resume_failed:
2597 	dev_err(&indio_dev->dev, "failed to resume\n");
2598 	return ret;
2599 }
2600 
at91_adc_runtime_suspend(struct device * dev)2601 static int at91_adc_runtime_suspend(struct device *dev)
2602 {
2603 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2604 	struct at91_adc_state *st = iio_priv(indio_dev);
2605 
2606 	clk_disable(st->per_clk);
2607 
2608 	return 0;
2609 }
2610 
at91_adc_runtime_resume(struct device * dev)2611 static int at91_adc_runtime_resume(struct device *dev)
2612 {
2613 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2614 	struct at91_adc_state *st = iio_priv(indio_dev);
2615 
2616 	return clk_enable(st->per_clk);
2617 }
2618 
2619 static const struct dev_pm_ops at91_adc_pm_ops = {
2620 	SYSTEM_SLEEP_PM_OPS(at91_adc_suspend, at91_adc_resume)
2621 	RUNTIME_PM_OPS(at91_adc_runtime_suspend, at91_adc_runtime_resume,
2622 		       NULL)
2623 };
2624 
2625 static const struct of_device_id at91_adc_dt_match[] = {
2626 	{
2627 		.compatible = "atmel,sama5d2-adc",
2628 		.data = (const void *)&sama5d2_platform,
2629 	}, {
2630 		.compatible = "microchip,sama7g5-adc",
2631 		.data = (const void *)&sama7g5_platform,
2632 	}, {
2633 		/* sentinel */
2634 	}
2635 };
2636 MODULE_DEVICE_TABLE(of, at91_adc_dt_match);
2637 
2638 static struct platform_driver at91_adc_driver = {
2639 	.probe = at91_adc_probe,
2640 	.remove = at91_adc_remove,
2641 	.driver = {
2642 		.name = "at91-sama5d2_adc",
2643 		.of_match_table = at91_adc_dt_match,
2644 		.pm = pm_ptr(&at91_adc_pm_ops),
2645 	},
2646 };
2647 module_platform_driver(at91_adc_driver)
2648 
2649 MODULE_AUTHOR("Ludovic Desroches <ludovic.desroches@microchip.com>");
2650 MODULE_AUTHOR("Eugen Hristev <eugen.hristev@microchip.com");
2651 MODULE_DESCRIPTION("Atmel AT91 SAMA5D2 ADC");
2652 MODULE_LICENSE("GPL v2");
2653