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