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