]> Git Repo - J-linux.git/blob - drivers/iio/adc/at91-sama5d2_adc.c
Merge tag 'trace-v5.13-2' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt...
[J-linux.git] / drivers / iio / adc / at91-sama5d2_adc.c
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 <[email protected]>
7  */
8
9 #include <linux/bitops.h>
10 #include <linux/clk.h>
11 #include <linux/delay.h>
12 #include <linux/dma-mapping.h>
13 #include <linux/dmaengine.h>
14 #include <linux/interrupt.h>
15 #include <linux/io.h>
16 #include <linux/module.h>
17 #include <linux/of_device.h>
18 #include <linux/platform_device.h>
19 #include <linux/sched.h>
20 #include <linux/wait.h>
21 #include <linux/iio/iio.h>
22 #include <linux/iio/sysfs.h>
23 #include <linux/iio/buffer.h>
24 #include <linux/iio/trigger.h>
25 #include <linux/iio/trigger_consumer.h>
26 #include <linux/iio/triggered_buffer.h>
27 #include <linux/pinctrl/consumer.h>
28 #include <linux/regulator/consumer.h>
29
30 /* Control Register */
31 #define AT91_SAMA5D2_CR         0x00
32 /* Software Reset */
33 #define AT91_SAMA5D2_CR_SWRST           BIT(0)
34 /* Start Conversion */
35 #define AT91_SAMA5D2_CR_START           BIT(1)
36 /* Touchscreen Calibration */
37 #define AT91_SAMA5D2_CR_TSCALIB         BIT(2)
38 /* Comparison Restart */
39 #define AT91_SAMA5D2_CR_CMPRST          BIT(4)
40
41 /* Mode Register */
42 #define AT91_SAMA5D2_MR         0x04
43 /* Trigger Selection */
44 #define AT91_SAMA5D2_MR_TRGSEL(v)       ((v) << 1)
45 /* ADTRG */
46 #define AT91_SAMA5D2_MR_TRGSEL_TRIG0    0
47 /* TIOA0 */
48 #define AT91_SAMA5D2_MR_TRGSEL_TRIG1    1
49 /* TIOA1 */
50 #define AT91_SAMA5D2_MR_TRGSEL_TRIG2    2
51 /* TIOA2 */
52 #define AT91_SAMA5D2_MR_TRGSEL_TRIG3    3
53 /* PWM event line 0 */
54 #define AT91_SAMA5D2_MR_TRGSEL_TRIG4    4
55 /* PWM event line 1 */
56 #define AT91_SAMA5D2_MR_TRGSEL_TRIG5    5
57 /* TIOA3 */
58 #define AT91_SAMA5D2_MR_TRGSEL_TRIG6    6
59 /* RTCOUT0 */
60 #define AT91_SAMA5D2_MR_TRGSEL_TRIG7    7
61 /* Sleep Mode */
62 #define AT91_SAMA5D2_MR_SLEEP           BIT(5)
63 /* Fast Wake Up */
64 #define AT91_SAMA5D2_MR_FWUP            BIT(6)
65 /* Prescaler Rate Selection */
66 #define AT91_SAMA5D2_MR_PRESCAL(v)      ((v) << AT91_SAMA5D2_MR_PRESCAL_OFFSET)
67 #define AT91_SAMA5D2_MR_PRESCAL_OFFSET  8
68 #define AT91_SAMA5D2_MR_PRESCAL_MAX     0xff
69 #define AT91_SAMA5D2_MR_PRESCAL_MASK    GENMASK(15, 8)
70 /* Startup Time */
71 #define AT91_SAMA5D2_MR_STARTUP(v)      ((v) << 16)
72 #define AT91_SAMA5D2_MR_STARTUP_MASK    GENMASK(19, 16)
73 /* Analog Change */
74 #define AT91_SAMA5D2_MR_ANACH           BIT(23)
75 /* Tracking Time */
76 #define AT91_SAMA5D2_MR_TRACKTIM(v)     ((v) << 24)
77 #define AT91_SAMA5D2_MR_TRACKTIM_MAX    0xff
78 /* Transfer Time */
79 #define AT91_SAMA5D2_MR_TRANSFER(v)     ((v) << 28)
80 #define AT91_SAMA5D2_MR_TRANSFER_MAX    0x3
81 /* Use Sequence Enable */
82 #define AT91_SAMA5D2_MR_USEQ            BIT(31)
83
84 /* Channel Sequence Register 1 */
85 #define AT91_SAMA5D2_SEQR1      0x08
86 /* Channel Sequence Register 2 */
87 #define AT91_SAMA5D2_SEQR2      0x0c
88 /* Channel Enable Register */
89 #define AT91_SAMA5D2_CHER       0x10
90 /* Channel Disable Register */
91 #define AT91_SAMA5D2_CHDR       0x14
92 /* Channel Status Register */
93 #define AT91_SAMA5D2_CHSR       0x18
94 /* Last Converted Data Register */
95 #define AT91_SAMA5D2_LCDR       0x20
96 /* Interrupt Enable Register */
97 #define AT91_SAMA5D2_IER        0x24
98 /* Interrupt Enable Register - TS X measurement ready */
99 #define AT91_SAMA5D2_IER_XRDY   BIT(20)
100 /* Interrupt Enable Register - TS Y measurement ready */
101 #define AT91_SAMA5D2_IER_YRDY   BIT(21)
102 /* Interrupt Enable Register - TS pressure measurement ready */
103 #define AT91_SAMA5D2_IER_PRDY   BIT(22)
104 /* Interrupt Enable Register - Data ready */
105 #define AT91_SAMA5D2_IER_DRDY   BIT(24)
106 /* Interrupt Enable Register - general overrun error */
107 #define AT91_SAMA5D2_IER_GOVRE BIT(25)
108 /* Interrupt Enable Register - Pen detect */
109 #define AT91_SAMA5D2_IER_PEN    BIT(29)
110 /* Interrupt Enable Register - No pen detect */
111 #define AT91_SAMA5D2_IER_NOPEN  BIT(30)
112 /* Interrupt Disable Register */
113 #define AT91_SAMA5D2_IDR        0x28
114 /* Interrupt Mask Register */
115 #define AT91_SAMA5D2_IMR        0x2c
116 /* Interrupt Status Register */
117 #define AT91_SAMA5D2_ISR        0x30
118 /* Interrupt Status Register - Pen touching sense status */
119 #define AT91_SAMA5D2_ISR_PENS   BIT(31)
120 /* Last Channel Trigger Mode Register */
121 #define AT91_SAMA5D2_LCTMR      0x34
122 /* Last Channel Compare Window Register */
123 #define AT91_SAMA5D2_LCCWR      0x38
124 /* Overrun Status Register */
125 #define AT91_SAMA5D2_OVER       0x3c
126 /* Extended Mode Register */
127 #define AT91_SAMA5D2_EMR        0x40
128 /* Extended Mode Register - Oversampling rate */
129 #define AT91_SAMA5D2_EMR_OSR(V)                 ((V) << 16)
130 #define AT91_SAMA5D2_EMR_OSR_MASK               GENMASK(17, 16)
131 #define AT91_SAMA5D2_EMR_OSR_1SAMPLES           0
132 #define AT91_SAMA5D2_EMR_OSR_4SAMPLES           1
133 #define AT91_SAMA5D2_EMR_OSR_16SAMPLES          2
134
135 /* Extended Mode Register - Averaging on single trigger event */
136 #define AT91_SAMA5D2_EMR_ASTE(V)                ((V) << 20)
137 /* Compare Window Register */
138 #define AT91_SAMA5D2_CWR        0x44
139 /* Channel Gain Register */
140 #define AT91_SAMA5D2_CGR        0x48
141
142 /* Channel Offset Register */
143 #define AT91_SAMA5D2_COR        0x4c
144 #define AT91_SAMA5D2_COR_DIFF_OFFSET    16
145
146 /* Channel Data Register 0 */
147 #define AT91_SAMA5D2_CDR0       0x50
148 /* Analog Control Register */
149 #define AT91_SAMA5D2_ACR        0x94
150 /* Analog Control Register - Pen detect sensitivity mask */
151 #define AT91_SAMA5D2_ACR_PENDETSENS_MASK        GENMASK(1, 0)
152
153 /* Touchscreen Mode Register */
154 #define AT91_SAMA5D2_TSMR       0xb0
155 /* Touchscreen Mode Register - No touch mode */
156 #define AT91_SAMA5D2_TSMR_TSMODE_NONE           0
157 /* Touchscreen Mode Register - 4 wire screen, no pressure measurement */
158 #define AT91_SAMA5D2_TSMR_TSMODE_4WIRE_NO_PRESS 1
159 /* Touchscreen Mode Register - 4 wire screen, pressure measurement */
160 #define AT91_SAMA5D2_TSMR_TSMODE_4WIRE_PRESS    2
161 /* Touchscreen Mode Register - 5 wire screen */
162 #define AT91_SAMA5D2_TSMR_TSMODE_5WIRE          3
163 /* Touchscreen Mode Register - Average samples mask */
164 #define AT91_SAMA5D2_TSMR_TSAV_MASK             GENMASK(5, 4)
165 /* Touchscreen Mode Register - Average samples */
166 #define AT91_SAMA5D2_TSMR_TSAV(x)               ((x) << 4)
167 /* Touchscreen Mode Register - Touch/trigger frequency ratio mask */
168 #define AT91_SAMA5D2_TSMR_TSFREQ_MASK           GENMASK(11, 8)
169 /* Touchscreen Mode Register - Touch/trigger frequency ratio */
170 #define AT91_SAMA5D2_TSMR_TSFREQ(x)             ((x) << 8)
171 /* Touchscreen Mode Register - Pen Debounce Time mask */
172 #define AT91_SAMA5D2_TSMR_PENDBC_MASK           GENMASK(31, 28)
173 /* Touchscreen Mode Register - Pen Debounce Time */
174 #define AT91_SAMA5D2_TSMR_PENDBC(x)            ((x) << 28)
175 /* Touchscreen Mode Register - No DMA for touch measurements */
176 #define AT91_SAMA5D2_TSMR_NOTSDMA               BIT(22)
177 /* Touchscreen Mode Register - Disable pen detection */
178 #define AT91_SAMA5D2_TSMR_PENDET_DIS            (0 << 24)
179 /* Touchscreen Mode Register - Enable pen detection */
180 #define AT91_SAMA5D2_TSMR_PENDET_ENA            BIT(24)
181
182 /* Touchscreen X Position Register */
183 #define AT91_SAMA5D2_XPOSR      0xb4
184 /* Touchscreen Y Position Register */
185 #define AT91_SAMA5D2_YPOSR      0xb8
186 /* Touchscreen Pressure Register */
187 #define AT91_SAMA5D2_PRESSR     0xbc
188 /* Trigger Register */
189 #define AT91_SAMA5D2_TRGR       0xc0
190 /* Mask for TRGMOD field of TRGR register */
191 #define AT91_SAMA5D2_TRGR_TRGMOD_MASK GENMASK(2, 0)
192 /* No trigger, only software trigger can start conversions */
193 #define AT91_SAMA5D2_TRGR_TRGMOD_NO_TRIGGER 0
194 /* Trigger Mode external trigger rising edge */
195 #define AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_RISE 1
196 /* Trigger Mode external trigger falling edge */
197 #define AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_FALL 2
198 /* Trigger Mode external trigger any edge */
199 #define AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_ANY 3
200 /* Trigger Mode internal periodic */
201 #define AT91_SAMA5D2_TRGR_TRGMOD_PERIODIC 5
202 /* Trigger Mode - trigger period mask */
203 #define AT91_SAMA5D2_TRGR_TRGPER_MASK           GENMASK(31, 16)
204 /* Trigger Mode - trigger period */
205 #define AT91_SAMA5D2_TRGR_TRGPER(x)             ((x) << 16)
206
207 /* Correction Select Register */
208 #define AT91_SAMA5D2_COSR       0xd0
209 /* Correction Value Register */
210 #define AT91_SAMA5D2_CVR        0xd4
211 /* Channel Error Correction Register */
212 #define AT91_SAMA5D2_CECR       0xd8
213 /* Write Protection Mode Register */
214 #define AT91_SAMA5D2_WPMR       0xe4
215 /* Write Protection Status Register */
216 #define AT91_SAMA5D2_WPSR       0xe8
217 /* Version Register */
218 #define AT91_SAMA5D2_VERSION    0xfc
219
220 #define AT91_SAMA5D2_HW_TRIG_CNT 3
221 #define AT91_SAMA5D2_SINGLE_CHAN_CNT 12
222 #define AT91_SAMA5D2_DIFF_CHAN_CNT 6
223
224 #define AT91_SAMA5D2_TIMESTAMP_CHAN_IDX (AT91_SAMA5D2_SINGLE_CHAN_CNT + \
225                                          AT91_SAMA5D2_DIFF_CHAN_CNT + 1)
226
227 #define AT91_SAMA5D2_TOUCH_X_CHAN_IDX (AT91_SAMA5D2_SINGLE_CHAN_CNT + \
228                                          AT91_SAMA5D2_DIFF_CHAN_CNT * 2)
229 #define AT91_SAMA5D2_TOUCH_Y_CHAN_IDX   (AT91_SAMA5D2_TOUCH_X_CHAN_IDX + 1)
230 #define AT91_SAMA5D2_TOUCH_P_CHAN_IDX   (AT91_SAMA5D2_TOUCH_Y_CHAN_IDX + 1)
231 #define AT91_SAMA5D2_MAX_CHAN_IDX       AT91_SAMA5D2_TOUCH_P_CHAN_IDX
232
233 #define AT91_SAMA5D2_TOUCH_SAMPLE_PERIOD_US          2000    /* 2ms */
234 #define AT91_SAMA5D2_TOUCH_PEN_DETECT_DEBOUNCE_US    200
235
236 #define AT91_SAMA5D2_XYZ_MASK           GENMASK(11, 0)
237
238 #define AT91_SAMA5D2_MAX_POS_BITS                       12
239
240 /*
241  * Maximum number of bytes to hold conversion from all channels
242  * without the timestamp.
243  */
244 #define AT91_BUFFER_MAX_CONVERSION_BYTES ((AT91_SAMA5D2_SINGLE_CHAN_CNT + \
245                                          AT91_SAMA5D2_DIFF_CHAN_CNT) * 2)
246
247 /* This total must also include the timestamp */
248 #define AT91_BUFFER_MAX_BYTES (AT91_BUFFER_MAX_CONVERSION_BYTES + 8)
249
250 #define AT91_BUFFER_MAX_HWORDS (AT91_BUFFER_MAX_BYTES / 2)
251
252 #define AT91_HWFIFO_MAX_SIZE_STR        "128"
253 #define AT91_HWFIFO_MAX_SIZE            128
254
255 /* Possible values for oversampling ratio */
256 #define AT91_OSR_1SAMPLES               1
257 #define AT91_OSR_4SAMPLES               4
258 #define AT91_OSR_16SAMPLES              16
259
260 #define AT91_SAMA5D2_CHAN_SINGLE(num, addr)                             \
261         {                                                               \
262                 .type = IIO_VOLTAGE,                                    \
263                 .channel = num,                                         \
264                 .address = addr,                                        \
265                 .scan_index = num,                                      \
266                 .scan_type = {                                          \
267                         .sign = 'u',                                    \
268                         .realbits = 14,                                 \
269                         .storagebits = 16,                              \
270                 },                                                      \
271                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),           \
272                 .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),   \
273                 .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ)|\
274                                 BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),  \
275                 .datasheet_name = "CH"#num,                             \
276                 .indexed = 1,                                           \
277         }
278
279 #define AT91_SAMA5D2_CHAN_DIFF(num, num2, addr)                         \
280         {                                                               \
281                 .type = IIO_VOLTAGE,                                    \
282                 .differential = 1,                                      \
283                 .channel = num,                                         \
284                 .channel2 = num2,                                       \
285                 .address = addr,                                        \
286                 .scan_index = num + AT91_SAMA5D2_SINGLE_CHAN_CNT,       \
287                 .scan_type = {                                          \
288                         .sign = 's',                                    \
289                         .realbits = 14,                                 \
290                         .storagebits = 16,                              \
291                 },                                                      \
292                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),           \
293                 .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),   \
294                 .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ)|\
295                                 BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),  \
296                 .datasheet_name = "CH"#num"-CH"#num2,                   \
297                 .indexed = 1,                                           \
298         }
299
300 #define AT91_SAMA5D2_CHAN_TOUCH(num, name, mod)                         \
301         {                                                               \
302                 .type = IIO_POSITIONRELATIVE,                           \
303                 .modified = 1,                                          \
304                 .channel = num,                                         \
305                 .channel2 = mod,                                        \
306                 .scan_index = num,                                      \
307                 .scan_type = {                                          \
308                         .sign = 'u',                                    \
309                         .realbits = 12,                                 \
310                         .storagebits = 16,                              \
311                 },                                                      \
312                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),           \
313                 .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ)|\
314                                 BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),  \
315                 .datasheet_name = name,                                 \
316         }
317 #define AT91_SAMA5D2_CHAN_PRESSURE(num, name)                           \
318         {                                                               \
319                 .type = IIO_PRESSURE,                                   \
320                 .channel = num,                                         \
321                 .scan_index = num,                                      \
322                 .scan_type = {                                          \
323                         .sign = 'u',                                    \
324                         .realbits = 12,                                 \
325                         .storagebits = 16,                              \
326                 },                                                      \
327                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),           \
328                 .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ)|\
329                                 BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),  \
330                 .datasheet_name = name,                                 \
331         }
332
333 #define at91_adc_readl(st, reg)         readl_relaxed(st->base + reg)
334 #define at91_adc_writel(st, reg, val)   writel_relaxed(val, st->base + reg)
335
336 struct at91_adc_soc_info {
337         unsigned                        startup_time;
338         unsigned                        min_sample_rate;
339         unsigned                        max_sample_rate;
340 };
341
342 struct at91_adc_trigger {
343         char                            *name;
344         unsigned int                    trgmod_value;
345         unsigned int                    edge_type;
346         bool                            hw_trig;
347 };
348
349 /**
350  * struct at91_adc_dma - at91-sama5d2 dma information struct
351  * @dma_chan:           the dma channel acquired
352  * @rx_buf:             dma coherent allocated area
353  * @rx_dma_buf:         dma handler for the buffer
354  * @phys_addr:          physical address of the ADC base register
355  * @buf_idx:            index inside the dma buffer where reading was last done
356  * @rx_buf_sz:          size of buffer used by DMA operation
357  * @watermark:          number of conversions to copy before DMA triggers irq
358  * @dma_ts:             hold the start timestamp of dma operation
359  */
360 struct at91_adc_dma {
361         struct dma_chan                 *dma_chan;
362         u8                              *rx_buf;
363         dma_addr_t                      rx_dma_buf;
364         phys_addr_t                     phys_addr;
365         int                             buf_idx;
366         int                             rx_buf_sz;
367         int                             watermark;
368         s64                             dma_ts;
369 };
370
371 /**
372  * struct at91_adc_touch - at91-sama5d2 touchscreen information struct
373  * @sample_period_val:          the value for periodic trigger interval
374  * @touching:                   is the pen touching the screen or not
375  * @x_pos:                      temporary placeholder for pressure computation
376  * @channels_bitmask:           bitmask with the touchscreen channels enabled
377  * @workq:                      workqueue for buffer data pushing
378  */
379 struct at91_adc_touch {
380         u16                             sample_period_val;
381         bool                            touching;
382         u16                             x_pos;
383         unsigned long                   channels_bitmask;
384         struct work_struct              workq;
385 };
386
387 struct at91_adc_state {
388         void __iomem                    *base;
389         int                             irq;
390         struct clk                      *per_clk;
391         struct regulator                *reg;
392         struct regulator                *vref;
393         int                             vref_uv;
394         unsigned int                    current_sample_rate;
395         struct iio_trigger              *trig;
396         const struct at91_adc_trigger   *selected_trig;
397         const struct iio_chan_spec      *chan;
398         bool                            conversion_done;
399         u32                             conversion_value;
400         unsigned int                    oversampling_ratio;
401         struct at91_adc_soc_info        soc_info;
402         wait_queue_head_t               wq_data_available;
403         struct at91_adc_dma             dma_st;
404         struct at91_adc_touch           touch_st;
405         struct iio_dev                  *indio_dev;
406         u16                             buffer[AT91_BUFFER_MAX_HWORDS];
407         /*
408          * lock to prevent concurrent 'single conversion' requests through
409          * sysfs.
410          */
411         struct mutex                    lock;
412 };
413
414 static const struct at91_adc_trigger at91_adc_trigger_list[] = {
415         {
416                 .name = "external_rising",
417                 .trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_RISE,
418                 .edge_type = IRQ_TYPE_EDGE_RISING,
419                 .hw_trig = true,
420         },
421         {
422                 .name = "external_falling",
423                 .trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_FALL,
424                 .edge_type = IRQ_TYPE_EDGE_FALLING,
425                 .hw_trig = true,
426         },
427         {
428                 .name = "external_any",
429                 .trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_ANY,
430                 .edge_type = IRQ_TYPE_EDGE_BOTH,
431                 .hw_trig = true,
432         },
433         {
434                 .name = "software",
435                 .trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_NO_TRIGGER,
436                 .edge_type = IRQ_TYPE_NONE,
437                 .hw_trig = false,
438         },
439 };
440
441 static const struct iio_chan_spec at91_adc_channels[] = {
442         AT91_SAMA5D2_CHAN_SINGLE(0, 0x50),
443         AT91_SAMA5D2_CHAN_SINGLE(1, 0x54),
444         AT91_SAMA5D2_CHAN_SINGLE(2, 0x58),
445         AT91_SAMA5D2_CHAN_SINGLE(3, 0x5c),
446         AT91_SAMA5D2_CHAN_SINGLE(4, 0x60),
447         AT91_SAMA5D2_CHAN_SINGLE(5, 0x64),
448         AT91_SAMA5D2_CHAN_SINGLE(6, 0x68),
449         AT91_SAMA5D2_CHAN_SINGLE(7, 0x6c),
450         AT91_SAMA5D2_CHAN_SINGLE(8, 0x70),
451         AT91_SAMA5D2_CHAN_SINGLE(9, 0x74),
452         AT91_SAMA5D2_CHAN_SINGLE(10, 0x78),
453         AT91_SAMA5D2_CHAN_SINGLE(11, 0x7c),
454         AT91_SAMA5D2_CHAN_DIFF(0, 1, 0x50),
455         AT91_SAMA5D2_CHAN_DIFF(2, 3, 0x58),
456         AT91_SAMA5D2_CHAN_DIFF(4, 5, 0x60),
457         AT91_SAMA5D2_CHAN_DIFF(6, 7, 0x68),
458         AT91_SAMA5D2_CHAN_DIFF(8, 9, 0x70),
459         AT91_SAMA5D2_CHAN_DIFF(10, 11, 0x78),
460         IIO_CHAN_SOFT_TIMESTAMP(AT91_SAMA5D2_TIMESTAMP_CHAN_IDX),
461         AT91_SAMA5D2_CHAN_TOUCH(AT91_SAMA5D2_TOUCH_X_CHAN_IDX, "x", IIO_MOD_X),
462         AT91_SAMA5D2_CHAN_TOUCH(AT91_SAMA5D2_TOUCH_Y_CHAN_IDX, "y", IIO_MOD_Y),
463         AT91_SAMA5D2_CHAN_PRESSURE(AT91_SAMA5D2_TOUCH_P_CHAN_IDX, "pressure"),
464 };
465
466 static int at91_adc_chan_xlate(struct iio_dev *indio_dev, int chan)
467 {
468         int i;
469
470         for (i = 0; i < indio_dev->num_channels; i++) {
471                 if (indio_dev->channels[i].scan_index == chan)
472                         return i;
473         }
474         return -EINVAL;
475 }
476
477 static inline struct iio_chan_spec const *
478 at91_adc_chan_get(struct iio_dev *indio_dev, int chan)
479 {
480         int index = at91_adc_chan_xlate(indio_dev, chan);
481
482         if (index < 0)
483                 return NULL;
484         return indio_dev->channels + index;
485 }
486
487 static inline int at91_adc_of_xlate(struct iio_dev *indio_dev,
488                                     const struct of_phandle_args *iiospec)
489 {
490         return at91_adc_chan_xlate(indio_dev, iiospec->args[0]);
491 }
492
493 static unsigned int at91_adc_active_scan_mask_to_reg(struct iio_dev *indio_dev)
494 {
495         u32 mask = 0;
496         u8 bit;
497
498         for_each_set_bit(bit, indio_dev->active_scan_mask,
499                          indio_dev->num_channels) {
500                 struct iio_chan_spec const *chan =
501                          at91_adc_chan_get(indio_dev, bit);
502                 mask |= BIT(chan->channel);
503         }
504
505         return mask & GENMASK(11, 0);
506 }
507
508 static void at91_adc_config_emr(struct at91_adc_state *st)
509 {
510         /* configure the extended mode register */
511         unsigned int emr = at91_adc_readl(st, AT91_SAMA5D2_EMR);
512
513         /* select oversampling per single trigger event */
514         emr |= AT91_SAMA5D2_EMR_ASTE(1);
515
516         /* delete leftover content if it's the case */
517         emr &= ~AT91_SAMA5D2_EMR_OSR_MASK;
518
519         /* select oversampling ratio from configuration */
520         switch (st->oversampling_ratio) {
521         case AT91_OSR_1SAMPLES:
522                 emr |= AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_1SAMPLES) &
523                        AT91_SAMA5D2_EMR_OSR_MASK;
524                 break;
525         case AT91_OSR_4SAMPLES:
526                 emr |= AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_4SAMPLES) &
527                        AT91_SAMA5D2_EMR_OSR_MASK;
528                 break;
529         case AT91_OSR_16SAMPLES:
530                 emr |= AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_16SAMPLES) &
531                        AT91_SAMA5D2_EMR_OSR_MASK;
532                 break;
533         }
534
535         at91_adc_writel(st, AT91_SAMA5D2_EMR, emr);
536 }
537
538 static int at91_adc_adjust_val_osr(struct at91_adc_state *st, int *val)
539 {
540         if (st->oversampling_ratio == AT91_OSR_1SAMPLES) {
541                 /*
542                  * in this case we only have 12 bits of real data, but channel
543                  * is registered as 14 bits, so shift left two bits
544                  */
545                 *val <<= 2;
546         } else if (st->oversampling_ratio == AT91_OSR_4SAMPLES) {
547                 /*
548                  * in this case we have 13 bits of real data, but channel
549                  * is registered as 14 bits, so left shift one bit
550                  */
551                 *val <<= 1;
552         }
553
554         return IIO_VAL_INT;
555 }
556
557 static void at91_adc_adjust_val_osr_array(struct at91_adc_state *st, void *buf,
558                                           int len)
559 {
560         int i = 0, val;
561         u16 *buf_u16 = (u16 *) buf;
562
563         /*
564          * We are converting each two bytes (each sample).
565          * First convert the byte based array to u16, and convert each sample
566          * separately.
567          * Each value is two bytes in an array of chars, so to not shift
568          * more than we need, save the value separately.
569          * len is in bytes, so divide by two to get number of samples.
570          */
571         while (i < len / 2) {
572                 val = buf_u16[i];
573                 at91_adc_adjust_val_osr(st, &val);
574                 buf_u16[i] = val;
575                 i++;
576         }
577 }
578
579 static int at91_adc_configure_touch(struct at91_adc_state *st, bool state)
580 {
581         u32 clk_khz = st->current_sample_rate / 1000;
582         int i = 0;
583         u16 pendbc;
584         u32 tsmr, acr;
585
586         if (!state) {
587                 /* disabling touch IRQs and setting mode to no touch enabled */
588                 at91_adc_writel(st, AT91_SAMA5D2_IDR,
589                                 AT91_SAMA5D2_IER_PEN | AT91_SAMA5D2_IER_NOPEN);
590                 at91_adc_writel(st, AT91_SAMA5D2_TSMR, 0);
591                 return 0;
592         }
593         /*
594          * debounce time is in microseconds, we need it in milliseconds to
595          * multiply with kilohertz, so, divide by 1000, but after the multiply.
596          * round up to make sure pendbc is at least 1
597          */
598         pendbc = round_up(AT91_SAMA5D2_TOUCH_PEN_DETECT_DEBOUNCE_US *
599                           clk_khz / 1000, 1);
600
601         /* get the required exponent */
602         while (pendbc >> i++)
603                 ;
604
605         pendbc = i;
606
607         tsmr = AT91_SAMA5D2_TSMR_TSMODE_4WIRE_PRESS;
608
609         tsmr |= AT91_SAMA5D2_TSMR_TSAV(2) & AT91_SAMA5D2_TSMR_TSAV_MASK;
610         tsmr |= AT91_SAMA5D2_TSMR_PENDBC(pendbc) &
611                 AT91_SAMA5D2_TSMR_PENDBC_MASK;
612         tsmr |= AT91_SAMA5D2_TSMR_NOTSDMA;
613         tsmr |= AT91_SAMA5D2_TSMR_PENDET_ENA;
614         tsmr |= AT91_SAMA5D2_TSMR_TSFREQ(2) & AT91_SAMA5D2_TSMR_TSFREQ_MASK;
615
616         at91_adc_writel(st, AT91_SAMA5D2_TSMR, tsmr);
617
618         acr =  at91_adc_readl(st, AT91_SAMA5D2_ACR);
619         acr &= ~AT91_SAMA5D2_ACR_PENDETSENS_MASK;
620         acr |= 0x02 & AT91_SAMA5D2_ACR_PENDETSENS_MASK;
621         at91_adc_writel(st, AT91_SAMA5D2_ACR, acr);
622
623         /* Sample Period Time = (TRGPER + 1) / ADCClock */
624         st->touch_st.sample_period_val =
625                                  round_up((AT91_SAMA5D2_TOUCH_SAMPLE_PERIOD_US *
626                                  clk_khz / 1000) - 1, 1);
627         /* enable pen detect IRQ */
628         at91_adc_writel(st, AT91_SAMA5D2_IER, AT91_SAMA5D2_IER_PEN);
629
630         return 0;
631 }
632
633 static u16 at91_adc_touch_pos(struct at91_adc_state *st, int reg)
634 {
635         u32 val;
636         u32 scale, result, pos;
637
638         /*
639          * to obtain the actual position we must divide by scale
640          * and multiply with max, where
641          * max = 2^AT91_SAMA5D2_MAX_POS_BITS - 1
642          */
643         /* first half of register is the x or y, second half is the scale */
644         val = at91_adc_readl(st, reg);
645         if (!val)
646                 dev_dbg(&st->indio_dev->dev, "pos is 0\n");
647
648         pos = val & AT91_SAMA5D2_XYZ_MASK;
649         result = (pos << AT91_SAMA5D2_MAX_POS_BITS) - pos;
650         scale = (val >> 16) & AT91_SAMA5D2_XYZ_MASK;
651         if (scale == 0) {
652                 dev_err(&st->indio_dev->dev, "scale is 0\n");
653                 return 0;
654         }
655         result /= scale;
656
657         return result;
658 }
659
660 static u16 at91_adc_touch_x_pos(struct at91_adc_state *st)
661 {
662         st->touch_st.x_pos = at91_adc_touch_pos(st, AT91_SAMA5D2_XPOSR);
663         return st->touch_st.x_pos;
664 }
665
666 static u16 at91_adc_touch_y_pos(struct at91_adc_state *st)
667 {
668         return at91_adc_touch_pos(st, AT91_SAMA5D2_YPOSR);
669 }
670
671 static u16 at91_adc_touch_pressure(struct at91_adc_state *st)
672 {
673         u32 val;
674         u32 z1, z2;
675         u32 pres;
676         u32 rxp = 1;
677         u32 factor = 1000;
678
679         /* calculate the pressure */
680         val = at91_adc_readl(st, AT91_SAMA5D2_PRESSR);
681         z1 = val & AT91_SAMA5D2_XYZ_MASK;
682         z2 = (val >> 16) & AT91_SAMA5D2_XYZ_MASK;
683
684         if (z1 != 0)
685                 pres = rxp * (st->touch_st.x_pos * factor / 1024) *
686                         (z2 * factor / z1 - factor) /
687                         factor;
688         else
689                 pres = 0xFFFF;       /* no pen contact */
690
691         /*
692          * The pressure from device grows down, minimum is 0xFFFF, maximum 0x0.
693          * We compute it this way, but let's return it in the expected way,
694          * growing from 0 to 0xFFFF.
695          */
696         return 0xFFFF - pres;
697 }
698
699 static int at91_adc_read_position(struct at91_adc_state *st, int chan, u16 *val)
700 {
701         *val = 0;
702         if (!st->touch_st.touching)
703                 return -ENODATA;
704         if (chan == AT91_SAMA5D2_TOUCH_X_CHAN_IDX)
705                 *val = at91_adc_touch_x_pos(st);
706         else if (chan == AT91_SAMA5D2_TOUCH_Y_CHAN_IDX)
707                 *val = at91_adc_touch_y_pos(st);
708         else
709                 return -ENODATA;
710
711         return IIO_VAL_INT;
712 }
713
714 static int at91_adc_read_pressure(struct at91_adc_state *st, int chan, u16 *val)
715 {
716         *val = 0;
717         if (!st->touch_st.touching)
718                 return -ENODATA;
719         if (chan == AT91_SAMA5D2_TOUCH_P_CHAN_IDX)
720                 *val = at91_adc_touch_pressure(st);
721         else
722                 return -ENODATA;
723
724         return IIO_VAL_INT;
725 }
726
727 static int at91_adc_configure_trigger(struct iio_trigger *trig, bool state)
728 {
729         struct iio_dev *indio = iio_trigger_get_drvdata(trig);
730         struct at91_adc_state *st = iio_priv(indio);
731         u32 status = at91_adc_readl(st, AT91_SAMA5D2_TRGR);
732
733         /* clear TRGMOD */
734         status &= ~AT91_SAMA5D2_TRGR_TRGMOD_MASK;
735
736         if (state)
737                 status |= st->selected_trig->trgmod_value;
738
739         /* set/unset hw trigger */
740         at91_adc_writel(st, AT91_SAMA5D2_TRGR, status);
741
742         return 0;
743 }
744
745 static void at91_adc_reenable_trigger(struct iio_trigger *trig)
746 {
747         struct iio_dev *indio = iio_trigger_get_drvdata(trig);
748         struct at91_adc_state *st = iio_priv(indio);
749
750         /* if we are using DMA, we must not reenable irq after each trigger */
751         if (st->dma_st.dma_chan)
752                 return;
753
754         enable_irq(st->irq);
755
756         /* Needed to ACK the DRDY interruption */
757         at91_adc_readl(st, AT91_SAMA5D2_LCDR);
758 }
759
760 static const struct iio_trigger_ops at91_adc_trigger_ops = {
761         .set_trigger_state = &at91_adc_configure_trigger,
762         .reenable = &at91_adc_reenable_trigger,
763         .validate_device = iio_trigger_validate_own_device,
764 };
765
766 static int at91_adc_dma_size_done(struct at91_adc_state *st)
767 {
768         struct dma_tx_state state;
769         enum dma_status status;
770         int i, size;
771
772         status = dmaengine_tx_status(st->dma_st.dma_chan,
773                                      st->dma_st.dma_chan->cookie,
774                                      &state);
775         if (status != DMA_IN_PROGRESS)
776                 return 0;
777
778         /* Transferred length is size in bytes from end of buffer */
779         i = st->dma_st.rx_buf_sz - state.residue;
780
781         /* Return available bytes */
782         if (i >= st->dma_st.buf_idx)
783                 size = i - st->dma_st.buf_idx;
784         else
785                 size = st->dma_st.rx_buf_sz + i - st->dma_st.buf_idx;
786         return size;
787 }
788
789 static void at91_dma_buffer_done(void *data)
790 {
791         struct iio_dev *indio_dev = data;
792
793         iio_trigger_poll_chained(indio_dev->trig);
794 }
795
796 static int at91_adc_dma_start(struct iio_dev *indio_dev)
797 {
798         struct at91_adc_state *st = iio_priv(indio_dev);
799         struct dma_async_tx_descriptor *desc;
800         dma_cookie_t cookie;
801         int ret;
802         u8 bit;
803
804         if (!st->dma_st.dma_chan)
805                 return 0;
806
807         /* we start a new DMA, so set buffer index to start */
808         st->dma_st.buf_idx = 0;
809
810         /*
811          * compute buffer size w.r.t. watermark and enabled channels.
812          * scan_bytes is aligned so we need an exact size for DMA
813          */
814         st->dma_st.rx_buf_sz = 0;
815
816         for_each_set_bit(bit, indio_dev->active_scan_mask,
817                          indio_dev->num_channels) {
818                 struct iio_chan_spec const *chan =
819                                          at91_adc_chan_get(indio_dev, bit);
820
821                 if (!chan)
822                         continue;
823
824                 st->dma_st.rx_buf_sz += chan->scan_type.storagebits / 8;
825         }
826         st->dma_st.rx_buf_sz *= st->dma_st.watermark;
827
828         /* Prepare a DMA cyclic transaction */
829         desc = dmaengine_prep_dma_cyclic(st->dma_st.dma_chan,
830                                          st->dma_st.rx_dma_buf,
831                                          st->dma_st.rx_buf_sz,
832                                          st->dma_st.rx_buf_sz / 2,
833                                          DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT);
834
835         if (!desc) {
836                 dev_err(&indio_dev->dev, "cannot prepare DMA cyclic\n");
837                 return -EBUSY;
838         }
839
840         desc->callback = at91_dma_buffer_done;
841         desc->callback_param = indio_dev;
842
843         cookie = dmaengine_submit(desc);
844         ret = dma_submit_error(cookie);
845         if (ret) {
846                 dev_err(&indio_dev->dev, "cannot submit DMA cyclic\n");
847                 dmaengine_terminate_async(st->dma_st.dma_chan);
848                 return ret;
849         }
850
851         /* enable general overrun error signaling */
852         at91_adc_writel(st, AT91_SAMA5D2_IER, AT91_SAMA5D2_IER_GOVRE);
853         /* Issue pending DMA requests */
854         dma_async_issue_pending(st->dma_st.dma_chan);
855
856         /* consider current time as DMA start time for timestamps */
857         st->dma_st.dma_ts = iio_get_time_ns(indio_dev);
858
859         dev_dbg(&indio_dev->dev, "DMA cyclic started\n");
860
861         return 0;
862 }
863
864 static bool at91_adc_buffer_check_use_irq(struct iio_dev *indio,
865                                           struct at91_adc_state *st)
866 {
867         /* if using DMA, we do not use our own IRQ (we use DMA-controller) */
868         if (st->dma_st.dma_chan)
869                 return false;
870         /* if the trigger is not ours, then it has its own IRQ */
871         if (iio_trigger_validate_own_device(indio->trig, indio))
872                 return false;
873         return true;
874 }
875
876 static bool at91_adc_current_chan_is_touch(struct iio_dev *indio_dev)
877 {
878         struct at91_adc_state *st = iio_priv(indio_dev);
879
880         return !!bitmap_subset(indio_dev->active_scan_mask,
881                                &st->touch_st.channels_bitmask,
882                                AT91_SAMA5D2_MAX_CHAN_IDX + 1);
883 }
884
885 static int at91_adc_buffer_prepare(struct iio_dev *indio_dev)
886 {
887         int ret;
888         u8 bit;
889         struct at91_adc_state *st = iio_priv(indio_dev);
890
891         /* check if we are enabling triggered buffer or the touchscreen */
892         if (at91_adc_current_chan_is_touch(indio_dev))
893                 return at91_adc_configure_touch(st, true);
894
895         /* if we are not in triggered mode, we cannot enable the buffer. */
896         if (!(indio_dev->currentmode & INDIO_ALL_TRIGGERED_MODES))
897                 return -EINVAL;
898
899         /* we continue with the triggered buffer */
900         ret = at91_adc_dma_start(indio_dev);
901         if (ret) {
902                 dev_err(&indio_dev->dev, "buffer prepare failed\n");
903                 return ret;
904         }
905
906         for_each_set_bit(bit, indio_dev->active_scan_mask,
907                          indio_dev->num_channels) {
908                 struct iio_chan_spec const *chan =
909                                         at91_adc_chan_get(indio_dev, bit);
910                 u32 cor;
911
912                 if (!chan)
913                         continue;
914                 /* these channel types cannot be handled by this trigger */
915                 if (chan->type == IIO_POSITIONRELATIVE ||
916                     chan->type == IIO_PRESSURE)
917                         continue;
918
919                 cor = at91_adc_readl(st, AT91_SAMA5D2_COR);
920
921                 if (chan->differential)
922                         cor |= (BIT(chan->channel) | BIT(chan->channel2)) <<
923                                 AT91_SAMA5D2_COR_DIFF_OFFSET;
924                 else
925                         cor &= ~(BIT(chan->channel) <<
926                                AT91_SAMA5D2_COR_DIFF_OFFSET);
927
928                 at91_adc_writel(st, AT91_SAMA5D2_COR, cor);
929
930                 at91_adc_writel(st, AT91_SAMA5D2_CHER, BIT(chan->channel));
931         }
932
933         if (at91_adc_buffer_check_use_irq(indio_dev, st))
934                 at91_adc_writel(st, AT91_SAMA5D2_IER, AT91_SAMA5D2_IER_DRDY);
935
936         return 0;
937 }
938
939 static int at91_adc_buffer_postdisable(struct iio_dev *indio_dev)
940 {
941         struct at91_adc_state *st = iio_priv(indio_dev);
942         u8 bit;
943
944         /* check if we are disabling triggered buffer or the touchscreen */
945         if (at91_adc_current_chan_is_touch(indio_dev))
946                 return at91_adc_configure_touch(st, false);
947
948         /* if we are not in triggered mode, nothing to do here */
949         if (!(indio_dev->currentmode & INDIO_ALL_TRIGGERED_MODES))
950                 return -EINVAL;
951
952         /*
953          * For each enable channel we must disable it in hardware.
954          * In the case of DMA, we must read the last converted value
955          * to clear EOC status and not get a possible interrupt later.
956          * This value is being read by DMA from LCDR anyway, so it's not lost.
957          */
958         for_each_set_bit(bit, indio_dev->active_scan_mask,
959                          indio_dev->num_channels) {
960                 struct iio_chan_spec const *chan =
961                                         at91_adc_chan_get(indio_dev, bit);
962
963                 if (!chan)
964                         continue;
965                 /* these channel types are virtual, no need to do anything */
966                 if (chan->type == IIO_POSITIONRELATIVE ||
967                     chan->type == IIO_PRESSURE)
968                         continue;
969
970                 at91_adc_writel(st, AT91_SAMA5D2_CHDR, BIT(chan->channel));
971
972                 if (st->dma_st.dma_chan)
973                         at91_adc_readl(st, chan->address);
974         }
975
976         if (at91_adc_buffer_check_use_irq(indio_dev, st))
977                 at91_adc_writel(st, AT91_SAMA5D2_IDR, AT91_SAMA5D2_IER_DRDY);
978
979         /* read overflow register to clear possible overflow status */
980         at91_adc_readl(st, AT91_SAMA5D2_OVER);
981
982         /* if we are using DMA we must clear registers and end DMA */
983         if (st->dma_st.dma_chan)
984                 dmaengine_terminate_sync(st->dma_st.dma_chan);
985
986         return 0;
987 }
988
989 static const struct iio_buffer_setup_ops at91_buffer_setup_ops = {
990         .postdisable = &at91_adc_buffer_postdisable,
991 };
992
993 static struct iio_trigger *at91_adc_allocate_trigger(struct iio_dev *indio,
994                                                      char *trigger_name)
995 {
996         struct iio_trigger *trig;
997         int ret;
998
999         trig = devm_iio_trigger_alloc(&indio->dev, "%s-dev%d-%s", indio->name,
1000                                       indio->id, trigger_name);
1001         if (!trig)
1002                 return NULL;
1003
1004         trig->dev.parent = indio->dev.parent;
1005         iio_trigger_set_drvdata(trig, indio);
1006         trig->ops = &at91_adc_trigger_ops;
1007
1008         ret = devm_iio_trigger_register(&indio->dev, trig);
1009         if (ret)
1010                 return ERR_PTR(ret);
1011
1012         return trig;
1013 }
1014 static void at91_adc_trigger_handler_nodma(struct iio_dev *indio_dev,
1015                                            struct iio_poll_func *pf)
1016 {
1017         struct at91_adc_state *st = iio_priv(indio_dev);
1018         int i = 0;
1019         int val;
1020         u8 bit;
1021         u32 mask = at91_adc_active_scan_mask_to_reg(indio_dev);
1022         unsigned int timeout = 50;
1023
1024         /*
1025          * Check if the conversion is ready. If not, wait a little bit, and
1026          * in case of timeout exit with an error.
1027          */
1028         while ((at91_adc_readl(st, AT91_SAMA5D2_ISR) & mask) != mask &&
1029                timeout) {
1030                 usleep_range(50, 100);
1031                 timeout--;
1032         }
1033
1034         /* Cannot read data, not ready. Continue without reporting data */
1035         if (!timeout)
1036                 return;
1037
1038         for_each_set_bit(bit, indio_dev->active_scan_mask,
1039                          indio_dev->num_channels) {
1040                 struct iio_chan_spec const *chan =
1041                                         at91_adc_chan_get(indio_dev, bit);
1042
1043                 if (!chan)
1044                         continue;
1045                 /*
1046                  * Our external trigger only supports the voltage channels.
1047                  * In case someone requested a different type of channel
1048                  * just put zeroes to buffer.
1049                  * This should not happen because we check the scan mode
1050                  * and scan mask when we enable the buffer, and we don't allow
1051                  * the buffer to start with a mixed mask (voltage and something
1052                  * else).
1053                  * Thus, emit a warning.
1054                  */
1055                 if (chan->type == IIO_VOLTAGE) {
1056                         val = at91_adc_readl(st, chan->address);
1057                         at91_adc_adjust_val_osr(st, &val);
1058                         st->buffer[i] = val;
1059                 } else {
1060                         st->buffer[i] = 0;
1061                         WARN(true, "This trigger cannot handle this type of channel");
1062                 }
1063                 i++;
1064         }
1065         iio_push_to_buffers_with_timestamp(indio_dev, st->buffer,
1066                                            pf->timestamp);
1067 }
1068
1069 static void at91_adc_trigger_handler_dma(struct iio_dev *indio_dev)
1070 {
1071         struct at91_adc_state *st = iio_priv(indio_dev);
1072         int transferred_len = at91_adc_dma_size_done(st);
1073         s64 ns = iio_get_time_ns(indio_dev);
1074         s64 interval;
1075         int sample_index = 0, sample_count, sample_size;
1076
1077         u32 status = at91_adc_readl(st, AT91_SAMA5D2_ISR);
1078         /* if we reached this point, we cannot sample faster */
1079         if (status & AT91_SAMA5D2_IER_GOVRE)
1080                 pr_info_ratelimited("%s: conversion overrun detected\n",
1081                                     indio_dev->name);
1082
1083         sample_size = div_s64(st->dma_st.rx_buf_sz, st->dma_st.watermark);
1084
1085         sample_count = div_s64(transferred_len, sample_size);
1086
1087         /*
1088          * interval between samples is total time since last transfer handling
1089          * divided by the number of samples (total size divided by sample size)
1090          */
1091         interval = div_s64((ns - st->dma_st.dma_ts), sample_count);
1092
1093         while (transferred_len >= sample_size) {
1094                 /*
1095                  * for all the values in the current sample,
1096                  * adjust the values inside the buffer for oversampling
1097                  */
1098                 at91_adc_adjust_val_osr_array(st,
1099                                         &st->dma_st.rx_buf[st->dma_st.buf_idx],
1100                                         sample_size);
1101
1102                 iio_push_to_buffers_with_timestamp(indio_dev,
1103                                 (st->dma_st.rx_buf + st->dma_st.buf_idx),
1104                                 (st->dma_st.dma_ts + interval * sample_index));
1105                 /* adjust remaining length */
1106                 transferred_len -= sample_size;
1107                 /* adjust buffer index */
1108                 st->dma_st.buf_idx += sample_size;
1109                 /* in case of reaching end of buffer, reset index */
1110                 if (st->dma_st.buf_idx >= st->dma_st.rx_buf_sz)
1111                         st->dma_st.buf_idx = 0;
1112                 sample_index++;
1113         }
1114         /* adjust saved time for next transfer handling */
1115         st->dma_st.dma_ts = iio_get_time_ns(indio_dev);
1116 }
1117
1118 static irqreturn_t at91_adc_trigger_handler(int irq, void *p)
1119 {
1120         struct iio_poll_func *pf = p;
1121         struct iio_dev *indio_dev = pf->indio_dev;
1122         struct at91_adc_state *st = iio_priv(indio_dev);
1123
1124         /*
1125          * If it's not our trigger, start a conversion now, as we are
1126          * actually polling the trigger now.
1127          */
1128         if (iio_trigger_validate_own_device(indio_dev->trig, indio_dev))
1129                 at91_adc_writel(st, AT91_SAMA5D2_CR, AT91_SAMA5D2_CR_START);
1130
1131         if (st->dma_st.dma_chan)
1132                 at91_adc_trigger_handler_dma(indio_dev);
1133         else
1134                 at91_adc_trigger_handler_nodma(indio_dev, pf);
1135
1136         iio_trigger_notify_done(indio_dev->trig);
1137
1138         return IRQ_HANDLED;
1139 }
1140
1141 static unsigned at91_adc_startup_time(unsigned startup_time_min,
1142                                       unsigned adc_clk_khz)
1143 {
1144         static const unsigned int startup_lookup[] = {
1145                   0,   8,  16,  24,
1146                  64,  80,  96, 112,
1147                 512, 576, 640, 704,
1148                 768, 832, 896, 960
1149                 };
1150         unsigned ticks_min, i;
1151
1152         /*
1153          * Since the adc frequency is checked before, there is no reason
1154          * to not meet the startup time constraint.
1155          */
1156
1157         ticks_min = startup_time_min * adc_clk_khz / 1000;
1158         for (i = 0; i < ARRAY_SIZE(startup_lookup); i++)
1159                 if (startup_lookup[i] > ticks_min)
1160                         break;
1161
1162         return i;
1163 }
1164
1165 static void at91_adc_setup_samp_freq(struct iio_dev *indio_dev, unsigned freq)
1166 {
1167         struct at91_adc_state *st = iio_priv(indio_dev);
1168         unsigned f_per, prescal, startup, mr;
1169
1170         f_per = clk_get_rate(st->per_clk);
1171         prescal = (f_per / (2 * freq)) - 1;
1172
1173         startup = at91_adc_startup_time(st->soc_info.startup_time,
1174                                         freq / 1000);
1175
1176         mr = at91_adc_readl(st, AT91_SAMA5D2_MR);
1177         mr &= ~(AT91_SAMA5D2_MR_STARTUP_MASK | AT91_SAMA5D2_MR_PRESCAL_MASK);
1178         mr |= AT91_SAMA5D2_MR_STARTUP(startup);
1179         mr |= AT91_SAMA5D2_MR_PRESCAL(prescal);
1180         at91_adc_writel(st, AT91_SAMA5D2_MR, mr);
1181
1182         dev_dbg(&indio_dev->dev, "freq: %u, startup: %u, prescal: %u\n",
1183                 freq, startup, prescal);
1184         st->current_sample_rate = freq;
1185 }
1186
1187 static inline unsigned at91_adc_get_sample_freq(struct at91_adc_state *st)
1188 {
1189         return st->current_sample_rate;
1190 }
1191
1192 static void at91_adc_touch_data_handler(struct iio_dev *indio_dev)
1193 {
1194         struct at91_adc_state *st = iio_priv(indio_dev);
1195         u8 bit;
1196         u16 val;
1197         int i = 0;
1198
1199         for_each_set_bit(bit, indio_dev->active_scan_mask,
1200                          AT91_SAMA5D2_MAX_CHAN_IDX + 1) {
1201                 struct iio_chan_spec const *chan =
1202                                          at91_adc_chan_get(indio_dev, bit);
1203
1204                 if (chan->type == IIO_POSITIONRELATIVE)
1205                         at91_adc_read_position(st, chan->channel, &val);
1206                 else if (chan->type == IIO_PRESSURE)
1207                         at91_adc_read_pressure(st, chan->channel, &val);
1208                 else
1209                         continue;
1210                 st->buffer[i] = val;
1211                 i++;
1212         }
1213         /*
1214          * Schedule work to push to buffers.
1215          * This is intended to push to the callback buffer that another driver
1216          * registered. We are still in a handler from our IRQ. If we push
1217          * directly, it means the other driver has it's callback called
1218          * from our IRQ context. Which is something we better avoid.
1219          * Let's schedule it after our IRQ is completed.
1220          */
1221         schedule_work(&st->touch_st.workq);
1222 }
1223
1224 static void at91_adc_pen_detect_interrupt(struct at91_adc_state *st)
1225 {
1226         at91_adc_writel(st, AT91_SAMA5D2_IDR, AT91_SAMA5D2_IER_PEN);
1227         at91_adc_writel(st, AT91_SAMA5D2_IER, AT91_SAMA5D2_IER_NOPEN |
1228                         AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1229                         AT91_SAMA5D2_IER_PRDY);
1230         at91_adc_writel(st, AT91_SAMA5D2_TRGR,
1231                         AT91_SAMA5D2_TRGR_TRGMOD_PERIODIC |
1232                         AT91_SAMA5D2_TRGR_TRGPER(st->touch_st.sample_period_val));
1233         st->touch_st.touching = true;
1234 }
1235
1236 static void at91_adc_no_pen_detect_interrupt(struct iio_dev *indio_dev)
1237 {
1238         struct at91_adc_state *st = iio_priv(indio_dev);
1239
1240         at91_adc_writel(st, AT91_SAMA5D2_TRGR,
1241                         AT91_SAMA5D2_TRGR_TRGMOD_NO_TRIGGER);
1242         at91_adc_writel(st, AT91_SAMA5D2_IDR, AT91_SAMA5D2_IER_NOPEN |
1243                         AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1244                         AT91_SAMA5D2_IER_PRDY);
1245         st->touch_st.touching = false;
1246
1247         at91_adc_touch_data_handler(indio_dev);
1248
1249         at91_adc_writel(st, AT91_SAMA5D2_IER, AT91_SAMA5D2_IER_PEN);
1250 }
1251
1252 static void at91_adc_workq_handler(struct work_struct *workq)
1253 {
1254         struct at91_adc_touch *touch_st = container_of(workq,
1255                                         struct at91_adc_touch, workq);
1256         struct at91_adc_state *st = container_of(touch_st,
1257                                         struct at91_adc_state, touch_st);
1258         struct iio_dev *indio_dev = st->indio_dev;
1259
1260         iio_push_to_buffers(indio_dev, st->buffer);
1261 }
1262
1263 static irqreturn_t at91_adc_interrupt(int irq, void *private)
1264 {
1265         struct iio_dev *indio = private;
1266         struct at91_adc_state *st = iio_priv(indio);
1267         u32 status = at91_adc_readl(st, AT91_SAMA5D2_ISR);
1268         u32 imr = at91_adc_readl(st, AT91_SAMA5D2_IMR);
1269         u32 rdy_mask = AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1270                         AT91_SAMA5D2_IER_PRDY;
1271
1272         if (!(status & imr))
1273                 return IRQ_NONE;
1274         if (status & AT91_SAMA5D2_IER_PEN) {
1275                 /* pen detected IRQ */
1276                 at91_adc_pen_detect_interrupt(st);
1277         } else if ((status & AT91_SAMA5D2_IER_NOPEN)) {
1278                 /* nopen detected IRQ */
1279                 at91_adc_no_pen_detect_interrupt(indio);
1280         } else if ((status & AT91_SAMA5D2_ISR_PENS) &&
1281                    ((status & rdy_mask) == rdy_mask)) {
1282                 /* periodic trigger IRQ - during pen sense */
1283                 at91_adc_touch_data_handler(indio);
1284         } else if (status & AT91_SAMA5D2_ISR_PENS) {
1285                 /*
1286                  * touching, but the measurements are not ready yet.
1287                  * read and ignore.
1288                  */
1289                 status = at91_adc_readl(st, AT91_SAMA5D2_XPOSR);
1290                 status = at91_adc_readl(st, AT91_SAMA5D2_YPOSR);
1291                 status = at91_adc_readl(st, AT91_SAMA5D2_PRESSR);
1292         } else if (iio_buffer_enabled(indio) &&
1293                    (status & AT91_SAMA5D2_IER_DRDY)) {
1294                 /* triggered buffer without DMA */
1295                 disable_irq_nosync(irq);
1296                 iio_trigger_poll(indio->trig);
1297         } else if (iio_buffer_enabled(indio) && st->dma_st.dma_chan) {
1298                 /* triggered buffer with DMA - should not happen */
1299                 disable_irq_nosync(irq);
1300                 WARN(true, "Unexpected irq occurred\n");
1301         } else if (!iio_buffer_enabled(indio)) {
1302                 /* software requested conversion */
1303                 st->conversion_value = at91_adc_readl(st, st->chan->address);
1304                 st->conversion_done = true;
1305                 wake_up_interruptible(&st->wq_data_available);
1306         }
1307         return IRQ_HANDLED;
1308 }
1309
1310 static int at91_adc_read_info_raw(struct iio_dev *indio_dev,
1311                                   struct iio_chan_spec const *chan, int *val)
1312 {
1313         struct at91_adc_state *st = iio_priv(indio_dev);
1314         u32 cor = 0;
1315         u16 tmp_val;
1316         int ret;
1317
1318         /*
1319          * Keep in mind that we cannot use software trigger or touchscreen
1320          * if external trigger is enabled
1321          */
1322         if (chan->type == IIO_POSITIONRELATIVE) {
1323                 ret = iio_device_claim_direct_mode(indio_dev);
1324                 if (ret)
1325                         return ret;
1326                 mutex_lock(&st->lock);
1327
1328                 ret = at91_adc_read_position(st, chan->channel,
1329                                              &tmp_val);
1330                 *val = tmp_val;
1331                 mutex_unlock(&st->lock);
1332                 iio_device_release_direct_mode(indio_dev);
1333
1334                 return at91_adc_adjust_val_osr(st, val);
1335         }
1336         if (chan->type == IIO_PRESSURE) {
1337                 ret = iio_device_claim_direct_mode(indio_dev);
1338                 if (ret)
1339                         return ret;
1340                 mutex_lock(&st->lock);
1341
1342                 ret = at91_adc_read_pressure(st, chan->channel,
1343                                              &tmp_val);
1344                 *val = tmp_val;
1345                 mutex_unlock(&st->lock);
1346                 iio_device_release_direct_mode(indio_dev);
1347
1348                 return at91_adc_adjust_val_osr(st, val);
1349         }
1350
1351         /* in this case we have a voltage channel */
1352
1353         ret = iio_device_claim_direct_mode(indio_dev);
1354         if (ret)
1355                 return ret;
1356         mutex_lock(&st->lock);
1357
1358         st->chan = chan;
1359
1360         if (chan->differential)
1361                 cor = (BIT(chan->channel) | BIT(chan->channel2)) <<
1362                       AT91_SAMA5D2_COR_DIFF_OFFSET;
1363
1364         at91_adc_writel(st, AT91_SAMA5D2_COR, cor);
1365         at91_adc_writel(st, AT91_SAMA5D2_CHER, BIT(chan->channel));
1366         at91_adc_writel(st, AT91_SAMA5D2_IER, BIT(chan->channel));
1367         at91_adc_writel(st, AT91_SAMA5D2_CR, AT91_SAMA5D2_CR_START);
1368
1369         ret = wait_event_interruptible_timeout(st->wq_data_available,
1370                                                st->conversion_done,
1371                                                msecs_to_jiffies(1000));
1372         if (ret == 0)
1373                 ret = -ETIMEDOUT;
1374
1375         if (ret > 0) {
1376                 *val = st->conversion_value;
1377                 ret = at91_adc_adjust_val_osr(st, val);
1378                 if (chan->scan_type.sign == 's')
1379                         *val = sign_extend32(*val, 11);
1380                 st->conversion_done = false;
1381         }
1382
1383         at91_adc_writel(st, AT91_SAMA5D2_IDR, BIT(chan->channel));
1384         at91_adc_writel(st, AT91_SAMA5D2_CHDR, BIT(chan->channel));
1385
1386         /* Needed to ACK the DRDY interruption */
1387         at91_adc_readl(st, AT91_SAMA5D2_LCDR);
1388
1389         mutex_unlock(&st->lock);
1390
1391         iio_device_release_direct_mode(indio_dev);
1392         return ret;
1393 }
1394
1395 static int at91_adc_read_raw(struct iio_dev *indio_dev,
1396                              struct iio_chan_spec const *chan,
1397                              int *val, int *val2, long mask)
1398 {
1399         struct at91_adc_state *st = iio_priv(indio_dev);
1400
1401         switch (mask) {
1402         case IIO_CHAN_INFO_RAW:
1403                 return at91_adc_read_info_raw(indio_dev, chan, val);
1404         case IIO_CHAN_INFO_SCALE:
1405                 *val = st->vref_uv / 1000;
1406                 if (chan->differential)
1407                         *val *= 2;
1408                 *val2 = chan->scan_type.realbits;
1409                 return IIO_VAL_FRACTIONAL_LOG2;
1410
1411         case IIO_CHAN_INFO_SAMP_FREQ:
1412                 *val = at91_adc_get_sample_freq(st);
1413                 return IIO_VAL_INT;
1414
1415         case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1416                 *val = st->oversampling_ratio;
1417                 return IIO_VAL_INT;
1418
1419         default:
1420                 return -EINVAL;
1421         }
1422 }
1423
1424 static int at91_adc_write_raw(struct iio_dev *indio_dev,
1425                               struct iio_chan_spec const *chan,
1426                               int val, int val2, long mask)
1427 {
1428         struct at91_adc_state *st = iio_priv(indio_dev);
1429
1430         switch (mask) {
1431         case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1432                 if ((val != AT91_OSR_1SAMPLES) && (val != AT91_OSR_4SAMPLES) &&
1433                     (val != AT91_OSR_16SAMPLES))
1434                         return -EINVAL;
1435                 /* if no change, optimize out */
1436                 if (val == st->oversampling_ratio)
1437                         return 0;
1438                 st->oversampling_ratio = val;
1439                 /* update ratio */
1440                 at91_adc_config_emr(st);
1441                 return 0;
1442         case IIO_CHAN_INFO_SAMP_FREQ:
1443                 if (val < st->soc_info.min_sample_rate ||
1444                     val > st->soc_info.max_sample_rate)
1445                         return -EINVAL;
1446
1447                 at91_adc_setup_samp_freq(indio_dev, val);
1448                 return 0;
1449         default:
1450                 return -EINVAL;
1451         }
1452 }
1453
1454 static void at91_adc_dma_init(struct platform_device *pdev)
1455 {
1456         struct iio_dev *indio_dev = platform_get_drvdata(pdev);
1457         struct at91_adc_state *st = iio_priv(indio_dev);
1458         struct dma_slave_config config = {0};
1459         /*
1460          * We make the buffer double the size of the fifo,
1461          * such that DMA uses one half of the buffer (full fifo size)
1462          * and the software uses the other half to read/write.
1463          */
1464         unsigned int pages = DIV_ROUND_UP(AT91_HWFIFO_MAX_SIZE *
1465                                           AT91_BUFFER_MAX_CONVERSION_BYTES * 2,
1466                                           PAGE_SIZE);
1467
1468         if (st->dma_st.dma_chan)
1469                 return;
1470
1471         st->dma_st.dma_chan = dma_request_chan(&pdev->dev, "rx");
1472         if (IS_ERR(st->dma_st.dma_chan))  {
1473                 dev_info(&pdev->dev, "can't get DMA channel\n");
1474                 st->dma_st.dma_chan = NULL;
1475                 goto dma_exit;
1476         }
1477
1478         st->dma_st.rx_buf = dma_alloc_coherent(st->dma_st.dma_chan->device->dev,
1479                                                pages * PAGE_SIZE,
1480                                                &st->dma_st.rx_dma_buf,
1481                                                GFP_KERNEL);
1482         if (!st->dma_st.rx_buf) {
1483                 dev_info(&pdev->dev, "can't allocate coherent DMA area\n");
1484                 goto dma_chan_disable;
1485         }
1486
1487         /* Configure DMA channel to read data register */
1488         config.direction = DMA_DEV_TO_MEM;
1489         config.src_addr = (phys_addr_t)(st->dma_st.phys_addr
1490                           + AT91_SAMA5D2_LCDR);
1491         config.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
1492         config.src_maxburst = 1;
1493         config.dst_maxburst = 1;
1494
1495         if (dmaengine_slave_config(st->dma_st.dma_chan, &config)) {
1496                 dev_info(&pdev->dev, "can't configure DMA slave\n");
1497                 goto dma_free_area;
1498         }
1499
1500         dev_info(&pdev->dev, "using %s for rx DMA transfers\n",
1501                  dma_chan_name(st->dma_st.dma_chan));
1502
1503         return;
1504
1505 dma_free_area:
1506         dma_free_coherent(st->dma_st.dma_chan->device->dev, pages * PAGE_SIZE,
1507                           st->dma_st.rx_buf, st->dma_st.rx_dma_buf);
1508 dma_chan_disable:
1509         dma_release_channel(st->dma_st.dma_chan);
1510         st->dma_st.dma_chan = NULL;
1511 dma_exit:
1512         dev_info(&pdev->dev, "continuing without DMA support\n");
1513 }
1514
1515 static void at91_adc_dma_disable(struct platform_device *pdev)
1516 {
1517         struct iio_dev *indio_dev = platform_get_drvdata(pdev);
1518         struct at91_adc_state *st = iio_priv(indio_dev);
1519         unsigned int pages = DIV_ROUND_UP(AT91_HWFIFO_MAX_SIZE *
1520                                           AT91_BUFFER_MAX_CONVERSION_BYTES * 2,
1521                                           PAGE_SIZE);
1522
1523         /* if we are not using DMA, just return */
1524         if (!st->dma_st.dma_chan)
1525                 return;
1526
1527         /* wait for all transactions to be terminated first*/
1528         dmaengine_terminate_sync(st->dma_st.dma_chan);
1529
1530         dma_free_coherent(st->dma_st.dma_chan->device->dev, pages * PAGE_SIZE,
1531                           st->dma_st.rx_buf, st->dma_st.rx_dma_buf);
1532         dma_release_channel(st->dma_st.dma_chan);
1533         st->dma_st.dma_chan = NULL;
1534
1535         dev_info(&pdev->dev, "continuing without DMA support\n");
1536 }
1537
1538 static int at91_adc_set_watermark(struct iio_dev *indio_dev, unsigned int val)
1539 {
1540         struct at91_adc_state *st = iio_priv(indio_dev);
1541         int ret;
1542
1543         if (val > AT91_HWFIFO_MAX_SIZE)
1544                 return -EINVAL;
1545
1546         if (!st->selected_trig->hw_trig) {
1547                 dev_dbg(&indio_dev->dev, "we need hw trigger for DMA\n");
1548                 return 0;
1549         }
1550
1551         dev_dbg(&indio_dev->dev, "new watermark is %u\n", val);
1552         st->dma_st.watermark = val;
1553
1554         /*
1555          * The logic here is: if we have watermark 1, it means we do
1556          * each conversion with it's own IRQ, thus we don't need DMA.
1557          * If the watermark is higher, we do DMA to do all the transfers in bulk
1558          */
1559
1560         if (val == 1)
1561                 at91_adc_dma_disable(to_platform_device(&indio_dev->dev));
1562         else if (val > 1)
1563                 at91_adc_dma_init(to_platform_device(&indio_dev->dev));
1564
1565         /*
1566          * We can start the DMA only after setting the watermark and
1567          * having the DMA initialization completed
1568          */
1569         ret = at91_adc_buffer_prepare(indio_dev);
1570         if (ret)
1571                 at91_adc_dma_disable(to_platform_device(&indio_dev->dev));
1572
1573         return ret;
1574 }
1575
1576 static int at91_adc_update_scan_mode(struct iio_dev *indio_dev,
1577                                      const unsigned long *scan_mask)
1578 {
1579         struct at91_adc_state *st = iio_priv(indio_dev);
1580
1581         if (bitmap_subset(scan_mask, &st->touch_st.channels_bitmask,
1582                           AT91_SAMA5D2_MAX_CHAN_IDX + 1))
1583                 return 0;
1584         /*
1585          * if the new bitmap is a combination of touchscreen and regular
1586          * channels, then we are not fine
1587          */
1588         if (bitmap_intersects(&st->touch_st.channels_bitmask, scan_mask,
1589                               AT91_SAMA5D2_MAX_CHAN_IDX + 1))
1590                 return -EINVAL;
1591         return 0;
1592 }
1593
1594 static void at91_adc_hw_init(struct iio_dev *indio_dev)
1595 {
1596         struct at91_adc_state *st = iio_priv(indio_dev);
1597
1598         at91_adc_writel(st, AT91_SAMA5D2_CR, AT91_SAMA5D2_CR_SWRST);
1599         at91_adc_writel(st, AT91_SAMA5D2_IDR, 0xffffffff);
1600         /*
1601          * Transfer field must be set to 2 according to the datasheet and
1602          * allows different analog settings for each channel.
1603          */
1604         at91_adc_writel(st, AT91_SAMA5D2_MR,
1605                         AT91_SAMA5D2_MR_TRANSFER(2) | AT91_SAMA5D2_MR_ANACH);
1606
1607         at91_adc_setup_samp_freq(indio_dev, st->soc_info.min_sample_rate);
1608
1609         /* configure extended mode register */
1610         at91_adc_config_emr(st);
1611 }
1612
1613 static ssize_t at91_adc_get_fifo_state(struct device *dev,
1614                                        struct device_attribute *attr, char *buf)
1615 {
1616         struct iio_dev *indio_dev = dev_get_drvdata(dev);
1617         struct at91_adc_state *st = iio_priv(indio_dev);
1618
1619         return scnprintf(buf, PAGE_SIZE, "%d\n", !!st->dma_st.dma_chan);
1620 }
1621
1622 static ssize_t at91_adc_get_watermark(struct device *dev,
1623                                       struct device_attribute *attr, char *buf)
1624 {
1625         struct iio_dev *indio_dev = dev_get_drvdata(dev);
1626         struct at91_adc_state *st = iio_priv(indio_dev);
1627
1628         return scnprintf(buf, PAGE_SIZE, "%d\n", st->dma_st.watermark);
1629 }
1630
1631 static IIO_DEVICE_ATTR(hwfifo_enabled, 0444,
1632                        at91_adc_get_fifo_state, NULL, 0);
1633 static IIO_DEVICE_ATTR(hwfifo_watermark, 0444,
1634                        at91_adc_get_watermark, NULL, 0);
1635
1636 static IIO_CONST_ATTR(hwfifo_watermark_min, "2");
1637 static IIO_CONST_ATTR(hwfifo_watermark_max, AT91_HWFIFO_MAX_SIZE_STR);
1638
1639 static IIO_CONST_ATTR(oversampling_ratio_available,
1640                       __stringify(AT91_OSR_1SAMPLES) " "
1641                       __stringify(AT91_OSR_4SAMPLES) " "
1642                       __stringify(AT91_OSR_16SAMPLES));
1643
1644 static struct attribute *at91_adc_attributes[] = {
1645         &iio_const_attr_oversampling_ratio_available.dev_attr.attr,
1646         NULL,
1647 };
1648
1649 static const struct attribute_group at91_adc_attribute_group = {
1650         .attrs = at91_adc_attributes,
1651 };
1652
1653 static const struct attribute *at91_adc_fifo_attributes[] = {
1654         &iio_const_attr_hwfifo_watermark_min.dev_attr.attr,
1655         &iio_const_attr_hwfifo_watermark_max.dev_attr.attr,
1656         &iio_dev_attr_hwfifo_watermark.dev_attr.attr,
1657         &iio_dev_attr_hwfifo_enabled.dev_attr.attr,
1658         NULL,
1659 };
1660
1661 static const struct iio_info at91_adc_info = {
1662         .attrs = &at91_adc_attribute_group,
1663         .read_raw = &at91_adc_read_raw,
1664         .write_raw = &at91_adc_write_raw,
1665         .update_scan_mode = &at91_adc_update_scan_mode,
1666         .of_xlate = &at91_adc_of_xlate,
1667         .hwfifo_set_watermark = &at91_adc_set_watermark,
1668 };
1669
1670 static int at91_adc_buffer_and_trigger_init(struct device *dev,
1671                                             struct iio_dev *indio)
1672 {
1673         struct at91_adc_state *st = iio_priv(indio);
1674         const struct attribute **fifo_attrs;
1675         int ret;
1676
1677         if (st->selected_trig->hw_trig)
1678                 fifo_attrs = at91_adc_fifo_attributes;
1679         else
1680                 fifo_attrs = NULL;
1681
1682         ret = devm_iio_triggered_buffer_setup_ext(&indio->dev, indio,
1683                 &iio_pollfunc_store_time,
1684                 &at91_adc_trigger_handler, &at91_buffer_setup_ops, fifo_attrs);
1685         if (ret < 0) {
1686                 dev_err(dev, "couldn't initialize the buffer.\n");
1687                 return ret;
1688         }
1689
1690         if (!st->selected_trig->hw_trig)
1691                 return 0;
1692
1693         st->trig = at91_adc_allocate_trigger(indio, st->selected_trig->name);
1694         if (IS_ERR(st->trig)) {
1695                 dev_err(dev, "could not allocate trigger\n");
1696                 return PTR_ERR(st->trig);
1697         }
1698
1699         /*
1700          * Initially the iio buffer has a length of 2 and
1701          * a watermark of 1
1702          */
1703         st->dma_st.watermark = 1;
1704
1705         return 0;
1706 }
1707
1708 static int at91_adc_probe(struct platform_device *pdev)
1709 {
1710         struct iio_dev *indio_dev;
1711         struct at91_adc_state *st;
1712         struct resource *res;
1713         int ret, i;
1714         u32 edge_type = IRQ_TYPE_NONE;
1715
1716         indio_dev = devm_iio_device_alloc(&pdev->dev, sizeof(*st));
1717         if (!indio_dev)
1718                 return -ENOMEM;
1719
1720         indio_dev->name = dev_name(&pdev->dev);
1721         indio_dev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
1722         indio_dev->info = &at91_adc_info;
1723         indio_dev->channels = at91_adc_channels;
1724         indio_dev->num_channels = ARRAY_SIZE(at91_adc_channels);
1725
1726         st = iio_priv(indio_dev);
1727         st->indio_dev = indio_dev;
1728
1729         bitmap_set(&st->touch_st.channels_bitmask,
1730                    AT91_SAMA5D2_TOUCH_X_CHAN_IDX, 1);
1731         bitmap_set(&st->touch_st.channels_bitmask,
1732                    AT91_SAMA5D2_TOUCH_Y_CHAN_IDX, 1);
1733         bitmap_set(&st->touch_st.channels_bitmask,
1734                    AT91_SAMA5D2_TOUCH_P_CHAN_IDX, 1);
1735
1736         st->oversampling_ratio = AT91_OSR_1SAMPLES;
1737
1738         ret = of_property_read_u32(pdev->dev.of_node,
1739                                    "atmel,min-sample-rate-hz",
1740                                    &st->soc_info.min_sample_rate);
1741         if (ret) {
1742                 dev_err(&pdev->dev,
1743                         "invalid or missing value for atmel,min-sample-rate-hz\n");
1744                 return ret;
1745         }
1746
1747         ret = of_property_read_u32(pdev->dev.of_node,
1748                                    "atmel,max-sample-rate-hz",
1749                                    &st->soc_info.max_sample_rate);
1750         if (ret) {
1751                 dev_err(&pdev->dev,
1752                         "invalid or missing value for atmel,max-sample-rate-hz\n");
1753                 return ret;
1754         }
1755
1756         ret = of_property_read_u32(pdev->dev.of_node, "atmel,startup-time-ms",
1757                                    &st->soc_info.startup_time);
1758         if (ret) {
1759                 dev_err(&pdev->dev,
1760                         "invalid or missing value for atmel,startup-time-ms\n");
1761                 return ret;
1762         }
1763
1764         ret = of_property_read_u32(pdev->dev.of_node,
1765                                    "atmel,trigger-edge-type", &edge_type);
1766         if (ret) {
1767                 dev_dbg(&pdev->dev,
1768                         "atmel,trigger-edge-type not specified, only software trigger available\n");
1769         }
1770
1771         st->selected_trig = NULL;
1772
1773         /* find the right trigger, or no trigger at all */
1774         for (i = 0; i < AT91_SAMA5D2_HW_TRIG_CNT + 1; i++)
1775                 if (at91_adc_trigger_list[i].edge_type == edge_type) {
1776                         st->selected_trig = &at91_adc_trigger_list[i];
1777                         break;
1778                 }
1779
1780         if (!st->selected_trig) {
1781                 dev_err(&pdev->dev, "invalid external trigger edge value\n");
1782                 return -EINVAL;
1783         }
1784
1785         init_waitqueue_head(&st->wq_data_available);
1786         mutex_init(&st->lock);
1787         INIT_WORK(&st->touch_st.workq, at91_adc_workq_handler);
1788
1789         st->base = devm_platform_get_and_ioremap_resource(pdev, 0, &res);
1790         if (IS_ERR(st->base))
1791                 return PTR_ERR(st->base);
1792
1793         /* if we plan to use DMA, we need the physical address of the regs */
1794         st->dma_st.phys_addr = res->start;
1795
1796         st->irq = platform_get_irq(pdev, 0);
1797         if (st->irq <= 0) {
1798                 if (!st->irq)
1799                         st->irq = -ENXIO;
1800
1801                 return st->irq;
1802         }
1803
1804         st->per_clk = devm_clk_get(&pdev->dev, "adc_clk");
1805         if (IS_ERR(st->per_clk))
1806                 return PTR_ERR(st->per_clk);
1807
1808         st->reg = devm_regulator_get(&pdev->dev, "vddana");
1809         if (IS_ERR(st->reg))
1810                 return PTR_ERR(st->reg);
1811
1812         st->vref = devm_regulator_get(&pdev->dev, "vref");
1813         if (IS_ERR(st->vref))
1814                 return PTR_ERR(st->vref);
1815
1816         ret = devm_request_irq(&pdev->dev, st->irq, at91_adc_interrupt, 0,
1817                                pdev->dev.driver->name, indio_dev);
1818         if (ret)
1819                 return ret;
1820
1821         ret = regulator_enable(st->reg);
1822         if (ret)
1823                 return ret;
1824
1825         ret = regulator_enable(st->vref);
1826         if (ret)
1827                 goto reg_disable;
1828
1829         st->vref_uv = regulator_get_voltage(st->vref);
1830         if (st->vref_uv <= 0) {
1831                 ret = -EINVAL;
1832                 goto vref_disable;
1833         }
1834
1835         at91_adc_hw_init(indio_dev);
1836
1837         ret = clk_prepare_enable(st->per_clk);
1838         if (ret)
1839                 goto vref_disable;
1840
1841         platform_set_drvdata(pdev, indio_dev);
1842
1843         ret = at91_adc_buffer_and_trigger_init(&pdev->dev, indio_dev);
1844         if (ret < 0)
1845                 goto per_clk_disable_unprepare;
1846
1847         if (dma_coerce_mask_and_coherent(&indio_dev->dev, DMA_BIT_MASK(32)))
1848                 dev_info(&pdev->dev, "cannot set DMA mask to 32-bit\n");
1849
1850         ret = iio_device_register(indio_dev);
1851         if (ret < 0)
1852                 goto dma_disable;
1853
1854         if (st->selected_trig->hw_trig)
1855                 dev_info(&pdev->dev, "setting up trigger as %s\n",
1856                          st->selected_trig->name);
1857
1858         dev_info(&pdev->dev, "version: %x\n",
1859                  readl_relaxed(st->base + AT91_SAMA5D2_VERSION));
1860
1861         return 0;
1862
1863 dma_disable:
1864         at91_adc_dma_disable(pdev);
1865 per_clk_disable_unprepare:
1866         clk_disable_unprepare(st->per_clk);
1867 vref_disable:
1868         regulator_disable(st->vref);
1869 reg_disable:
1870         regulator_disable(st->reg);
1871         return ret;
1872 }
1873
1874 static int at91_adc_remove(struct platform_device *pdev)
1875 {
1876         struct iio_dev *indio_dev = platform_get_drvdata(pdev);
1877         struct at91_adc_state *st = iio_priv(indio_dev);
1878
1879         iio_device_unregister(indio_dev);
1880
1881         at91_adc_dma_disable(pdev);
1882
1883         clk_disable_unprepare(st->per_clk);
1884
1885         regulator_disable(st->vref);
1886         regulator_disable(st->reg);
1887
1888         return 0;
1889 }
1890
1891 static __maybe_unused int at91_adc_suspend(struct device *dev)
1892 {
1893         struct iio_dev *indio_dev = dev_get_drvdata(dev);
1894         struct at91_adc_state *st = iio_priv(indio_dev);
1895
1896         /*
1897          * Do a sofware reset of the ADC before we go to suspend.
1898          * this will ensure that all pins are free from being muxed by the ADC
1899          * and can be used by for other devices.
1900          * Otherwise, ADC will hog them and we can't go to suspend mode.
1901          */
1902         at91_adc_writel(st, AT91_SAMA5D2_CR, AT91_SAMA5D2_CR_SWRST);
1903
1904         clk_disable_unprepare(st->per_clk);
1905         regulator_disable(st->vref);
1906         regulator_disable(st->reg);
1907
1908         return pinctrl_pm_select_sleep_state(dev);
1909 }
1910
1911 static __maybe_unused int at91_adc_resume(struct device *dev)
1912 {
1913         struct iio_dev *indio_dev = dev_get_drvdata(dev);
1914         struct at91_adc_state *st = iio_priv(indio_dev);
1915         int ret;
1916
1917         ret = pinctrl_pm_select_default_state(dev);
1918         if (ret)
1919                 goto resume_failed;
1920
1921         ret = regulator_enable(st->reg);
1922         if (ret)
1923                 goto resume_failed;
1924
1925         ret = regulator_enable(st->vref);
1926         if (ret)
1927                 goto reg_disable_resume;
1928
1929         ret = clk_prepare_enable(st->per_clk);
1930         if (ret)
1931                 goto vref_disable_resume;
1932
1933         at91_adc_hw_init(indio_dev);
1934
1935         /* reconfiguring trigger hardware state */
1936         if (!iio_buffer_enabled(indio_dev))
1937                 return 0;
1938
1939         /* check if we are enabling triggered buffer or the touchscreen */
1940         if (at91_adc_current_chan_is_touch(indio_dev))
1941                 return at91_adc_configure_touch(st, true);
1942         else
1943                 return at91_adc_configure_trigger(st->trig, true);
1944
1945         /* not needed but more explicit */
1946         return 0;
1947
1948 vref_disable_resume:
1949         regulator_disable(st->vref);
1950 reg_disable_resume:
1951         regulator_disable(st->reg);
1952 resume_failed:
1953         dev_err(&indio_dev->dev, "failed to resume\n");
1954         return ret;
1955 }
1956
1957 static SIMPLE_DEV_PM_OPS(at91_adc_pm_ops, at91_adc_suspend, at91_adc_resume);
1958
1959 static const struct of_device_id at91_adc_dt_match[] = {
1960         {
1961                 .compatible = "atmel,sama5d2-adc",
1962         }, {
1963                 /* sentinel */
1964         }
1965 };
1966 MODULE_DEVICE_TABLE(of, at91_adc_dt_match);
1967
1968 static struct platform_driver at91_adc_driver = {
1969         .probe = at91_adc_probe,
1970         .remove = at91_adc_remove,
1971         .driver = {
1972                 .name = "at91-sama5d2_adc",
1973                 .of_match_table = at91_adc_dt_match,
1974                 .pm = &at91_adc_pm_ops,
1975         },
1976 };
1977 module_platform_driver(at91_adc_driver)
1978
1979 MODULE_AUTHOR("Ludovic Desroches <[email protected]>");
1980 MODULE_DESCRIPTION("Atmel AT91 SAMA5D2 ADC");
1981 MODULE_LICENSE("GPL v2");
This page took 0.149635 seconds and 4 git commands to generate.