GNU Linux-libre 4.14.324-gnu1
[releases.git] / drivers / iio / adc / at91_adc.c
1 /*
2  * Driver for the ADC present in the Atmel AT91 evaluation boards.
3  *
4  * Copyright 2011 Free Electrons
5  *
6  * Licensed under the GPLv2 or later.
7  */
8
9 #include <linux/bitmap.h>
10 #include <linux/bitops.h>
11 #include <linux/clk.h>
12 #include <linux/err.h>
13 #include <linux/io.h>
14 #include <linux/input.h>
15 #include <linux/interrupt.h>
16 #include <linux/jiffies.h>
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/of.h>
20 #include <linux/of_device.h>
21 #include <linux/platform_device.h>
22 #include <linux/sched.h>
23 #include <linux/slab.h>
24 #include <linux/wait.h>
25
26 #include <linux/platform_data/at91_adc.h>
27
28 #include <linux/iio/iio.h>
29 #include <linux/iio/buffer.h>
30 #include <linux/iio/trigger.h>
31 #include <linux/iio/trigger_consumer.h>
32 #include <linux/iio/triggered_buffer.h>
33 #include <linux/pinctrl/consumer.h>
34
35 /* Registers */
36 #define AT91_ADC_CR             0x00            /* Control Register */
37 #define         AT91_ADC_SWRST          (1 << 0)        /* Software Reset */
38 #define         AT91_ADC_START          (1 << 1)        /* Start Conversion */
39
40 #define AT91_ADC_MR             0x04            /* Mode Register */
41 #define         AT91_ADC_TSAMOD         (3 << 0)        /* ADC mode */
42 #define         AT91_ADC_TSAMOD_ADC_ONLY_MODE           (0 << 0)        /* ADC Mode */
43 #define         AT91_ADC_TSAMOD_TS_ONLY_MODE            (1 << 0)        /* Touch Screen Only Mode */
44 #define         AT91_ADC_TRGEN          (1 << 0)        /* Trigger Enable */
45 #define         AT91_ADC_TRGSEL         (7 << 1)        /* Trigger Selection */
46 #define                 AT91_ADC_TRGSEL_TC0             (0 << 1)
47 #define                 AT91_ADC_TRGSEL_TC1             (1 << 1)
48 #define                 AT91_ADC_TRGSEL_TC2             (2 << 1)
49 #define                 AT91_ADC_TRGSEL_EXTERNAL        (6 << 1)
50 #define         AT91_ADC_LOWRES         (1 << 4)        /* Low Resolution */
51 #define         AT91_ADC_SLEEP          (1 << 5)        /* Sleep Mode */
52 #define         AT91_ADC_PENDET         (1 << 6)        /* Pen contact detection enable */
53 #define         AT91_ADC_PRESCAL_9260   (0x3f << 8)     /* Prescalar Rate Selection */
54 #define         AT91_ADC_PRESCAL_9G45   (0xff << 8)
55 #define                 AT91_ADC_PRESCAL_(x)    ((x) << 8)
56 #define         AT91_ADC_STARTUP_9260   (0x1f << 16)    /* Startup Up Time */
57 #define         AT91_ADC_STARTUP_9G45   (0x7f << 16)
58 #define         AT91_ADC_STARTUP_9X5    (0xf << 16)
59 #define                 AT91_ADC_STARTUP_(x)    ((x) << 16)
60 #define         AT91_ADC_SHTIM          (0xf  << 24)    /* Sample & Hold Time */
61 #define                 AT91_ADC_SHTIM_(x)      ((x) << 24)
62 #define         AT91_ADC_PENDBC         (0x0f << 28)    /* Pen Debounce time */
63 #define                 AT91_ADC_PENDBC_(x)     ((x) << 28)
64
65 #define AT91_ADC_TSR            0x0C
66 #define         AT91_ADC_TSR_SHTIM      (0xf  << 24)    /* Sample & Hold Time */
67 #define                 AT91_ADC_TSR_SHTIM_(x)  ((x) << 24)
68
69 #define AT91_ADC_CHER           0x10            /* Channel Enable Register */
70 #define AT91_ADC_CHDR           0x14            /* Channel Disable Register */
71 #define AT91_ADC_CHSR           0x18            /* Channel Status Register */
72 #define         AT91_ADC_CH(n)          (1 << (n))      /* Channel Number */
73
74 #define AT91_ADC_SR             0x1C            /* Status Register */
75 #define         AT91_ADC_EOC(n)         (1 << (n))      /* End of Conversion on Channel N */
76 #define         AT91_ADC_OVRE(n)        (1 << ((n) + 8))/* Overrun Error on Channel N */
77 #define         AT91_ADC_DRDY           (1 << 16)       /* Data Ready */
78 #define         AT91_ADC_GOVRE          (1 << 17)       /* General Overrun Error */
79 #define         AT91_ADC_ENDRX          (1 << 18)       /* End of RX Buffer */
80 #define         AT91_ADC_RXFUFF         (1 << 19)       /* RX Buffer Full */
81
82 #define AT91_ADC_SR_9X5         0x30            /* Status Register for 9x5 */
83 #define         AT91_ADC_SR_DRDY_9X5    (1 << 24)       /* Data Ready */
84
85 #define AT91_ADC_LCDR           0x20            /* Last Converted Data Register */
86 #define         AT91_ADC_LDATA          (0x3ff)
87
88 #define AT91_ADC_IER            0x24            /* Interrupt Enable Register */
89 #define AT91_ADC_IDR            0x28            /* Interrupt Disable Register */
90 #define AT91_ADC_IMR            0x2C            /* Interrupt Mask Register */
91 #define         AT91RL_ADC_IER_PEN      (1 << 20)
92 #define         AT91RL_ADC_IER_NOPEN    (1 << 21)
93 #define         AT91_ADC_IER_PEN        (1 << 29)
94 #define         AT91_ADC_IER_NOPEN      (1 << 30)
95 #define         AT91_ADC_IER_XRDY       (1 << 20)
96 #define         AT91_ADC_IER_YRDY       (1 << 21)
97 #define         AT91_ADC_IER_PRDY       (1 << 22)
98 #define         AT91_ADC_ISR_PENS       (1 << 31)
99
100 #define AT91_ADC_CHR(n)         (0x30 + ((n) * 4))      /* Channel Data Register N */
101 #define         AT91_ADC_DATA           (0x3ff)
102
103 #define AT91_ADC_CDR0_9X5       (0x50)                  /* Channel Data Register 0 for 9X5 */
104
105 #define AT91_ADC_ACR            0x94    /* Analog Control Register */
106 #define         AT91_ADC_ACR_PENDETSENS (0x3 << 0)      /* pull-up resistor */
107
108 #define AT91_ADC_TSMR           0xB0
109 #define         AT91_ADC_TSMR_TSMODE    (3 << 0)        /* Touch Screen Mode */
110 #define                 AT91_ADC_TSMR_TSMODE_NONE               (0 << 0)
111 #define                 AT91_ADC_TSMR_TSMODE_4WIRE_NO_PRESS     (1 << 0)
112 #define                 AT91_ADC_TSMR_TSMODE_4WIRE_PRESS        (2 << 0)
113 #define                 AT91_ADC_TSMR_TSMODE_5WIRE              (3 << 0)
114 #define         AT91_ADC_TSMR_TSAV      (3 << 4)        /* Averages samples */
115 #define                 AT91_ADC_TSMR_TSAV_(x)          ((x) << 4)
116 #define         AT91_ADC_TSMR_SCTIM     (0x0f << 16)    /* Switch closure time */
117 #define                 AT91_ADC_TSMR_SCTIM_(x)         ((x) << 16)
118 #define         AT91_ADC_TSMR_PENDBC    (0x0f << 28)    /* Pen Debounce time */
119 #define                 AT91_ADC_TSMR_PENDBC_(x)        ((x) << 28)
120 #define         AT91_ADC_TSMR_NOTSDMA   (1 << 22)       /* No Touchscreen DMA */
121 #define         AT91_ADC_TSMR_PENDET_DIS        (0 << 24)       /* Pen contact detection disable */
122 #define         AT91_ADC_TSMR_PENDET_ENA        (1 << 24)       /* Pen contact detection enable */
123
124 #define AT91_ADC_TSXPOSR        0xB4
125 #define AT91_ADC_TSYPOSR        0xB8
126 #define AT91_ADC_TSPRESSR       0xBC
127
128 #define AT91_ADC_TRGR_9260      AT91_ADC_MR
129 #define AT91_ADC_TRGR_9G45      0x08
130 #define AT91_ADC_TRGR_9X5       0xC0
131
132 /* Trigger Register bit field */
133 #define         AT91_ADC_TRGR_TRGPER    (0xffff << 16)
134 #define                 AT91_ADC_TRGR_TRGPER_(x)        ((x) << 16)
135 #define         AT91_ADC_TRGR_TRGMOD    (0x7 << 0)
136 #define                 AT91_ADC_TRGR_NONE              (0 << 0)
137 #define                 AT91_ADC_TRGR_MOD_PERIOD_TRIG   (5 << 0)
138
139 #define AT91_ADC_CHAN(st, ch) \
140         (st->registers->channel_base + (ch * 4))
141 #define at91_adc_readl(st, reg) \
142         (readl_relaxed(st->reg_base + reg))
143 #define at91_adc_writel(st, reg, val) \
144         (writel_relaxed(val, st->reg_base + reg))
145
146 #define DRIVER_NAME             "at91_adc"
147 #define MAX_POS_BITS            12
148
149 #define TOUCH_SAMPLE_PERIOD_US          2000    /* 2ms */
150 #define TOUCH_PEN_DETECT_DEBOUNCE_US    200
151
152 #define MAX_RLPOS_BITS         10
153 #define TOUCH_SAMPLE_PERIOD_US_RL      10000   /* 10ms, the SoC can't keep up with 2ms */
154 #define TOUCH_SHTIM                    0xa
155 #define TOUCH_SCTIM_US          10              /* 10us for the Touchscreen Switches Closure Time */
156
157 /**
158  * struct at91_adc_reg_desc - Various informations relative to registers
159  * @channel_base:       Base offset for the channel data registers
160  * @drdy_mask:          Mask of the DRDY field in the relevant registers
161                         (Interruptions registers mostly)
162  * @status_register:    Offset of the Interrupt Status Register
163  * @trigger_register:   Offset of the Trigger setup register
164  * @mr_prescal_mask:    Mask of the PRESCAL field in the adc MR register
165  * @mr_startup_mask:    Mask of the STARTUP field in the adc MR register
166  */
167 struct at91_adc_reg_desc {
168         u8      channel_base;
169         u32     drdy_mask;
170         u8      status_register;
171         u8      trigger_register;
172         u32     mr_prescal_mask;
173         u32     mr_startup_mask;
174 };
175
176 struct at91_adc_caps {
177         bool    has_ts;         /* Support touch screen */
178         bool    has_tsmr;       /* only at91sam9x5, sama5d3 have TSMR reg */
179         /*
180          * Numbers of sampling data will be averaged. Can be 0~3.
181          * Hardware can average (2 ^ ts_filter_average) sample data.
182          */
183         u8      ts_filter_average;
184         /* Pen Detection input pull-up resistor, can be 0~3 */
185         u8      ts_pen_detect_sensitivity;
186
187         /* startup time calculate function */
188         u32 (*calc_startup_ticks)(u32 startup_time, u32 adc_clk_khz);
189
190         u8      num_channels;
191         struct at91_adc_reg_desc registers;
192 };
193
194 struct at91_adc_state {
195         struct clk              *adc_clk;
196         u16                     *buffer;
197         unsigned long           channels_mask;
198         struct clk              *clk;
199         bool                    done;
200         int                     irq;
201         u16                     last_value;
202         int                     chnb;
203         struct mutex            lock;
204         u8                      num_channels;
205         void __iomem            *reg_base;
206         struct at91_adc_reg_desc *registers;
207         u32                     startup_time;
208         u8                      sample_hold_time;
209         bool                    sleep_mode;
210         struct iio_trigger      **trig;
211         struct at91_adc_trigger *trigger_list;
212         u32                     trigger_number;
213         bool                    use_external;
214         u32                     vref_mv;
215         u32                     res;            /* resolution used for convertions */
216         bool                    low_res;        /* the resolution corresponds to the lowest one */
217         wait_queue_head_t       wq_data_avail;
218         struct at91_adc_caps    *caps;
219
220         /*
221          * Following ADC channels are shared by touchscreen:
222          *
223          * CH0 -- Touch screen XP/UL
224          * CH1 -- Touch screen XM/UR
225          * CH2 -- Touch screen YP/LL
226          * CH3 -- Touch screen YM/Sense
227          * CH4 -- Touch screen LR(5-wire only)
228          *
229          * The bitfields below represents the reserved channel in the
230          * touchscreen mode.
231          */
232 #define CHAN_MASK_TOUCHSCREEN_4WIRE     (0xf << 0)
233 #define CHAN_MASK_TOUCHSCREEN_5WIRE     (0x1f << 0)
234         enum atmel_adc_ts_type  touchscreen_type;
235         struct input_dev        *ts_input;
236
237         u16                     ts_sample_period_val;
238         u32                     ts_pressure_threshold;
239         u16                     ts_pendbc;
240
241         bool                    ts_bufferedmeasure;
242         u32                     ts_prev_absx;
243         u32                     ts_prev_absy;
244 };
245
246 static irqreturn_t at91_adc_trigger_handler(int irq, void *p)
247 {
248         struct iio_poll_func *pf = p;
249         struct iio_dev *idev = pf->indio_dev;
250         struct at91_adc_state *st = iio_priv(idev);
251         struct iio_chan_spec const *chan;
252         int i, j = 0;
253
254         for (i = 0; i < idev->masklength; i++) {
255                 if (!test_bit(i, idev->active_scan_mask))
256                         continue;
257                 chan = idev->channels + i;
258                 st->buffer[j] = at91_adc_readl(st, AT91_ADC_CHAN(st, chan->channel));
259                 j++;
260         }
261
262         iio_push_to_buffers_with_timestamp(idev, st->buffer, pf->timestamp);
263
264         iio_trigger_notify_done(idev->trig);
265
266         /* Needed to ACK the DRDY interruption */
267         at91_adc_readl(st, AT91_ADC_LCDR);
268
269         enable_irq(st->irq);
270
271         return IRQ_HANDLED;
272 }
273
274 /* Handler for classic adc channel eoc trigger */
275 static void handle_adc_eoc_trigger(int irq, struct iio_dev *idev)
276 {
277         struct at91_adc_state *st = iio_priv(idev);
278
279         if (iio_buffer_enabled(idev)) {
280                 disable_irq_nosync(irq);
281                 iio_trigger_poll(idev->trig);
282         } else {
283                 st->last_value = at91_adc_readl(st, AT91_ADC_CHAN(st, st->chnb));
284                 /* Needed to ACK the DRDY interruption */
285                 at91_adc_readl(st, AT91_ADC_LCDR);
286                 st->done = true;
287                 wake_up_interruptible(&st->wq_data_avail);
288         }
289 }
290
291 static int at91_ts_sample(struct at91_adc_state *st)
292 {
293         unsigned int xscale, yscale, reg, z1, z2;
294         unsigned int x, y, pres, xpos, ypos;
295         unsigned int rxp = 1;
296         unsigned int factor = 1000;
297         struct iio_dev *idev = iio_priv_to_dev(st);
298
299         unsigned int xyz_mask_bits = st->res;
300         unsigned int xyz_mask = (1 << xyz_mask_bits) - 1;
301
302         /* calculate position */
303         /* x position = (x / xscale) * max, max = 2^MAX_POS_BITS - 1 */
304         reg = at91_adc_readl(st, AT91_ADC_TSXPOSR);
305         xpos = reg & xyz_mask;
306         x = (xpos << MAX_POS_BITS) - xpos;
307         xscale = (reg >> 16) & xyz_mask;
308         if (xscale == 0) {
309                 dev_err(&idev->dev, "Error: xscale == 0!\n");
310                 return -1;
311         }
312         x /= xscale;
313
314         /* y position = (y / yscale) * max, max = 2^MAX_POS_BITS - 1 */
315         reg = at91_adc_readl(st, AT91_ADC_TSYPOSR);
316         ypos = reg & xyz_mask;
317         y = (ypos << MAX_POS_BITS) - ypos;
318         yscale = (reg >> 16) & xyz_mask;
319         if (yscale == 0) {
320                 dev_err(&idev->dev, "Error: yscale == 0!\n");
321                 return -1;
322         }
323         y /= yscale;
324
325         /* calculate the pressure */
326         reg = at91_adc_readl(st, AT91_ADC_TSPRESSR);
327         z1 = reg & xyz_mask;
328         z2 = (reg >> 16) & xyz_mask;
329
330         if (z1 != 0)
331                 pres = rxp * (x * factor / 1024) * (z2 * factor / z1 - factor)
332                         / factor;
333         else
334                 pres = st->ts_pressure_threshold;       /* no pen contacted */
335
336         dev_dbg(&idev->dev, "xpos = %d, xscale = %d, ypos = %d, yscale = %d, z1 = %d, z2 = %d, press = %d\n",
337                                 xpos, xscale, ypos, yscale, z1, z2, pres);
338
339         if (pres < st->ts_pressure_threshold) {
340                 dev_dbg(&idev->dev, "x = %d, y = %d, pressure = %d\n",
341                                         x, y, pres / factor);
342                 input_report_abs(st->ts_input, ABS_X, x);
343                 input_report_abs(st->ts_input, ABS_Y, y);
344                 input_report_abs(st->ts_input, ABS_PRESSURE, pres);
345                 input_report_key(st->ts_input, BTN_TOUCH, 1);
346                 input_sync(st->ts_input);
347         } else {
348                 dev_dbg(&idev->dev, "pressure too low: not reporting\n");
349         }
350
351         return 0;
352 }
353
354 static irqreturn_t at91_adc_rl_interrupt(int irq, void *private)
355 {
356         struct iio_dev *idev = private;
357         struct at91_adc_state *st = iio_priv(idev);
358         u32 status = at91_adc_readl(st, st->registers->status_register);
359         unsigned int reg;
360
361         status &= at91_adc_readl(st, AT91_ADC_IMR);
362         if (status & GENMASK(st->num_channels - 1, 0))
363                 handle_adc_eoc_trigger(irq, idev);
364
365         if (status & AT91RL_ADC_IER_PEN) {
366                 /* Disabling pen debounce is required to get a NOPEN irq */
367                 reg = at91_adc_readl(st, AT91_ADC_MR);
368                 reg &= ~AT91_ADC_PENDBC;
369                 at91_adc_writel(st, AT91_ADC_MR, reg);
370
371                 at91_adc_writel(st, AT91_ADC_IDR, AT91RL_ADC_IER_PEN);
372                 at91_adc_writel(st, AT91_ADC_IER, AT91RL_ADC_IER_NOPEN
373                                 | AT91_ADC_EOC(3));
374                 /* Set up period trigger for sampling */
375                 at91_adc_writel(st, st->registers->trigger_register,
376                         AT91_ADC_TRGR_MOD_PERIOD_TRIG |
377                         AT91_ADC_TRGR_TRGPER_(st->ts_sample_period_val));
378         } else if (status & AT91RL_ADC_IER_NOPEN) {
379                 reg = at91_adc_readl(st, AT91_ADC_MR);
380                 reg |= AT91_ADC_PENDBC_(st->ts_pendbc) & AT91_ADC_PENDBC;
381                 at91_adc_writel(st, AT91_ADC_MR, reg);
382                 at91_adc_writel(st, st->registers->trigger_register,
383                         AT91_ADC_TRGR_NONE);
384
385                 at91_adc_writel(st, AT91_ADC_IDR, AT91RL_ADC_IER_NOPEN
386                                 | AT91_ADC_EOC(3));
387                 at91_adc_writel(st, AT91_ADC_IER, AT91RL_ADC_IER_PEN);
388                 st->ts_bufferedmeasure = false;
389                 input_report_key(st->ts_input, BTN_TOUCH, 0);
390                 input_sync(st->ts_input);
391         } else if (status & AT91_ADC_EOC(3) && st->ts_input) {
392                 /* Conversion finished and we've a touchscreen */
393                 if (st->ts_bufferedmeasure) {
394                         /*
395                          * Last measurement is always discarded, since it can
396                          * be erroneous.
397                          * Always report previous measurement
398                          */
399                         input_report_abs(st->ts_input, ABS_X, st->ts_prev_absx);
400                         input_report_abs(st->ts_input, ABS_Y, st->ts_prev_absy);
401                         input_report_key(st->ts_input, BTN_TOUCH, 1);
402                         input_sync(st->ts_input);
403                 } else
404                         st->ts_bufferedmeasure = true;
405
406                 /* Now make new measurement */
407                 st->ts_prev_absx = at91_adc_readl(st, AT91_ADC_CHAN(st, 3))
408                                    << MAX_RLPOS_BITS;
409                 st->ts_prev_absx /= at91_adc_readl(st, AT91_ADC_CHAN(st, 2));
410
411                 st->ts_prev_absy = at91_adc_readl(st, AT91_ADC_CHAN(st, 1))
412                                    << MAX_RLPOS_BITS;
413                 st->ts_prev_absy /= at91_adc_readl(st, AT91_ADC_CHAN(st, 0));
414         }
415
416         return IRQ_HANDLED;
417 }
418
419 static irqreturn_t at91_adc_9x5_interrupt(int irq, void *private)
420 {
421         struct iio_dev *idev = private;
422         struct at91_adc_state *st = iio_priv(idev);
423         u32 status = at91_adc_readl(st, st->registers->status_register);
424         const uint32_t ts_data_irq_mask =
425                 AT91_ADC_IER_XRDY |
426                 AT91_ADC_IER_YRDY |
427                 AT91_ADC_IER_PRDY;
428
429         if (status & GENMASK(st->num_channels - 1, 0))
430                 handle_adc_eoc_trigger(irq, idev);
431
432         if (status & AT91_ADC_IER_PEN) {
433                 at91_adc_writel(st, AT91_ADC_IDR, AT91_ADC_IER_PEN);
434                 at91_adc_writel(st, AT91_ADC_IER, AT91_ADC_IER_NOPEN |
435                         ts_data_irq_mask);
436                 /* Set up period trigger for sampling */
437                 at91_adc_writel(st, st->registers->trigger_register,
438                         AT91_ADC_TRGR_MOD_PERIOD_TRIG |
439                         AT91_ADC_TRGR_TRGPER_(st->ts_sample_period_val));
440         } else if (status & AT91_ADC_IER_NOPEN) {
441                 at91_adc_writel(st, st->registers->trigger_register, 0);
442                 at91_adc_writel(st, AT91_ADC_IDR, AT91_ADC_IER_NOPEN |
443                         ts_data_irq_mask);
444                 at91_adc_writel(st, AT91_ADC_IER, AT91_ADC_IER_PEN);
445
446                 input_report_key(st->ts_input, BTN_TOUCH, 0);
447                 input_sync(st->ts_input);
448         } else if ((status & ts_data_irq_mask) == ts_data_irq_mask) {
449                 /* Now all touchscreen data is ready */
450
451                 if (status & AT91_ADC_ISR_PENS) {
452                         /* validate data by pen contact */
453                         at91_ts_sample(st);
454                 } else {
455                         /* triggered by event that is no pen contact, just read
456                          * them to clean the interrupt and discard all.
457                          */
458                         at91_adc_readl(st, AT91_ADC_TSXPOSR);
459                         at91_adc_readl(st, AT91_ADC_TSYPOSR);
460                         at91_adc_readl(st, AT91_ADC_TSPRESSR);
461                 }
462         }
463
464         return IRQ_HANDLED;
465 }
466
467 static int at91_adc_channel_init(struct iio_dev *idev)
468 {
469         struct at91_adc_state *st = iio_priv(idev);
470         struct iio_chan_spec *chan_array, *timestamp;
471         int bit, idx = 0;
472         unsigned long rsvd_mask = 0;
473
474         /* If touchscreen is enable, then reserve the adc channels */
475         if (st->touchscreen_type == ATMEL_ADC_TOUCHSCREEN_4WIRE)
476                 rsvd_mask = CHAN_MASK_TOUCHSCREEN_4WIRE;
477         else if (st->touchscreen_type == ATMEL_ADC_TOUCHSCREEN_5WIRE)
478                 rsvd_mask = CHAN_MASK_TOUCHSCREEN_5WIRE;
479
480         /* set up the channel mask to reserve touchscreen channels */
481         st->channels_mask &= ~rsvd_mask;
482
483         idev->num_channels = bitmap_weight(&st->channels_mask,
484                                            st->num_channels) + 1;
485
486         chan_array = devm_kzalloc(&idev->dev,
487                                   ((idev->num_channels + 1) *
488                                         sizeof(struct iio_chan_spec)),
489                                   GFP_KERNEL);
490
491         if (!chan_array)
492                 return -ENOMEM;
493
494         for_each_set_bit(bit, &st->channels_mask, st->num_channels) {
495                 struct iio_chan_spec *chan = chan_array + idx;
496
497                 chan->type = IIO_VOLTAGE;
498                 chan->indexed = 1;
499                 chan->channel = bit;
500                 chan->scan_index = idx;
501                 chan->scan_type.sign = 'u';
502                 chan->scan_type.realbits = st->res;
503                 chan->scan_type.storagebits = 16;
504                 chan->info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE);
505                 chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
506                 idx++;
507         }
508         timestamp = chan_array + idx;
509
510         timestamp->type = IIO_TIMESTAMP;
511         timestamp->channel = -1;
512         timestamp->scan_index = idx;
513         timestamp->scan_type.sign = 's';
514         timestamp->scan_type.realbits = 64;
515         timestamp->scan_type.storagebits = 64;
516
517         idev->channels = chan_array;
518         return idev->num_channels;
519 }
520
521 static int at91_adc_get_trigger_value_by_name(struct iio_dev *idev,
522                                              struct at91_adc_trigger *triggers,
523                                              const char *trigger_name)
524 {
525         struct at91_adc_state *st = iio_priv(idev);
526         int i;
527
528         for (i = 0; i < st->trigger_number; i++) {
529                 char *name = kasprintf(GFP_KERNEL,
530                                 "%s-dev%d-%s",
531                                 idev->name,
532                                 idev->id,
533                                 triggers[i].name);
534                 if (!name)
535                         return -ENOMEM;
536
537                 if (strcmp(trigger_name, name) == 0) {
538                         kfree(name);
539                         if (triggers[i].value == 0)
540                                 return -EINVAL;
541                         return triggers[i].value;
542                 }
543
544                 kfree(name);
545         }
546
547         return -EINVAL;
548 }
549
550 static int at91_adc_configure_trigger(struct iio_trigger *trig, bool state)
551 {
552         struct iio_dev *idev = iio_trigger_get_drvdata(trig);
553         struct at91_adc_state *st = iio_priv(idev);
554         struct at91_adc_reg_desc *reg = st->registers;
555         u32 status = at91_adc_readl(st, reg->trigger_register);
556         int value;
557         u8 bit;
558
559         value = at91_adc_get_trigger_value_by_name(idev,
560                                                    st->trigger_list,
561                                                    idev->trig->name);
562         if (value < 0)
563                 return value;
564
565         if (state) {
566                 st->buffer = kmalloc(idev->scan_bytes, GFP_KERNEL);
567                 if (st->buffer == NULL)
568                         return -ENOMEM;
569
570                 at91_adc_writel(st, reg->trigger_register,
571                                 status | value);
572
573                 for_each_set_bit(bit, idev->active_scan_mask,
574                                  st->num_channels) {
575                         struct iio_chan_spec const *chan = idev->channels + bit;
576                         at91_adc_writel(st, AT91_ADC_CHER,
577                                         AT91_ADC_CH(chan->channel));
578                 }
579
580                 at91_adc_writel(st, AT91_ADC_IER, reg->drdy_mask);
581
582         } else {
583                 at91_adc_writel(st, AT91_ADC_IDR, reg->drdy_mask);
584
585                 at91_adc_writel(st, reg->trigger_register,
586                                 status & ~value);
587
588                 for_each_set_bit(bit, idev->active_scan_mask,
589                                  st->num_channels) {
590                         struct iio_chan_spec const *chan = idev->channels + bit;
591                         at91_adc_writel(st, AT91_ADC_CHDR,
592                                         AT91_ADC_CH(chan->channel));
593                 }
594                 kfree(st->buffer);
595         }
596
597         return 0;
598 }
599
600 static const struct iio_trigger_ops at91_adc_trigger_ops = {
601         .owner = THIS_MODULE,
602         .set_trigger_state = &at91_adc_configure_trigger,
603 };
604
605 static struct iio_trigger *at91_adc_allocate_trigger(struct iio_dev *idev,
606                                                      struct at91_adc_trigger *trigger)
607 {
608         struct iio_trigger *trig;
609         int ret;
610
611         trig = iio_trigger_alloc("%s-dev%d-%s", idev->name,
612                                  idev->id, trigger->name);
613         if (trig == NULL)
614                 return NULL;
615
616         trig->dev.parent = idev->dev.parent;
617         iio_trigger_set_drvdata(trig, idev);
618         trig->ops = &at91_adc_trigger_ops;
619
620         ret = iio_trigger_register(trig);
621         if (ret) {
622                 iio_trigger_free(trig);
623                 return NULL;
624         }
625
626         return trig;
627 }
628
629 static int at91_adc_trigger_init(struct iio_dev *idev)
630 {
631         struct at91_adc_state *st = iio_priv(idev);
632         int i, ret;
633
634         st->trig = devm_kzalloc(&idev->dev,
635                                 st->trigger_number * sizeof(*st->trig),
636                                 GFP_KERNEL);
637
638         if (st->trig == NULL) {
639                 ret = -ENOMEM;
640                 goto error_ret;
641         }
642
643         for (i = 0; i < st->trigger_number; i++) {
644                 if (st->trigger_list[i].is_external && !(st->use_external))
645                         continue;
646
647                 st->trig[i] = at91_adc_allocate_trigger(idev,
648                                                         st->trigger_list + i);
649                 if (st->trig[i] == NULL) {
650                         dev_err(&idev->dev,
651                                 "Could not allocate trigger %d\n", i);
652                         ret = -ENOMEM;
653                         goto error_trigger;
654                 }
655         }
656
657         return 0;
658
659 error_trigger:
660         for (i--; i >= 0; i--) {
661                 iio_trigger_unregister(st->trig[i]);
662                 iio_trigger_free(st->trig[i]);
663         }
664 error_ret:
665         return ret;
666 }
667
668 static void at91_adc_trigger_remove(struct iio_dev *idev)
669 {
670         struct at91_adc_state *st = iio_priv(idev);
671         int i;
672
673         for (i = 0; i < st->trigger_number; i++) {
674                 iio_trigger_unregister(st->trig[i]);
675                 iio_trigger_free(st->trig[i]);
676         }
677 }
678
679 static int at91_adc_buffer_init(struct iio_dev *idev)
680 {
681         return iio_triggered_buffer_setup(idev, &iio_pollfunc_store_time,
682                 &at91_adc_trigger_handler, NULL);
683 }
684
685 static void at91_adc_buffer_remove(struct iio_dev *idev)
686 {
687         iio_triggered_buffer_cleanup(idev);
688 }
689
690 static int at91_adc_read_raw(struct iio_dev *idev,
691                              struct iio_chan_spec const *chan,
692                              int *val, int *val2, long mask)
693 {
694         struct at91_adc_state *st = iio_priv(idev);
695         int ret;
696
697         switch (mask) {
698         case IIO_CHAN_INFO_RAW:
699                 mutex_lock(&st->lock);
700
701                 st->chnb = chan->channel;
702                 at91_adc_writel(st, AT91_ADC_CHER,
703                                 AT91_ADC_CH(chan->channel));
704                 at91_adc_writel(st, AT91_ADC_IER, BIT(chan->channel));
705                 at91_adc_writel(st, AT91_ADC_CR, AT91_ADC_START);
706
707                 ret = wait_event_interruptible_timeout(st->wq_data_avail,
708                                                        st->done,
709                                                        msecs_to_jiffies(1000));
710
711                 /* Disable interrupts, regardless if adc conversion was
712                  * successful or not
713                  */
714                 at91_adc_writel(st, AT91_ADC_CHDR,
715                                 AT91_ADC_CH(chan->channel));
716                 at91_adc_writel(st, AT91_ADC_IDR, BIT(chan->channel));
717
718                 if (ret > 0) {
719                         /* a valid conversion took place */
720                         *val = st->last_value;
721                         st->last_value = 0;
722                         st->done = false;
723                         ret = IIO_VAL_INT;
724                 } else if (ret == 0) {
725                         /* conversion timeout */
726                         dev_err(&idev->dev, "ADC Channel %d timeout.\n",
727                                 chan->channel);
728                         ret = -ETIMEDOUT;
729                 }
730
731                 mutex_unlock(&st->lock);
732                 return ret;
733
734         case IIO_CHAN_INFO_SCALE:
735                 *val = st->vref_mv;
736                 *val2 = chan->scan_type.realbits;
737                 return IIO_VAL_FRACTIONAL_LOG2;
738         default:
739                 break;
740         }
741         return -EINVAL;
742 }
743
744 static int at91_adc_of_get_resolution(struct at91_adc_state *st,
745                                       struct platform_device *pdev)
746 {
747         struct iio_dev *idev = iio_priv_to_dev(st);
748         struct device_node *np = pdev->dev.of_node;
749         int count, i, ret = 0;
750         char *res_name, *s;
751         u32 *resolutions;
752
753         count = of_property_count_strings(np, "atmel,adc-res-names");
754         if (count < 2) {
755                 dev_err(&idev->dev, "You must specified at least two resolution names for "
756                                     "adc-res-names property in the DT\n");
757                 return count;
758         }
759
760         resolutions = kmalloc_array(count, sizeof(*resolutions), GFP_KERNEL);
761         if (!resolutions)
762                 return -ENOMEM;
763
764         if (of_property_read_u32_array(np, "atmel,adc-res", resolutions, count)) {
765                 dev_err(&idev->dev, "Missing adc-res property in the DT.\n");
766                 ret = -ENODEV;
767                 goto ret;
768         }
769
770         if (of_property_read_string(np, "atmel,adc-use-res", (const char **)&res_name))
771                 res_name = "highres";
772
773         for (i = 0; i < count; i++) {
774                 if (of_property_read_string_index(np, "atmel,adc-res-names", i, (const char **)&s))
775                         continue;
776
777                 if (strcmp(res_name, s))
778                         continue;
779
780                 st->res = resolutions[i];
781                 if (!strcmp(res_name, "lowres"))
782                         st->low_res = true;
783                 else
784                         st->low_res = false;
785
786                 dev_info(&idev->dev, "Resolution used: %u bits\n", st->res);
787                 goto ret;
788         }
789
790         dev_err(&idev->dev, "There is no resolution for %s\n", res_name);
791
792 ret:
793         kfree(resolutions);
794         return ret;
795 }
796
797 static u32 calc_startup_ticks_9260(u32 startup_time, u32 adc_clk_khz)
798 {
799         /*
800          * Number of ticks needed to cover the startup time of the ADC
801          * as defined in the electrical characteristics of the board,
802          * divided by 8. The formula thus is :
803          *   Startup Time = (ticks + 1) * 8 / ADC Clock
804          */
805         return round_up((startup_time * adc_clk_khz / 1000) - 1, 8) / 8;
806 }
807
808 static u32 calc_startup_ticks_9x5(u32 startup_time, u32 adc_clk_khz)
809 {
810         /*
811          * For sama5d3x and at91sam9x5, the formula changes to:
812          * Startup Time = <lookup_table_value> / ADC Clock
813          */
814         static const int startup_lookup[] = {
815                 0,   8,   16,  24,
816                 64,  80,  96,  112,
817                 512, 576, 640, 704,
818                 768, 832, 896, 960
819                 };
820         int i, size = ARRAY_SIZE(startup_lookup);
821         unsigned int ticks;
822
823         ticks = startup_time * adc_clk_khz / 1000;
824         for (i = 0; i < size; i++)
825                 if (ticks < startup_lookup[i])
826                         break;
827
828         ticks = i;
829         if (ticks == size)
830                 /* Reach the end of lookup table */
831                 ticks = size - 1;
832
833         return ticks;
834 }
835
836 static const struct of_device_id at91_adc_dt_ids[];
837
838 static int at91_adc_probe_dt_ts(struct device_node *node,
839         struct at91_adc_state *st, struct device *dev)
840 {
841         int ret;
842         u32 prop;
843
844         ret = of_property_read_u32(node, "atmel,adc-ts-wires", &prop);
845         if (ret) {
846                 dev_info(dev, "ADC Touch screen is disabled.\n");
847                 return 0;
848         }
849
850         switch (prop) {
851         case 4:
852         case 5:
853                 st->touchscreen_type = prop;
854                 break;
855         default:
856                 dev_err(dev, "Unsupported number of touchscreen wires (%d). Should be 4 or 5.\n", prop);
857                 return -EINVAL;
858         }
859
860         if (!st->caps->has_tsmr)
861                 return 0;
862         prop = 0;
863         of_property_read_u32(node, "atmel,adc-ts-pressure-threshold", &prop);
864         st->ts_pressure_threshold = prop;
865         if (st->ts_pressure_threshold) {
866                 return 0;
867         } else {
868                 dev_err(dev, "Invalid pressure threshold for the touchscreen\n");
869                 return -EINVAL;
870         }
871 }
872
873 static int at91_adc_probe_dt(struct at91_adc_state *st,
874                              struct platform_device *pdev)
875 {
876         struct iio_dev *idev = iio_priv_to_dev(st);
877         struct device_node *node = pdev->dev.of_node;
878         struct device_node *trig_node;
879         int i = 0, ret;
880         u32 prop;
881
882         if (!node)
883                 return -EINVAL;
884
885         st->caps = (struct at91_adc_caps *)
886                 of_match_device(at91_adc_dt_ids, &pdev->dev)->data;
887
888         st->use_external = of_property_read_bool(node, "atmel,adc-use-external-triggers");
889
890         if (of_property_read_u32(node, "atmel,adc-channels-used", &prop)) {
891                 dev_err(&idev->dev, "Missing adc-channels-used property in the DT.\n");
892                 ret = -EINVAL;
893                 goto error_ret;
894         }
895         st->channels_mask = prop;
896
897         st->sleep_mode = of_property_read_bool(node, "atmel,adc-sleep-mode");
898
899         if (of_property_read_u32(node, "atmel,adc-startup-time", &prop)) {
900                 dev_err(&idev->dev, "Missing adc-startup-time property in the DT.\n");
901                 ret = -EINVAL;
902                 goto error_ret;
903         }
904         st->startup_time = prop;
905
906         prop = 0;
907         of_property_read_u32(node, "atmel,adc-sample-hold-time", &prop);
908         st->sample_hold_time = prop;
909
910         if (of_property_read_u32(node, "atmel,adc-vref", &prop)) {
911                 dev_err(&idev->dev, "Missing adc-vref property in the DT.\n");
912                 ret = -EINVAL;
913                 goto error_ret;
914         }
915         st->vref_mv = prop;
916
917         ret = at91_adc_of_get_resolution(st, pdev);
918         if (ret)
919                 goto error_ret;
920
921         st->registers = &st->caps->registers;
922         st->num_channels = st->caps->num_channels;
923         st->trigger_number = of_get_child_count(node);
924         st->trigger_list = devm_kzalloc(&idev->dev, st->trigger_number *
925                                         sizeof(struct at91_adc_trigger),
926                                         GFP_KERNEL);
927         if (!st->trigger_list) {
928                 dev_err(&idev->dev, "Could not allocate trigger list memory.\n");
929                 ret = -ENOMEM;
930                 goto error_ret;
931         }
932
933         for_each_child_of_node(node, trig_node) {
934                 struct at91_adc_trigger *trig = st->trigger_list + i;
935                 const char *name;
936
937                 if (of_property_read_string(trig_node, "trigger-name", &name)) {
938                         dev_err(&idev->dev, "Missing trigger-name property in the DT.\n");
939                         ret = -EINVAL;
940                         goto error_ret;
941                 }
942                 trig->name = name;
943
944                 if (of_property_read_u32(trig_node, "trigger-value", &prop)) {
945                         dev_err(&idev->dev, "Missing trigger-value property in the DT.\n");
946                         ret = -EINVAL;
947                         goto error_ret;
948                 }
949                 trig->value = prop;
950                 trig->is_external = of_property_read_bool(trig_node, "trigger-external");
951                 i++;
952         }
953
954         /* Check if touchscreen is supported. */
955         if (st->caps->has_ts)
956                 return at91_adc_probe_dt_ts(node, st, &idev->dev);
957         else
958                 dev_info(&idev->dev, "not support touchscreen in the adc compatible string.\n");
959
960         return 0;
961
962 error_ret:
963         return ret;
964 }
965
966 static int at91_adc_probe_pdata(struct at91_adc_state *st,
967                                 struct platform_device *pdev)
968 {
969         struct at91_adc_data *pdata = pdev->dev.platform_data;
970
971         if (!pdata)
972                 return -EINVAL;
973
974         st->caps = (struct at91_adc_caps *)
975                         platform_get_device_id(pdev)->driver_data;
976
977         st->use_external = pdata->use_external_triggers;
978         st->vref_mv = pdata->vref;
979         st->channels_mask = pdata->channels_used;
980         st->num_channels = st->caps->num_channels;
981         st->startup_time = pdata->startup_time;
982         st->trigger_number = pdata->trigger_number;
983         st->trigger_list = pdata->trigger_list;
984         st->registers = &st->caps->registers;
985         st->touchscreen_type = pdata->touchscreen_type;
986
987         return 0;
988 }
989
990 static const struct iio_info at91_adc_info = {
991         .driver_module = THIS_MODULE,
992         .read_raw = &at91_adc_read_raw,
993 };
994
995 /* Touchscreen related functions */
996 static int atmel_ts_open(struct input_dev *dev)
997 {
998         struct at91_adc_state *st = input_get_drvdata(dev);
999
1000         if (st->caps->has_tsmr)
1001                 at91_adc_writel(st, AT91_ADC_IER, AT91_ADC_IER_PEN);
1002         else
1003                 at91_adc_writel(st, AT91_ADC_IER, AT91RL_ADC_IER_PEN);
1004         return 0;
1005 }
1006
1007 static void atmel_ts_close(struct input_dev *dev)
1008 {
1009         struct at91_adc_state *st = input_get_drvdata(dev);
1010
1011         if (st->caps->has_tsmr)
1012                 at91_adc_writel(st, AT91_ADC_IDR, AT91_ADC_IER_PEN);
1013         else
1014                 at91_adc_writel(st, AT91_ADC_IDR, AT91RL_ADC_IER_PEN);
1015 }
1016
1017 static int at91_ts_hw_init(struct at91_adc_state *st, u32 adc_clk_khz)
1018 {
1019         struct iio_dev *idev = iio_priv_to_dev(st);
1020         u32 reg = 0;
1021         u32 tssctim = 0;
1022         int i = 0;
1023
1024         /* a Pen Detect Debounce Time is necessary for the ADC Touch to avoid
1025          * pen detect noise.
1026          * The formula is : Pen Detect Debounce Time = (2 ^ pendbc) / ADCClock
1027          */
1028         st->ts_pendbc = round_up(TOUCH_PEN_DETECT_DEBOUNCE_US * adc_clk_khz /
1029                                  1000, 1);
1030
1031         while (st->ts_pendbc >> ++i)
1032                 ;       /* Empty! Find the shift offset */
1033         if (abs(st->ts_pendbc - (1 << i)) < abs(st->ts_pendbc - (1 << (i - 1))))
1034                 st->ts_pendbc = i;
1035         else
1036                 st->ts_pendbc = i - 1;
1037
1038         if (!st->caps->has_tsmr) {
1039                 reg = at91_adc_readl(st, AT91_ADC_MR);
1040                 reg |= AT91_ADC_TSAMOD_TS_ONLY_MODE | AT91_ADC_PENDET;
1041
1042                 reg |= AT91_ADC_PENDBC_(st->ts_pendbc) & AT91_ADC_PENDBC;
1043                 at91_adc_writel(st, AT91_ADC_MR, reg);
1044
1045                 reg = AT91_ADC_TSR_SHTIM_(TOUCH_SHTIM) & AT91_ADC_TSR_SHTIM;
1046                 at91_adc_writel(st, AT91_ADC_TSR, reg);
1047
1048                 st->ts_sample_period_val = round_up((TOUCH_SAMPLE_PERIOD_US_RL *
1049                                                     adc_clk_khz / 1000) - 1, 1);
1050
1051                 return 0;
1052         }
1053
1054         /* Touchscreen Switches Closure time needed for allowing the value to
1055          * stabilize.
1056          * Switch Closure Time = (TSSCTIM * 4) ADCClock periods
1057          */
1058         tssctim = DIV_ROUND_UP(TOUCH_SCTIM_US * adc_clk_khz / 1000, 4);
1059         dev_dbg(&idev->dev, "adc_clk at: %d KHz, tssctim at: %d\n",
1060                 adc_clk_khz, tssctim);
1061
1062         if (st->touchscreen_type == ATMEL_ADC_TOUCHSCREEN_4WIRE)
1063                 reg = AT91_ADC_TSMR_TSMODE_4WIRE_PRESS;
1064         else
1065                 reg = AT91_ADC_TSMR_TSMODE_5WIRE;
1066
1067         reg |= AT91_ADC_TSMR_SCTIM_(tssctim) & AT91_ADC_TSMR_SCTIM;
1068         reg |= AT91_ADC_TSMR_TSAV_(st->caps->ts_filter_average)
1069                & AT91_ADC_TSMR_TSAV;
1070         reg |= AT91_ADC_TSMR_PENDBC_(st->ts_pendbc) & AT91_ADC_TSMR_PENDBC;
1071         reg |= AT91_ADC_TSMR_NOTSDMA;
1072         reg |= AT91_ADC_TSMR_PENDET_ENA;
1073         reg |= 0x03 << 8;       /* TSFREQ, needs to be bigger than TSAV */
1074
1075         at91_adc_writel(st, AT91_ADC_TSMR, reg);
1076
1077         /* Change adc internal resistor value for better pen detection,
1078          * default value is 100 kOhm.
1079          * 0 = 200 kOhm, 1 = 150 kOhm, 2 = 100 kOhm, 3 = 50 kOhm
1080          * option only available on ES2 and higher
1081          */
1082         at91_adc_writel(st, AT91_ADC_ACR, st->caps->ts_pen_detect_sensitivity
1083                         & AT91_ADC_ACR_PENDETSENS);
1084
1085         /* Sample Period Time = (TRGPER + 1) / ADCClock */
1086         st->ts_sample_period_val = round_up((TOUCH_SAMPLE_PERIOD_US *
1087                         adc_clk_khz / 1000) - 1, 1);
1088
1089         return 0;
1090 }
1091
1092 static int at91_ts_register(struct at91_adc_state *st,
1093                 struct platform_device *pdev)
1094 {
1095         struct input_dev *input;
1096         struct iio_dev *idev = iio_priv_to_dev(st);
1097         int ret;
1098
1099         input = input_allocate_device();
1100         if (!input) {
1101                 dev_err(&idev->dev, "Failed to allocate TS device!\n");
1102                 return -ENOMEM;
1103         }
1104
1105         input->name = DRIVER_NAME;
1106         input->id.bustype = BUS_HOST;
1107         input->dev.parent = &pdev->dev;
1108         input->open = atmel_ts_open;
1109         input->close = atmel_ts_close;
1110
1111         __set_bit(EV_ABS, input->evbit);
1112         __set_bit(EV_KEY, input->evbit);
1113         __set_bit(BTN_TOUCH, input->keybit);
1114         if (st->caps->has_tsmr) {
1115                 input_set_abs_params(input, ABS_X, 0, (1 << MAX_POS_BITS) - 1,
1116                                      0, 0);
1117                 input_set_abs_params(input, ABS_Y, 0, (1 << MAX_POS_BITS) - 1,
1118                                      0, 0);
1119                 input_set_abs_params(input, ABS_PRESSURE, 0, 0xffffff, 0, 0);
1120         } else {
1121                 if (st->touchscreen_type != ATMEL_ADC_TOUCHSCREEN_4WIRE) {
1122                         dev_err(&pdev->dev,
1123                                 "This touchscreen controller only support 4 wires\n");
1124                         ret = -EINVAL;
1125                         goto err;
1126                 }
1127
1128                 input_set_abs_params(input, ABS_X, 0, (1 << MAX_RLPOS_BITS) - 1,
1129                                      0, 0);
1130                 input_set_abs_params(input, ABS_Y, 0, (1 << MAX_RLPOS_BITS) - 1,
1131                                      0, 0);
1132         }
1133
1134         st->ts_input = input;
1135         input_set_drvdata(input, st);
1136
1137         ret = input_register_device(input);
1138         if (ret)
1139                 goto err;
1140
1141         return ret;
1142
1143 err:
1144         input_free_device(st->ts_input);
1145         return ret;
1146 }
1147
1148 static void at91_ts_unregister(struct at91_adc_state *st)
1149 {
1150         input_unregister_device(st->ts_input);
1151 }
1152
1153 static int at91_adc_probe(struct platform_device *pdev)
1154 {
1155         unsigned int prsc, mstrclk, ticks, adc_clk, adc_clk_khz, shtim;
1156         int ret;
1157         struct iio_dev *idev;
1158         struct at91_adc_state *st;
1159         struct resource *res;
1160         u32 reg;
1161
1162         idev = devm_iio_device_alloc(&pdev->dev, sizeof(struct at91_adc_state));
1163         if (!idev)
1164                 return -ENOMEM;
1165
1166         st = iio_priv(idev);
1167
1168         if (pdev->dev.of_node)
1169                 ret = at91_adc_probe_dt(st, pdev);
1170         else
1171                 ret = at91_adc_probe_pdata(st, pdev);
1172
1173         if (ret) {
1174                 dev_err(&pdev->dev, "No platform data available.\n");
1175                 return -EINVAL;
1176         }
1177
1178         platform_set_drvdata(pdev, idev);
1179
1180         idev->dev.parent = &pdev->dev;
1181         idev->name = dev_name(&pdev->dev);
1182         idev->modes = INDIO_DIRECT_MODE;
1183         idev->info = &at91_adc_info;
1184
1185         st->irq = platform_get_irq(pdev, 0);
1186         if (st->irq < 0) {
1187                 dev_err(&pdev->dev, "No IRQ ID is designated\n");
1188                 return -ENODEV;
1189         }
1190
1191         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1192
1193         st->reg_base = devm_ioremap_resource(&pdev->dev, res);
1194         if (IS_ERR(st->reg_base)) {
1195                 return PTR_ERR(st->reg_base);
1196         }
1197
1198         /*
1199          * Disable all IRQs before setting up the handler
1200          */
1201         at91_adc_writel(st, AT91_ADC_CR, AT91_ADC_SWRST);
1202         at91_adc_writel(st, AT91_ADC_IDR, 0xFFFFFFFF);
1203
1204         if (st->caps->has_tsmr)
1205                 ret = request_irq(st->irq, at91_adc_9x5_interrupt, 0,
1206                                   pdev->dev.driver->name, idev);
1207         else
1208                 ret = request_irq(st->irq, at91_adc_rl_interrupt, 0,
1209                                   pdev->dev.driver->name, idev);
1210         if (ret) {
1211                 dev_err(&pdev->dev, "Failed to allocate IRQ.\n");
1212                 return ret;
1213         }
1214
1215         st->clk = devm_clk_get(&pdev->dev, "adc_clk");
1216         if (IS_ERR(st->clk)) {
1217                 dev_err(&pdev->dev, "Failed to get the clock.\n");
1218                 ret = PTR_ERR(st->clk);
1219                 goto error_free_irq;
1220         }
1221
1222         ret = clk_prepare_enable(st->clk);
1223         if (ret) {
1224                 dev_err(&pdev->dev,
1225                         "Could not prepare or enable the clock.\n");
1226                 goto error_free_irq;
1227         }
1228
1229         st->adc_clk = devm_clk_get(&pdev->dev, "adc_op_clk");
1230         if (IS_ERR(st->adc_clk)) {
1231                 dev_err(&pdev->dev, "Failed to get the ADC clock.\n");
1232                 ret = PTR_ERR(st->adc_clk);
1233                 goto error_disable_clk;
1234         }
1235
1236         ret = clk_prepare_enable(st->adc_clk);
1237         if (ret) {
1238                 dev_err(&pdev->dev,
1239                         "Could not prepare or enable the ADC clock.\n");
1240                 goto error_disable_clk;
1241         }
1242
1243         /*
1244          * Prescaler rate computation using the formula from the Atmel's
1245          * datasheet : ADC Clock = MCK / ((Prescaler + 1) * 2), ADC Clock being
1246          * specified by the electrical characteristics of the board.
1247          */
1248         mstrclk = clk_get_rate(st->clk);
1249         adc_clk = clk_get_rate(st->adc_clk);
1250         adc_clk_khz = adc_clk / 1000;
1251
1252         dev_dbg(&pdev->dev, "Master clock is set as: %d Hz, adc_clk should set as: %d Hz\n",
1253                 mstrclk, adc_clk);
1254
1255         prsc = (mstrclk / (2 * adc_clk)) - 1;
1256
1257         if (!st->startup_time) {
1258                 dev_err(&pdev->dev, "No startup time available.\n");
1259                 ret = -EINVAL;
1260                 goto error_disable_adc_clk;
1261         }
1262         ticks = (*st->caps->calc_startup_ticks)(st->startup_time, adc_clk_khz);
1263
1264         /*
1265          * a minimal Sample and Hold Time is necessary for the ADC to guarantee
1266          * the best converted final value between two channels selection
1267          * The formula thus is : Sample and Hold Time = (shtim + 1) / ADCClock
1268          */
1269         if (st->sample_hold_time > 0)
1270                 shtim = round_up((st->sample_hold_time * adc_clk_khz / 1000)
1271                                  - 1, 1);
1272         else
1273                 shtim = 0;
1274
1275         reg = AT91_ADC_PRESCAL_(prsc) & st->registers->mr_prescal_mask;
1276         reg |= AT91_ADC_STARTUP_(ticks) & st->registers->mr_startup_mask;
1277         if (st->low_res)
1278                 reg |= AT91_ADC_LOWRES;
1279         if (st->sleep_mode)
1280                 reg |= AT91_ADC_SLEEP;
1281         reg |= AT91_ADC_SHTIM_(shtim) & AT91_ADC_SHTIM;
1282         at91_adc_writel(st, AT91_ADC_MR, reg);
1283
1284         /* Setup the ADC channels available on the board */
1285         ret = at91_adc_channel_init(idev);
1286         if (ret < 0) {
1287                 dev_err(&pdev->dev, "Couldn't initialize the channels.\n");
1288                 goto error_disable_adc_clk;
1289         }
1290
1291         init_waitqueue_head(&st->wq_data_avail);
1292         mutex_init(&st->lock);
1293
1294         /*
1295          * Since touch screen will set trigger register as period trigger. So
1296          * when touch screen is enabled, then we have to disable hardware
1297          * trigger for classic adc.
1298          */
1299         if (!st->touchscreen_type) {
1300                 ret = at91_adc_buffer_init(idev);
1301                 if (ret < 0) {
1302                         dev_err(&pdev->dev, "Couldn't initialize the buffer.\n");
1303                         goto error_disable_adc_clk;
1304                 }
1305
1306                 ret = at91_adc_trigger_init(idev);
1307                 if (ret < 0) {
1308                         dev_err(&pdev->dev, "Couldn't setup the triggers.\n");
1309                         at91_adc_buffer_remove(idev);
1310                         goto error_disable_adc_clk;
1311                 }
1312         } else {
1313                 ret = at91_ts_register(st, pdev);
1314                 if (ret)
1315                         goto error_disable_adc_clk;
1316
1317                 at91_ts_hw_init(st, adc_clk_khz);
1318         }
1319
1320         ret = iio_device_register(idev);
1321         if (ret < 0) {
1322                 dev_err(&pdev->dev, "Couldn't register the device.\n");
1323                 goto error_iio_device_register;
1324         }
1325
1326         return 0;
1327
1328 error_iio_device_register:
1329         if (!st->touchscreen_type) {
1330                 at91_adc_trigger_remove(idev);
1331                 at91_adc_buffer_remove(idev);
1332         } else {
1333                 at91_ts_unregister(st);
1334         }
1335 error_disable_adc_clk:
1336         clk_disable_unprepare(st->adc_clk);
1337 error_disable_clk:
1338         clk_disable_unprepare(st->clk);
1339 error_free_irq:
1340         free_irq(st->irq, idev);
1341         return ret;
1342 }
1343
1344 static int at91_adc_remove(struct platform_device *pdev)
1345 {
1346         struct iio_dev *idev = platform_get_drvdata(pdev);
1347         struct at91_adc_state *st = iio_priv(idev);
1348
1349         iio_device_unregister(idev);
1350         if (!st->touchscreen_type) {
1351                 at91_adc_trigger_remove(idev);
1352                 at91_adc_buffer_remove(idev);
1353         } else {
1354                 at91_ts_unregister(st);
1355         }
1356         clk_disable_unprepare(st->adc_clk);
1357         clk_disable_unprepare(st->clk);
1358         free_irq(st->irq, idev);
1359
1360         return 0;
1361 }
1362
1363 #ifdef CONFIG_PM_SLEEP
1364 static int at91_adc_suspend(struct device *dev)
1365 {
1366         struct iio_dev *idev = platform_get_drvdata(to_platform_device(dev));
1367         struct at91_adc_state *st = iio_priv(idev);
1368
1369         pinctrl_pm_select_sleep_state(dev);
1370         clk_disable_unprepare(st->clk);
1371
1372         return 0;
1373 }
1374
1375 static int at91_adc_resume(struct device *dev)
1376 {
1377         struct iio_dev *idev = platform_get_drvdata(to_platform_device(dev));
1378         struct at91_adc_state *st = iio_priv(idev);
1379
1380         clk_prepare_enable(st->clk);
1381         pinctrl_pm_select_default_state(dev);
1382
1383         return 0;
1384 }
1385 #endif
1386
1387 static SIMPLE_DEV_PM_OPS(at91_adc_pm_ops, at91_adc_suspend, at91_adc_resume);
1388
1389 static struct at91_adc_caps at91sam9260_caps = {
1390         .calc_startup_ticks = calc_startup_ticks_9260,
1391         .num_channels = 4,
1392         .registers = {
1393                 .channel_base = AT91_ADC_CHR(0),
1394                 .drdy_mask = AT91_ADC_DRDY,
1395                 .status_register = AT91_ADC_SR,
1396                 .trigger_register = AT91_ADC_TRGR_9260,
1397                 .mr_prescal_mask = AT91_ADC_PRESCAL_9260,
1398                 .mr_startup_mask = AT91_ADC_STARTUP_9260,
1399         },
1400 };
1401
1402 static struct at91_adc_caps at91sam9rl_caps = {
1403         .has_ts = true,
1404         .calc_startup_ticks = calc_startup_ticks_9260,  /* same as 9260 */
1405         .num_channels = 6,
1406         .registers = {
1407                 .channel_base = AT91_ADC_CHR(0),
1408                 .drdy_mask = AT91_ADC_DRDY,
1409                 .status_register = AT91_ADC_SR,
1410                 .trigger_register = AT91_ADC_TRGR_9G45,
1411                 .mr_prescal_mask = AT91_ADC_PRESCAL_9260,
1412                 .mr_startup_mask = AT91_ADC_STARTUP_9G45,
1413         },
1414 };
1415
1416 static struct at91_adc_caps at91sam9g45_caps = {
1417         .has_ts = true,
1418         .calc_startup_ticks = calc_startup_ticks_9260,  /* same as 9260 */
1419         .num_channels = 8,
1420         .registers = {
1421                 .channel_base = AT91_ADC_CHR(0),
1422                 .drdy_mask = AT91_ADC_DRDY,
1423                 .status_register = AT91_ADC_SR,
1424                 .trigger_register = AT91_ADC_TRGR_9G45,
1425                 .mr_prescal_mask = AT91_ADC_PRESCAL_9G45,
1426                 .mr_startup_mask = AT91_ADC_STARTUP_9G45,
1427         },
1428 };
1429
1430 static struct at91_adc_caps at91sam9x5_caps = {
1431         .has_ts = true,
1432         .has_tsmr = true,
1433         .ts_filter_average = 3,
1434         .ts_pen_detect_sensitivity = 2,
1435         .calc_startup_ticks = calc_startup_ticks_9x5,
1436         .num_channels = 12,
1437         .registers = {
1438                 .channel_base = AT91_ADC_CDR0_9X5,
1439                 .drdy_mask = AT91_ADC_SR_DRDY_9X5,
1440                 .status_register = AT91_ADC_SR_9X5,
1441                 .trigger_register = AT91_ADC_TRGR_9X5,
1442                 /* prescal mask is same as 9G45 */
1443                 .mr_prescal_mask = AT91_ADC_PRESCAL_9G45,
1444                 .mr_startup_mask = AT91_ADC_STARTUP_9X5,
1445         },
1446 };
1447
1448 static const struct of_device_id at91_adc_dt_ids[] = {
1449         { .compatible = "atmel,at91sam9260-adc", .data = &at91sam9260_caps },
1450         { .compatible = "atmel,at91sam9rl-adc", .data = &at91sam9rl_caps },
1451         { .compatible = "atmel,at91sam9g45-adc", .data = &at91sam9g45_caps },
1452         { .compatible = "atmel,at91sam9x5-adc", .data = &at91sam9x5_caps },
1453         {},
1454 };
1455 MODULE_DEVICE_TABLE(of, at91_adc_dt_ids);
1456
1457 static const struct platform_device_id at91_adc_ids[] = {
1458         {
1459                 .name = "at91sam9260-adc",
1460                 .driver_data = (unsigned long)&at91sam9260_caps,
1461         }, {
1462                 .name = "at91sam9rl-adc",
1463                 .driver_data = (unsigned long)&at91sam9rl_caps,
1464         }, {
1465                 .name = "at91sam9g45-adc",
1466                 .driver_data = (unsigned long)&at91sam9g45_caps,
1467         }, {
1468                 .name = "at91sam9x5-adc",
1469                 .driver_data = (unsigned long)&at91sam9x5_caps,
1470         }, {
1471                 /* terminator */
1472         }
1473 };
1474 MODULE_DEVICE_TABLE(platform, at91_adc_ids);
1475
1476 static struct platform_driver at91_adc_driver = {
1477         .probe = at91_adc_probe,
1478         .remove = at91_adc_remove,
1479         .id_table = at91_adc_ids,
1480         .driver = {
1481                    .name = DRIVER_NAME,
1482                    .of_match_table = of_match_ptr(at91_adc_dt_ids),
1483                    .pm = &at91_adc_pm_ops,
1484         },
1485 };
1486
1487 module_platform_driver(at91_adc_driver);
1488
1489 MODULE_LICENSE("GPL");
1490 MODULE_DESCRIPTION("Atmel AT91 ADC Driver");
1491 MODULE_AUTHOR("Maxime Ripard <maxime.ripard@free-electrons.com>");