]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/iio/adc/stm32-dfsdm-adc.c
iio: adc: stm32-dfsdm: fix data type
[linux.git] / drivers / iio / adc / stm32-dfsdm-adc.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This file is the ADC part of the STM32 DFSDM driver
4  *
5  * Copyright (C) 2017, STMicroelectronics - All Rights Reserved
6  * Author: Arnaud Pouliquen <arnaud.pouliquen@st.com>.
7  */
8
9 #include <linux/dmaengine.h>
10 #include <linux/dma-mapping.h>
11 #include <linux/iio/adc/stm32-dfsdm-adc.h>
12 #include <linux/iio/buffer.h>
13 #include <linux/iio/hw-consumer.h>
14 #include <linux/iio/sysfs.h>
15 #include <linux/iio/timer/stm32-lptim-trigger.h>
16 #include <linux/iio/timer/stm32-timer-trigger.h>
17 #include <linux/iio/trigger.h>
18 #include <linux/iio/trigger_consumer.h>
19 #include <linux/iio/triggered_buffer.h>
20 #include <linux/interrupt.h>
21 #include <linux/module.h>
22 #include <linux/of_device.h>
23 #include <linux/platform_device.h>
24 #include <linux/regmap.h>
25 #include <linux/slab.h>
26
27 #include "stm32-dfsdm.h"
28
29 #define DFSDM_DMA_BUFFER_SIZE (4 * PAGE_SIZE)
30
31 /* Conversion timeout */
32 #define DFSDM_TIMEOUT_US 100000
33 #define DFSDM_TIMEOUT (msecs_to_jiffies(DFSDM_TIMEOUT_US / 1000))
34
35 /* Oversampling attribute default */
36 #define DFSDM_DEFAULT_OVERSAMPLING  100
37
38 /* Oversampling max values */
39 #define DFSDM_MAX_INT_OVERSAMPLING 256
40 #define DFSDM_MAX_FL_OVERSAMPLING 1024
41
42 /* Limit filter output resolution to 31 bits. (i.e. sample range is +/-2^30) */
43 #define DFSDM_DATA_MAX BIT(30)
44 /*
45  * Data are output as two's complement data in a 24 bit field.
46  * Data from filters are in the range +/-2^(n-1)
47  * 2^(n-1) maximum positive value cannot be coded in 2's complement n bits
48  * An extra bit is required to avoid wrap-around of the binary code for 2^(n-1)
49  * So, the resolution of samples from filter is actually limited to 23 bits
50  */
51 #define DFSDM_DATA_RES 24
52
53 /* Filter configuration */
54 #define DFSDM_CR1_CFG_MASK (DFSDM_CR1_RCH_MASK | DFSDM_CR1_RCONT_MASK | \
55                             DFSDM_CR1_RSYNC_MASK | DFSDM_CR1_JSYNC_MASK | \
56                             DFSDM_CR1_JSCAN_MASK)
57
58 enum sd_converter_type {
59         DFSDM_AUDIO,
60         DFSDM_IIO,
61 };
62
63 struct stm32_dfsdm_dev_data {
64         int type;
65         int (*init)(struct iio_dev *indio_dev);
66         unsigned int num_channels;
67         const struct regmap_config *regmap_cfg;
68 };
69
70 struct stm32_dfsdm_adc {
71         struct stm32_dfsdm *dfsdm;
72         const struct stm32_dfsdm_dev_data *dev_data;
73         unsigned int fl_id;
74         unsigned int nconv;
75         unsigned long smask;
76
77         /* ADC specific */
78         unsigned int oversamp;
79         struct iio_hw_consumer *hwc;
80         struct completion completion;
81         u32 *buffer;
82
83         /* Audio specific */
84         unsigned int spi_freq;  /* SPI bus clock frequency */
85         unsigned int sample_freq; /* Sample frequency after filter decimation */
86         int (*cb)(const void *data, size_t size, void *cb_priv);
87         void *cb_priv;
88
89         /* DMA */
90         u8 *rx_buf;
91         unsigned int bufi; /* Buffer current position */
92         unsigned int buf_sz; /* Buffer size */
93         struct dma_chan *dma_chan;
94         dma_addr_t dma_buf;
95 };
96
97 struct stm32_dfsdm_str2field {
98         const char      *name;
99         unsigned int    val;
100 };
101
102 /* DFSDM channel serial interface type */
103 static const struct stm32_dfsdm_str2field stm32_dfsdm_chan_type[] = {
104         { "SPI_R", 0 }, /* SPI with data on rising edge */
105         { "SPI_F", 1 }, /* SPI with data on falling edge */
106         { "MANCH_R", 2 }, /* Manchester codec, rising edge = logic 0 */
107         { "MANCH_F", 3 }, /* Manchester codec, falling edge = logic 1 */
108         {},
109 };
110
111 /* DFSDM channel clock source */
112 static const struct stm32_dfsdm_str2field stm32_dfsdm_chan_src[] = {
113         /* External SPI clock (CLKIN x) */
114         { "CLKIN", DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL },
115         /* Internal SPI clock (CLKOUT) */
116         { "CLKOUT", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL },
117         /* Internal SPI clock divided by 2 (falling edge) */
118         { "CLKOUT_F", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_FALLING },
119         /* Internal SPI clock divided by 2 (falling edge) */
120         { "CLKOUT_R", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_RISING },
121         {},
122 };
123
124 static int stm32_dfsdm_str2val(const char *str,
125                                const struct stm32_dfsdm_str2field *list)
126 {
127         const struct stm32_dfsdm_str2field *p = list;
128
129         for (p = list; p && p->name; p++)
130                 if (!strcmp(p->name, str))
131                         return p->val;
132
133         return -EINVAL;
134 }
135
136 /**
137  * struct stm32_dfsdm_trig_info - DFSDM trigger info
138  * @name:               name of the trigger, corresponding to its source
139  * @jextsel:            trigger signal selection
140  */
141 struct stm32_dfsdm_trig_info {
142         const char *name;
143         unsigned int jextsel;
144 };
145
146 /* hardware injected trigger enable, edge selection */
147 enum stm32_dfsdm_jexten {
148         STM32_DFSDM_JEXTEN_DISABLED,
149         STM32_DFSDM_JEXTEN_RISING_EDGE,
150         STM32_DFSDM_JEXTEN_FALLING_EDGE,
151         STM32_DFSDM_EXTEN_BOTH_EDGES,
152 };
153
154 static const struct stm32_dfsdm_trig_info stm32_dfsdm_trigs[] = {
155         { TIM1_TRGO, 0 },
156         { TIM1_TRGO2, 1 },
157         { TIM8_TRGO, 2 },
158         { TIM8_TRGO2, 3 },
159         { TIM3_TRGO, 4 },
160         { TIM4_TRGO, 5 },
161         { TIM16_OC1, 6 },
162         { TIM6_TRGO, 7 },
163         { TIM7_TRGO, 8 },
164         { LPTIM1_OUT, 26 },
165         { LPTIM2_OUT, 27 },
166         { LPTIM3_OUT, 28 },
167         {},
168 };
169
170 static int stm32_dfsdm_get_jextsel(struct iio_dev *indio_dev,
171                                    struct iio_trigger *trig)
172 {
173         int i;
174
175         /* lookup triggers registered by stm32 timer trigger driver */
176         for (i = 0; stm32_dfsdm_trigs[i].name; i++) {
177                 /**
178                  * Checking both stm32 timer trigger type and trig name
179                  * should be safe against arbitrary trigger names.
180                  */
181                 if ((is_stm32_timer_trigger(trig) ||
182                      is_stm32_lptim_trigger(trig)) &&
183                     !strcmp(stm32_dfsdm_trigs[i].name, trig->name)) {
184                         return stm32_dfsdm_trigs[i].jextsel;
185                 }
186         }
187
188         return -EINVAL;
189 }
190
191 static int stm32_dfsdm_compute_osrs(struct stm32_dfsdm_filter *fl,
192                                     unsigned int fast, unsigned int oversamp)
193 {
194         unsigned int i, d, fosr, iosr;
195         u64 res, max;
196         int bits, shift;
197         unsigned int m = 1;     /* multiplication factor */
198         unsigned int p = fl->ford;      /* filter order (ford) */
199         struct stm32_dfsdm_filter_osr *flo = &fl->flo;
200
201         pr_debug("%s: Requested oversampling: %d\n",  __func__, oversamp);
202         /*
203          * This function tries to compute filter oversampling and integrator
204          * oversampling, base on oversampling ratio requested by user.
205          *
206          * Decimation d depends on the filter order and the oversampling ratios.
207          * ford: filter order
208          * fosr: filter over sampling ratio
209          * iosr: integrator over sampling ratio
210          */
211         if (fl->ford == DFSDM_FASTSINC_ORDER) {
212                 m = 2;
213                 p = 2;
214         }
215
216         /*
217          * Look for filter and integrator oversampling ratios which allows
218          * to maximize data output resolution.
219          */
220         flo->res = 0;
221         for (fosr = 1; fosr <= DFSDM_MAX_FL_OVERSAMPLING; fosr++) {
222                 for (iosr = 1; iosr <= DFSDM_MAX_INT_OVERSAMPLING; iosr++) {
223                         if (fast)
224                                 d = fosr * iosr;
225                         else if (fl->ford == DFSDM_FASTSINC_ORDER)
226                                 d = fosr * (iosr + 3) + 2;
227                         else
228                                 d = fosr * (iosr - 1 + p) + p;
229
230                         if (d > oversamp)
231                                 break;
232                         else if (d != oversamp)
233                                 continue;
234                         /*
235                          * Check resolution (limited to signed 32 bits)
236                          *   res <= 2^31
237                          * Sincx filters:
238                          *   res = m * fosr^p x iosr (with m=1, p=ford)
239                          * FastSinc filter
240                          *   res = m * fosr^p x iosr (with m=2, p=2)
241                          */
242                         res = fosr;
243                         for (i = p - 1; i > 0; i--) {
244                                 res = res * (u64)fosr;
245                                 if (res > DFSDM_DATA_MAX)
246                                         break;
247                         }
248                         if (res > DFSDM_DATA_MAX)
249                                 continue;
250
251                         res = res * (u64)m * (u64)iosr;
252                         if (res > DFSDM_DATA_MAX)
253                                 continue;
254
255                         if (res >= flo->res) {
256                                 flo->res = res;
257                                 flo->fosr = fosr;
258                                 flo->iosr = iosr;
259
260                                 bits = fls(flo->res);
261                                 /* 8 LBSs in data register contain chan info */
262                                 max = flo->res << 8;
263
264                                 /* if resolution is not a power of two */
265                                 if (flo->res > BIT(bits - 1))
266                                         bits++;
267                                 else
268                                         max--;
269
270                                 shift = DFSDM_DATA_RES - bits;
271                                 /*
272                                  * Compute right/left shift
273                                  * Right shift is performed by hardware
274                                  * when transferring samples to data register.
275                                  * Left shift is done by software on buffer
276                                  */
277                                 if (shift > 0) {
278                                         /* Resolution is lower than 24 bits */
279                                         flo->rshift = 0;
280                                         flo->lshift = shift;
281                                 } else {
282                                         /*
283                                          * If resolution is 24 bits or more,
284                                          * max positive value may be ambiguous
285                                          * (equal to max negative value as sign
286                                          * bit is dropped).
287                                          * Reduce resolution to 23 bits (rshift)
288                                          * to keep the sign on bit 23 and treat
289                                          * saturation before rescaling on 24
290                                          * bits (lshift).
291                                          */
292                                         flo->rshift = 1 - shift;
293                                         flo->lshift = 1;
294                                         max >>= flo->rshift;
295                                 }
296                                 flo->max = (s32)max;
297
298                                 pr_debug("%s: fast %d, fosr %d, iosr %d, res 0x%llx/%d bits, rshift %d, lshift %d\n",
299                                          __func__, fast, flo->fosr, flo->iosr,
300                                          flo->res, bits, flo->rshift,
301                                          flo->lshift);
302                         }
303                 }
304         }
305
306         if (!flo->res)
307                 return -EINVAL;
308
309         return 0;
310 }
311
312 static int stm32_dfsdm_start_channel(struct stm32_dfsdm_adc *adc)
313 {
314         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
315         struct regmap *regmap = adc->dfsdm->regmap;
316         const struct iio_chan_spec *chan;
317         unsigned int bit;
318         int ret;
319
320         for_each_set_bit(bit, &adc->smask, sizeof(adc->smask) * BITS_PER_BYTE) {
321                 chan = indio_dev->channels + bit;
322                 ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(chan->channel),
323                                          DFSDM_CHCFGR1_CHEN_MASK,
324                                          DFSDM_CHCFGR1_CHEN(1));
325                 if (ret < 0)
326                         return ret;
327         }
328
329         return 0;
330 }
331
332 static void stm32_dfsdm_stop_channel(struct stm32_dfsdm_adc *adc)
333 {
334         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
335         struct regmap *regmap = adc->dfsdm->regmap;
336         const struct iio_chan_spec *chan;
337         unsigned int bit;
338
339         for_each_set_bit(bit, &adc->smask, sizeof(adc->smask) * BITS_PER_BYTE) {
340                 chan = indio_dev->channels + bit;
341                 regmap_update_bits(regmap, DFSDM_CHCFGR1(chan->channel),
342                                    DFSDM_CHCFGR1_CHEN_MASK,
343                                    DFSDM_CHCFGR1_CHEN(0));
344         }
345 }
346
347 static int stm32_dfsdm_chan_configure(struct stm32_dfsdm *dfsdm,
348                                       struct stm32_dfsdm_channel *ch)
349 {
350         unsigned int id = ch->id;
351         struct regmap *regmap = dfsdm->regmap;
352         int ret;
353
354         ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
355                                  DFSDM_CHCFGR1_SITP_MASK,
356                                  DFSDM_CHCFGR1_SITP(ch->type));
357         if (ret < 0)
358                 return ret;
359         ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
360                                  DFSDM_CHCFGR1_SPICKSEL_MASK,
361                                  DFSDM_CHCFGR1_SPICKSEL(ch->src));
362         if (ret < 0)
363                 return ret;
364         return regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
365                                   DFSDM_CHCFGR1_CHINSEL_MASK,
366                                   DFSDM_CHCFGR1_CHINSEL(ch->alt_si));
367 }
368
369 static int stm32_dfsdm_start_filter(struct stm32_dfsdm_adc *adc,
370                                     unsigned int fl_id,
371                                     struct iio_trigger *trig)
372 {
373         struct stm32_dfsdm *dfsdm = adc->dfsdm;
374         int ret;
375
376         /* Enable filter */
377         ret = regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
378                                  DFSDM_CR1_DFEN_MASK, DFSDM_CR1_DFEN(1));
379         if (ret < 0)
380                 return ret;
381
382         /* Nothing more to do for injected (scan mode/triggered) conversions */
383         if (adc->nconv > 1 || trig)
384                 return 0;
385
386         /* Software start (single or continuous) regular conversion */
387         return regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
388                                   DFSDM_CR1_RSWSTART_MASK,
389                                   DFSDM_CR1_RSWSTART(1));
390 }
391
392 static void stm32_dfsdm_stop_filter(struct stm32_dfsdm *dfsdm,
393                                     unsigned int fl_id)
394 {
395         /* Disable conversion */
396         regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
397                            DFSDM_CR1_DFEN_MASK, DFSDM_CR1_DFEN(0));
398 }
399
400 static int stm32_dfsdm_filter_set_trig(struct stm32_dfsdm_adc *adc,
401                                        unsigned int fl_id,
402                                        struct iio_trigger *trig)
403 {
404         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
405         struct regmap *regmap = adc->dfsdm->regmap;
406         u32 jextsel = 0, jexten = STM32_DFSDM_JEXTEN_DISABLED;
407         int ret;
408
409         if (trig) {
410                 ret = stm32_dfsdm_get_jextsel(indio_dev, trig);
411                 if (ret < 0)
412                         return ret;
413
414                 /* set trigger source and polarity (default to rising edge) */
415                 jextsel = ret;
416                 jexten = STM32_DFSDM_JEXTEN_RISING_EDGE;
417         }
418
419         ret = regmap_update_bits(regmap, DFSDM_CR1(fl_id),
420                                  DFSDM_CR1_JEXTSEL_MASK | DFSDM_CR1_JEXTEN_MASK,
421                                  DFSDM_CR1_JEXTSEL(jextsel) |
422                                  DFSDM_CR1_JEXTEN(jexten));
423         if (ret < 0)
424                 return ret;
425
426         return 0;
427 }
428
429 static int stm32_dfsdm_channels_configure(struct stm32_dfsdm_adc *adc,
430                                           unsigned int fl_id,
431                                           struct iio_trigger *trig)
432 {
433         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
434         struct regmap *regmap = adc->dfsdm->regmap;
435         struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[fl_id];
436         struct stm32_dfsdm_filter_osr *flo = &fl->flo;
437         const struct iio_chan_spec *chan;
438         unsigned int bit;
439         int ret;
440
441         if (!flo->res)
442                 return -EINVAL;
443
444         for_each_set_bit(bit, &adc->smask,
445                          sizeof(adc->smask) * BITS_PER_BYTE) {
446                 chan = indio_dev->channels + bit;
447
448                 ret = regmap_update_bits(regmap,
449                                          DFSDM_CHCFGR2(chan->channel),
450                                          DFSDM_CHCFGR2_DTRBS_MASK,
451                                          DFSDM_CHCFGR2_DTRBS(flo->rshift));
452                 if (ret)
453                         return ret;
454         }
455
456         return 0;
457 }
458
459 static int stm32_dfsdm_filter_configure(struct stm32_dfsdm_adc *adc,
460                                         unsigned int fl_id,
461                                         struct iio_trigger *trig)
462 {
463         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
464         struct regmap *regmap = adc->dfsdm->regmap;
465         struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[fl_id];
466         struct stm32_dfsdm_filter_osr *flo = &fl->flo;
467         u32 cr1;
468         const struct iio_chan_spec *chan;
469         unsigned int bit, jchg = 0;
470         int ret;
471
472         /* Average integrator oversampling */
473         ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_IOSR_MASK,
474                                  DFSDM_FCR_IOSR(flo->iosr - 1));
475         if (ret)
476                 return ret;
477
478         /* Filter order and Oversampling */
479         ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_FOSR_MASK,
480                                  DFSDM_FCR_FOSR(flo->fosr - 1));
481         if (ret)
482                 return ret;
483
484         ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_FORD_MASK,
485                                  DFSDM_FCR_FORD(fl->ford));
486         if (ret)
487                 return ret;
488
489         ret = stm32_dfsdm_filter_set_trig(adc, fl_id, trig);
490         if (ret)
491                 return ret;
492
493         /*
494          * DFSDM modes configuration W.R.T audio/iio type modes
495          * ----------------------------------------------------------------
496          * Modes         | regular |  regular     | injected | injected   |
497          *               |         |  continuous  |          | + scan     |
498          * --------------|---------|--------------|----------|------------|
499          * single conv   |    x    |              |          |            |
500          * (1 chan)      |         |              |          |            |
501          * --------------|---------|--------------|----------|------------|
502          * 1 Audio chan  |         | sample freq  |          |            |
503          *               |         | or sync_mode |          |            |
504          * --------------|---------|--------------|----------|------------|
505          * 1 IIO chan    |         | sample freq  | trigger  |            |
506          *               |         | or sync_mode |          |            |
507          * --------------|---------|--------------|----------|------------|
508          * 2+ IIO chans  |         |              |          | trigger or |
509          *               |         |              |          | sync_mode  |
510          * ----------------------------------------------------------------
511          */
512         if (adc->nconv == 1 && !trig) {
513                 bit = __ffs(adc->smask);
514                 chan = indio_dev->channels + bit;
515
516                 /* Use regular conversion for single channel without trigger */
517                 cr1 = DFSDM_CR1_RCH(chan->channel);
518
519                 /* Continuous conversions triggered by SPI clk in buffer mode */
520                 if (indio_dev->currentmode & INDIO_BUFFER_SOFTWARE)
521                         cr1 |= DFSDM_CR1_RCONT(1);
522
523                 cr1 |= DFSDM_CR1_RSYNC(fl->sync_mode);
524         } else {
525                 /* Use injected conversion for multiple channels */
526                 for_each_set_bit(bit, &adc->smask,
527                                  sizeof(adc->smask) * BITS_PER_BYTE) {
528                         chan = indio_dev->channels + bit;
529                         jchg |= BIT(chan->channel);
530                 }
531                 ret = regmap_write(regmap, DFSDM_JCHGR(fl_id), jchg);
532                 if (ret < 0)
533                         return ret;
534
535                 /* Use scan mode for multiple channels */
536                 cr1 = DFSDM_CR1_JSCAN((adc->nconv > 1) ? 1 : 0);
537
538                 /*
539                  * Continuous conversions not supported in injected mode,
540                  * either use:
541                  * - conversions in sync with filter 0
542                  * - triggered conversions
543                  */
544                 if (!fl->sync_mode && !trig)
545                         return -EINVAL;
546                 cr1 |= DFSDM_CR1_JSYNC(fl->sync_mode);
547         }
548
549         return regmap_update_bits(regmap, DFSDM_CR1(fl_id), DFSDM_CR1_CFG_MASK,
550                                   cr1);
551 }
552
553 static int stm32_dfsdm_channel_parse_of(struct stm32_dfsdm *dfsdm,
554                                         struct iio_dev *indio_dev,
555                                         struct iio_chan_spec *ch)
556 {
557         struct stm32_dfsdm_channel *df_ch;
558         const char *of_str;
559         int chan_idx = ch->scan_index;
560         int ret, val;
561
562         ret = of_property_read_u32_index(indio_dev->dev.of_node,
563                                          "st,adc-channels", chan_idx,
564                                          &ch->channel);
565         if (ret < 0) {
566                 dev_err(&indio_dev->dev,
567                         " Error parsing 'st,adc-channels' for idx %d\n",
568                         chan_idx);
569                 return ret;
570         }
571         if (ch->channel >= dfsdm->num_chs) {
572                 dev_err(&indio_dev->dev,
573                         " Error bad channel number %d (max = %d)\n",
574                         ch->channel, dfsdm->num_chs);
575                 return -EINVAL;
576         }
577
578         ret = of_property_read_string_index(indio_dev->dev.of_node,
579                                             "st,adc-channel-names", chan_idx,
580                                             &ch->datasheet_name);
581         if (ret < 0) {
582                 dev_err(&indio_dev->dev,
583                         " Error parsing 'st,adc-channel-names' for idx %d\n",
584                         chan_idx);
585                 return ret;
586         }
587
588         df_ch =  &dfsdm->ch_list[ch->channel];
589         df_ch->id = ch->channel;
590
591         ret = of_property_read_string_index(indio_dev->dev.of_node,
592                                             "st,adc-channel-types", chan_idx,
593                                             &of_str);
594         if (!ret) {
595                 val = stm32_dfsdm_str2val(of_str, stm32_dfsdm_chan_type);
596                 if (val < 0)
597                         return val;
598         } else {
599                 val = 0;
600         }
601         df_ch->type = val;
602
603         ret = of_property_read_string_index(indio_dev->dev.of_node,
604                                             "st,adc-channel-clk-src", chan_idx,
605                                             &of_str);
606         if (!ret) {
607                 val = stm32_dfsdm_str2val(of_str, stm32_dfsdm_chan_src);
608                 if (val < 0)
609                         return val;
610         } else {
611                 val = 0;
612         }
613         df_ch->src = val;
614
615         ret = of_property_read_u32_index(indio_dev->dev.of_node,
616                                          "st,adc-alt-channel", chan_idx,
617                                          &df_ch->alt_si);
618         if (ret < 0)
619                 df_ch->alt_si = 0;
620
621         return 0;
622 }
623
624 static ssize_t dfsdm_adc_audio_get_spiclk(struct iio_dev *indio_dev,
625                                           uintptr_t priv,
626                                           const struct iio_chan_spec *chan,
627                                           char *buf)
628 {
629         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
630
631         return snprintf(buf, PAGE_SIZE, "%d\n", adc->spi_freq);
632 }
633
634 static int dfsdm_adc_set_samp_freq(struct iio_dev *indio_dev,
635                                    unsigned int sample_freq,
636                                    unsigned int spi_freq)
637 {
638         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
639         struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[adc->fl_id];
640         unsigned int oversamp;
641         int ret;
642
643         oversamp = DIV_ROUND_CLOSEST(spi_freq, sample_freq);
644         if (spi_freq % sample_freq)
645                 dev_dbg(&indio_dev->dev,
646                         "Rate not accurate. requested (%u), actual (%u)\n",
647                         sample_freq, spi_freq / oversamp);
648
649         ret = stm32_dfsdm_compute_osrs(fl, 0, oversamp);
650         if (ret < 0) {
651                 dev_err(&indio_dev->dev, "No filter parameters that match!\n");
652                 return ret;
653         }
654         adc->sample_freq = spi_freq / oversamp;
655         adc->oversamp = oversamp;
656
657         return 0;
658 }
659
660 static ssize_t dfsdm_adc_audio_set_spiclk(struct iio_dev *indio_dev,
661                                           uintptr_t priv,
662                                           const struct iio_chan_spec *chan,
663                                           const char *buf, size_t len)
664 {
665         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
666         struct stm32_dfsdm_channel *ch = &adc->dfsdm->ch_list[chan->channel];
667         unsigned int sample_freq = adc->sample_freq;
668         unsigned int spi_freq;
669         int ret;
670
671         dev_err(&indio_dev->dev, "enter %s\n", __func__);
672         /* If DFSDM is master on SPI, SPI freq can not be updated */
673         if (ch->src != DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL)
674                 return -EPERM;
675
676         ret = kstrtoint(buf, 0, &spi_freq);
677         if (ret)
678                 return ret;
679
680         if (!spi_freq)
681                 return -EINVAL;
682
683         if (sample_freq) {
684                 ret = dfsdm_adc_set_samp_freq(indio_dev, sample_freq, spi_freq);
685                 if (ret < 0)
686                         return ret;
687         }
688         adc->spi_freq = spi_freq;
689
690         return len;
691 }
692
693 static int stm32_dfsdm_start_conv(struct stm32_dfsdm_adc *adc,
694                                   struct iio_trigger *trig)
695 {
696         struct regmap *regmap = adc->dfsdm->regmap;
697         int ret;
698
699         ret = stm32_dfsdm_channels_configure(adc, adc->fl_id, trig);
700         if (ret < 0)
701                 return ret;
702
703         ret = stm32_dfsdm_start_channel(adc);
704         if (ret < 0)
705                 return ret;
706
707         ret = stm32_dfsdm_filter_configure(adc, adc->fl_id, trig);
708         if (ret < 0)
709                 goto stop_channels;
710
711         ret = stm32_dfsdm_start_filter(adc, adc->fl_id, trig);
712         if (ret < 0)
713                 goto filter_unconfigure;
714
715         return 0;
716
717 filter_unconfigure:
718         regmap_update_bits(regmap, DFSDM_CR1(adc->fl_id),
719                            DFSDM_CR1_CFG_MASK, 0);
720 stop_channels:
721         stm32_dfsdm_stop_channel(adc);
722
723         return ret;
724 }
725
726 static void stm32_dfsdm_stop_conv(struct stm32_dfsdm_adc *adc)
727 {
728         struct regmap *regmap = adc->dfsdm->regmap;
729
730         stm32_dfsdm_stop_filter(adc->dfsdm, adc->fl_id);
731
732         regmap_update_bits(regmap, DFSDM_CR1(adc->fl_id),
733                            DFSDM_CR1_CFG_MASK, 0);
734
735         stm32_dfsdm_stop_channel(adc);
736 }
737
738 static int stm32_dfsdm_set_watermark(struct iio_dev *indio_dev,
739                                      unsigned int val)
740 {
741         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
742         unsigned int watermark = DFSDM_DMA_BUFFER_SIZE / 2;
743         unsigned int rx_buf_sz = DFSDM_DMA_BUFFER_SIZE;
744
745         /*
746          * DMA cyclic transfers are used, buffer is split into two periods.
747          * There should be :
748          * - always one buffer (period) DMA is working on
749          * - one buffer (period) driver pushed to ASoC side.
750          */
751         watermark = min(watermark, val * (unsigned int)(sizeof(u32)));
752         adc->buf_sz = min(rx_buf_sz, watermark * 2 * adc->nconv);
753
754         return 0;
755 }
756
757 static unsigned int stm32_dfsdm_adc_dma_residue(struct stm32_dfsdm_adc *adc)
758 {
759         struct dma_tx_state state;
760         enum dma_status status;
761
762         status = dmaengine_tx_status(adc->dma_chan,
763                                      adc->dma_chan->cookie,
764                                      &state);
765         if (status == DMA_IN_PROGRESS) {
766                 /* Residue is size in bytes from end of buffer */
767                 unsigned int i = adc->buf_sz - state.residue;
768                 unsigned int size;
769
770                 /* Return available bytes */
771                 if (i >= adc->bufi)
772                         size = i - adc->bufi;
773                 else
774                         size = adc->buf_sz + i - adc->bufi;
775
776                 return size;
777         }
778
779         return 0;
780 }
781
782 static irqreturn_t stm32_dfsdm_adc_trigger_handler(int irq, void *p)
783 {
784         struct iio_poll_func *pf = p;
785         struct iio_dev *indio_dev = pf->indio_dev;
786         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
787         int available = stm32_dfsdm_adc_dma_residue(adc);
788
789         while (available >= indio_dev->scan_bytes) {
790                 u32 *buffer = (u32 *)&adc->rx_buf[adc->bufi];
791
792                 iio_push_to_buffers_with_timestamp(indio_dev, buffer,
793                                                    pf->timestamp);
794                 available -= indio_dev->scan_bytes;
795                 adc->bufi += indio_dev->scan_bytes;
796                 if (adc->bufi >= adc->buf_sz)
797                         adc->bufi = 0;
798         }
799
800         iio_trigger_notify_done(indio_dev->trig);
801
802         return IRQ_HANDLED;
803 }
804
805 static void stm32_dfsdm_dma_buffer_done(void *data)
806 {
807         struct iio_dev *indio_dev = data;
808         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
809         struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[adc->fl_id];
810         struct stm32_dfsdm_filter_osr *flo = &fl->flo;
811         int available = stm32_dfsdm_adc_dma_residue(adc);
812         size_t old_pos;
813
814         if (indio_dev->currentmode & INDIO_BUFFER_TRIGGERED) {
815                 iio_trigger_poll_chained(indio_dev->trig);
816                 return;
817         }
818
819         /*
820          * FIXME: In Kernel interface does not support cyclic DMA buffer,and
821          * offers only an interface to push data samples per samples.
822          * For this reason IIO buffer interface is not used and interface is
823          * bypassed using a private callback registered by ASoC.
824          * This should be a temporary solution waiting a cyclic DMA engine
825          * support in IIO.
826          */
827
828         dev_dbg(&indio_dev->dev, "%s: pos = %d, available = %d\n", __func__,
829                 adc->bufi, available);
830         old_pos = adc->bufi;
831
832         while (available >= indio_dev->scan_bytes) {
833                 s32 *buffer = (s32 *)&adc->rx_buf[adc->bufi];
834
835                 /* Mask 8 LSB that contains the channel ID */
836                 *buffer &= 0xFFFFFF00;
837                 /* Convert 2^(n-1) sample to 2^(n-1)-1 to avoid wrap-around */
838                 if (*buffer > flo->max)
839                         *buffer -= 1;
840                 /*
841                  * Samples from filter are retrieved with 23 bits resolution
842                  * or less. Shift left to align MSB on 24 bits.
843                  */
844                 *buffer <<= flo->lshift;
845
846                 available -= indio_dev->scan_bytes;
847                 adc->bufi += indio_dev->scan_bytes;
848                 if (adc->bufi >= adc->buf_sz) {
849                         if (adc->cb)
850                                 adc->cb(&adc->rx_buf[old_pos],
851                                          adc->buf_sz - old_pos, adc->cb_priv);
852                         adc->bufi = 0;
853                         old_pos = 0;
854                 }
855                 /* regular iio buffer without trigger */
856                 if (adc->dev_data->type == DFSDM_IIO)
857                         iio_push_to_buffers(indio_dev, buffer);
858         }
859         if (adc->cb)
860                 adc->cb(&adc->rx_buf[old_pos], adc->bufi - old_pos,
861                         adc->cb_priv);
862 }
863
864 static int stm32_dfsdm_adc_dma_start(struct iio_dev *indio_dev)
865 {
866         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
867         struct dma_slave_config config = {
868                 .src_addr = (dma_addr_t)adc->dfsdm->phys_base,
869                 .src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES,
870         };
871         struct dma_async_tx_descriptor *desc;
872         dma_cookie_t cookie;
873         int ret;
874
875         if (!adc->dma_chan)
876                 return -EINVAL;
877
878         dev_dbg(&indio_dev->dev, "%s size=%d watermark=%d\n", __func__,
879                 adc->buf_sz, adc->buf_sz / 2);
880
881         if (adc->nconv == 1 && !indio_dev->trig)
882                 config.src_addr += DFSDM_RDATAR(adc->fl_id);
883         else
884                 config.src_addr += DFSDM_JDATAR(adc->fl_id);
885         ret = dmaengine_slave_config(adc->dma_chan, &config);
886         if (ret)
887                 return ret;
888
889         /* Prepare a DMA cyclic transaction */
890         desc = dmaengine_prep_dma_cyclic(adc->dma_chan,
891                                          adc->dma_buf,
892                                          adc->buf_sz, adc->buf_sz / 2,
893                                          DMA_DEV_TO_MEM,
894                                          DMA_PREP_INTERRUPT);
895         if (!desc)
896                 return -EBUSY;
897
898         desc->callback = stm32_dfsdm_dma_buffer_done;
899         desc->callback_param = indio_dev;
900
901         cookie = dmaengine_submit(desc);
902         ret = dma_submit_error(cookie);
903         if (ret)
904                 goto err_stop_dma;
905
906         /* Issue pending DMA requests */
907         dma_async_issue_pending(adc->dma_chan);
908
909         if (adc->nconv == 1 && !indio_dev->trig) {
910                 /* Enable regular DMA transfer*/
911                 ret = regmap_update_bits(adc->dfsdm->regmap,
912                                          DFSDM_CR1(adc->fl_id),
913                                          DFSDM_CR1_RDMAEN_MASK,
914                                          DFSDM_CR1_RDMAEN_MASK);
915         } else {
916                 /* Enable injected DMA transfer*/
917                 ret = regmap_update_bits(adc->dfsdm->regmap,
918                                          DFSDM_CR1(adc->fl_id),
919                                          DFSDM_CR1_JDMAEN_MASK,
920                                          DFSDM_CR1_JDMAEN_MASK);
921         }
922
923         if (ret < 0)
924                 goto err_stop_dma;
925
926         return 0;
927
928 err_stop_dma:
929         dmaengine_terminate_all(adc->dma_chan);
930
931         return ret;
932 }
933
934 static void stm32_dfsdm_adc_dma_stop(struct iio_dev *indio_dev)
935 {
936         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
937
938         if (!adc->dma_chan)
939                 return;
940
941         regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR1(adc->fl_id),
942                            DFSDM_CR1_RDMAEN_MASK | DFSDM_CR1_JDMAEN_MASK, 0);
943         dmaengine_terminate_all(adc->dma_chan);
944 }
945
946 static int stm32_dfsdm_update_scan_mode(struct iio_dev *indio_dev,
947                                         const unsigned long *scan_mask)
948 {
949         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
950
951         adc->nconv = bitmap_weight(scan_mask, indio_dev->masklength);
952         adc->smask = *scan_mask;
953
954         dev_dbg(&indio_dev->dev, "nconv=%d mask=%lx\n", adc->nconv, *scan_mask);
955
956         return 0;
957 }
958
959 static int __stm32_dfsdm_postenable(struct iio_dev *indio_dev)
960 {
961         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
962         int ret;
963
964         /* Reset adc buffer index */
965         adc->bufi = 0;
966
967         if (adc->hwc) {
968                 ret = iio_hw_consumer_enable(adc->hwc);
969                 if (ret < 0)
970                         return ret;
971         }
972
973         ret = stm32_dfsdm_start_dfsdm(adc->dfsdm);
974         if (ret < 0)
975                 goto err_stop_hwc;
976
977         ret = stm32_dfsdm_adc_dma_start(indio_dev);
978         if (ret) {
979                 dev_err(&indio_dev->dev, "Can't start DMA\n");
980                 goto stop_dfsdm;
981         }
982
983         ret = stm32_dfsdm_start_conv(adc, indio_dev->trig);
984         if (ret) {
985                 dev_err(&indio_dev->dev, "Can't start conversion\n");
986                 goto err_stop_dma;
987         }
988
989         return 0;
990
991 err_stop_dma:
992         stm32_dfsdm_adc_dma_stop(indio_dev);
993 stop_dfsdm:
994         stm32_dfsdm_stop_dfsdm(adc->dfsdm);
995 err_stop_hwc:
996         if (adc->hwc)
997                 iio_hw_consumer_disable(adc->hwc);
998
999         return ret;
1000 }
1001
1002 static int stm32_dfsdm_postenable(struct iio_dev *indio_dev)
1003 {
1004         int ret;
1005
1006         if (indio_dev->currentmode == INDIO_BUFFER_TRIGGERED) {
1007                 ret = iio_triggered_buffer_postenable(indio_dev);
1008                 if (ret < 0)
1009                         return ret;
1010         }
1011
1012         ret = __stm32_dfsdm_postenable(indio_dev);
1013         if (ret < 0)
1014                 goto err_predisable;
1015
1016         return 0;
1017
1018 err_predisable:
1019         if (indio_dev->currentmode == INDIO_BUFFER_TRIGGERED)
1020                 iio_triggered_buffer_predisable(indio_dev);
1021
1022         return ret;
1023 }
1024
1025 static void __stm32_dfsdm_predisable(struct iio_dev *indio_dev)
1026 {
1027         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1028
1029         stm32_dfsdm_stop_conv(adc);
1030
1031         stm32_dfsdm_adc_dma_stop(indio_dev);
1032
1033         stm32_dfsdm_stop_dfsdm(adc->dfsdm);
1034
1035         if (adc->hwc)
1036                 iio_hw_consumer_disable(adc->hwc);
1037 }
1038
1039 static int stm32_dfsdm_predisable(struct iio_dev *indio_dev)
1040 {
1041         __stm32_dfsdm_predisable(indio_dev);
1042
1043         if (indio_dev->currentmode == INDIO_BUFFER_TRIGGERED)
1044                 iio_triggered_buffer_predisable(indio_dev);
1045
1046         return 0;
1047 }
1048
1049 static const struct iio_buffer_setup_ops stm32_dfsdm_buffer_setup_ops = {
1050         .postenable = &stm32_dfsdm_postenable,
1051         .predisable = &stm32_dfsdm_predisable,
1052 };
1053
1054 /**
1055  * stm32_dfsdm_get_buff_cb() - register a callback that will be called when
1056  *                             DMA transfer period is achieved.
1057  *
1058  * @iio_dev: Handle to IIO device.
1059  * @cb: Pointer to callback function:
1060  *      - data: pointer to data buffer
1061  *      - size: size in byte of the data buffer
1062  *      - private: pointer to consumer private structure.
1063  * @private: Pointer to consumer private structure.
1064  */
1065 int stm32_dfsdm_get_buff_cb(struct iio_dev *iio_dev,
1066                             int (*cb)(const void *data, size_t size,
1067                                       void *private),
1068                             void *private)
1069 {
1070         struct stm32_dfsdm_adc *adc;
1071
1072         if (!iio_dev)
1073                 return -EINVAL;
1074         adc = iio_priv(iio_dev);
1075
1076         adc->cb = cb;
1077         adc->cb_priv = private;
1078
1079         return 0;
1080 }
1081 EXPORT_SYMBOL_GPL(stm32_dfsdm_get_buff_cb);
1082
1083 /**
1084  * stm32_dfsdm_release_buff_cb - unregister buffer callback
1085  *
1086  * @iio_dev: Handle to IIO device.
1087  */
1088 int stm32_dfsdm_release_buff_cb(struct iio_dev *iio_dev)
1089 {
1090         struct stm32_dfsdm_adc *adc;
1091
1092         if (!iio_dev)
1093                 return -EINVAL;
1094         adc = iio_priv(iio_dev);
1095
1096         adc->cb = NULL;
1097         adc->cb_priv = NULL;
1098
1099         return 0;
1100 }
1101 EXPORT_SYMBOL_GPL(stm32_dfsdm_release_buff_cb);
1102
1103 static int stm32_dfsdm_single_conv(struct iio_dev *indio_dev,
1104                                    const struct iio_chan_spec *chan, int *res)
1105 {
1106         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1107         long timeout;
1108         int ret;
1109
1110         reinit_completion(&adc->completion);
1111
1112         adc->buffer = res;
1113
1114         ret = stm32_dfsdm_start_dfsdm(adc->dfsdm);
1115         if (ret < 0)
1116                 return ret;
1117
1118         ret = regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1119                                  DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(1));
1120         if (ret < 0)
1121                 goto stop_dfsdm;
1122
1123         adc->nconv = 1;
1124         adc->smask = BIT(chan->scan_index);
1125         ret = stm32_dfsdm_start_conv(adc, NULL);
1126         if (ret < 0) {
1127                 regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1128                                    DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(0));
1129                 goto stop_dfsdm;
1130         }
1131
1132         timeout = wait_for_completion_interruptible_timeout(&adc->completion,
1133                                                             DFSDM_TIMEOUT);
1134
1135         /* Mask IRQ for regular conversion achievement*/
1136         regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1137                            DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(0));
1138
1139         if (timeout == 0)
1140                 ret = -ETIMEDOUT;
1141         else if (timeout < 0)
1142                 ret = timeout;
1143         else
1144                 ret = IIO_VAL_INT;
1145
1146         stm32_dfsdm_stop_conv(adc);
1147
1148 stop_dfsdm:
1149         stm32_dfsdm_stop_dfsdm(adc->dfsdm);
1150
1151         return ret;
1152 }
1153
1154 static int stm32_dfsdm_write_raw(struct iio_dev *indio_dev,
1155                                  struct iio_chan_spec const *chan,
1156                                  int val, int val2, long mask)
1157 {
1158         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1159         struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[adc->fl_id];
1160         struct stm32_dfsdm_channel *ch = &adc->dfsdm->ch_list[chan->channel];
1161         unsigned int spi_freq;
1162         int ret = -EINVAL;
1163
1164         switch (mask) {
1165         case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1166                 ret = iio_device_claim_direct_mode(indio_dev);
1167                 if (ret)
1168                         return ret;
1169                 ret = stm32_dfsdm_compute_osrs(fl, 0, val);
1170                 if (!ret)
1171                         adc->oversamp = val;
1172                 iio_device_release_direct_mode(indio_dev);
1173                 return ret;
1174
1175         case IIO_CHAN_INFO_SAMP_FREQ:
1176                 if (!val)
1177                         return -EINVAL;
1178
1179                 ret = iio_device_claim_direct_mode(indio_dev);
1180                 if (ret)
1181                         return ret;
1182
1183                 switch (ch->src) {
1184                 case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL:
1185                         spi_freq = adc->dfsdm->spi_master_freq;
1186                         break;
1187                 case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_FALLING:
1188                 case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_RISING:
1189                         spi_freq = adc->dfsdm->spi_master_freq / 2;
1190                         break;
1191                 default:
1192                         spi_freq = adc->spi_freq;
1193                 }
1194
1195                 ret = dfsdm_adc_set_samp_freq(indio_dev, val, spi_freq);
1196                 iio_device_release_direct_mode(indio_dev);
1197                 return ret;
1198         }
1199
1200         return -EINVAL;
1201 }
1202
1203 static int stm32_dfsdm_read_raw(struct iio_dev *indio_dev,
1204                                 struct iio_chan_spec const *chan, int *val,
1205                                 int *val2, long mask)
1206 {
1207         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1208         int ret;
1209
1210         switch (mask) {
1211         case IIO_CHAN_INFO_RAW:
1212                 ret = iio_device_claim_direct_mode(indio_dev);
1213                 if (ret)
1214                         return ret;
1215                 ret = iio_hw_consumer_enable(adc->hwc);
1216                 if (ret < 0) {
1217                         dev_err(&indio_dev->dev,
1218                                 "%s: IIO enable failed (channel %d)\n",
1219                                 __func__, chan->channel);
1220                         iio_device_release_direct_mode(indio_dev);
1221                         return ret;
1222                 }
1223                 ret = stm32_dfsdm_single_conv(indio_dev, chan, val);
1224                 iio_hw_consumer_disable(adc->hwc);
1225                 if (ret < 0) {
1226                         dev_err(&indio_dev->dev,
1227                                 "%s: Conversion failed (channel %d)\n",
1228                                 __func__, chan->channel);
1229                         iio_device_release_direct_mode(indio_dev);
1230                         return ret;
1231                 }
1232                 iio_device_release_direct_mode(indio_dev);
1233                 return IIO_VAL_INT;
1234
1235         case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1236                 *val = adc->oversamp;
1237
1238                 return IIO_VAL_INT;
1239
1240         case IIO_CHAN_INFO_SAMP_FREQ:
1241                 *val = adc->sample_freq;
1242
1243                 return IIO_VAL_INT;
1244         }
1245
1246         return -EINVAL;
1247 }
1248
1249 static int stm32_dfsdm_validate_trigger(struct iio_dev *indio_dev,
1250                                         struct iio_trigger *trig)
1251 {
1252         return stm32_dfsdm_get_jextsel(indio_dev, trig) < 0 ? -EINVAL : 0;
1253 }
1254
1255 static const struct iio_info stm32_dfsdm_info_audio = {
1256         .hwfifo_set_watermark = stm32_dfsdm_set_watermark,
1257         .read_raw = stm32_dfsdm_read_raw,
1258         .write_raw = stm32_dfsdm_write_raw,
1259         .update_scan_mode = stm32_dfsdm_update_scan_mode,
1260 };
1261
1262 static const struct iio_info stm32_dfsdm_info_adc = {
1263         .hwfifo_set_watermark = stm32_dfsdm_set_watermark,
1264         .read_raw = stm32_dfsdm_read_raw,
1265         .write_raw = stm32_dfsdm_write_raw,
1266         .update_scan_mode = stm32_dfsdm_update_scan_mode,
1267         .validate_trigger = stm32_dfsdm_validate_trigger,
1268 };
1269
1270 static irqreturn_t stm32_dfsdm_irq(int irq, void *arg)
1271 {
1272         struct stm32_dfsdm_adc *adc = arg;
1273         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1274         struct regmap *regmap = adc->dfsdm->regmap;
1275         unsigned int status, int_en;
1276
1277         regmap_read(regmap, DFSDM_ISR(adc->fl_id), &status);
1278         regmap_read(regmap, DFSDM_CR2(adc->fl_id), &int_en);
1279
1280         if (status & DFSDM_ISR_REOCF_MASK) {
1281                 /* Read the data register clean the IRQ status */
1282                 regmap_read(regmap, DFSDM_RDATAR(adc->fl_id), adc->buffer);
1283                 complete(&adc->completion);
1284         }
1285
1286         if (status & DFSDM_ISR_ROVRF_MASK) {
1287                 if (int_en & DFSDM_CR2_ROVRIE_MASK)
1288                         dev_warn(&indio_dev->dev, "Overrun detected\n");
1289                 regmap_update_bits(regmap, DFSDM_ICR(adc->fl_id),
1290                                    DFSDM_ICR_CLRROVRF_MASK,
1291                                    DFSDM_ICR_CLRROVRF_MASK);
1292         }
1293
1294         return IRQ_HANDLED;
1295 }
1296
1297 /*
1298  * Define external info for SPI Frequency and audio sampling rate that can be
1299  * configured by ASoC driver through consumer.h API
1300  */
1301 static const struct iio_chan_spec_ext_info dfsdm_adc_audio_ext_info[] = {
1302         /* spi_clk_freq : clock freq on SPI/manchester bus used by channel */
1303         {
1304                 .name = "spi_clk_freq",
1305                 .shared = IIO_SHARED_BY_TYPE,
1306                 .read = dfsdm_adc_audio_get_spiclk,
1307                 .write = dfsdm_adc_audio_set_spiclk,
1308         },
1309         {},
1310 };
1311
1312 static void stm32_dfsdm_dma_release(struct iio_dev *indio_dev)
1313 {
1314         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1315
1316         if (adc->dma_chan) {
1317                 dma_free_coherent(adc->dma_chan->device->dev,
1318                                   DFSDM_DMA_BUFFER_SIZE,
1319                                   adc->rx_buf, adc->dma_buf);
1320                 dma_release_channel(adc->dma_chan);
1321         }
1322 }
1323
1324 static int stm32_dfsdm_dma_request(struct iio_dev *indio_dev)
1325 {
1326         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1327
1328         adc->dma_chan = dma_request_slave_channel(&indio_dev->dev, "rx");
1329         if (!adc->dma_chan)
1330                 return -EINVAL;
1331
1332         adc->rx_buf = dma_alloc_coherent(adc->dma_chan->device->dev,
1333                                          DFSDM_DMA_BUFFER_SIZE,
1334                                          &adc->dma_buf, GFP_KERNEL);
1335         if (!adc->rx_buf) {
1336                 dma_release_channel(adc->dma_chan);
1337                 return -ENOMEM;
1338         }
1339
1340         indio_dev->modes |= INDIO_BUFFER_SOFTWARE;
1341         indio_dev->setup_ops = &stm32_dfsdm_buffer_setup_ops;
1342
1343         return 0;
1344 }
1345
1346 static int stm32_dfsdm_adc_chan_init_one(struct iio_dev *indio_dev,
1347                                          struct iio_chan_spec *ch)
1348 {
1349         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1350         int ret;
1351
1352         ret = stm32_dfsdm_channel_parse_of(adc->dfsdm, indio_dev, ch);
1353         if (ret < 0)
1354                 return ret;
1355
1356         ch->type = IIO_VOLTAGE;
1357         ch->indexed = 1;
1358
1359         /*
1360          * IIO_CHAN_INFO_RAW: used to compute regular conversion
1361          * IIO_CHAN_INFO_OVERSAMPLING_RATIO: used to set oversampling
1362          */
1363         ch->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
1364         ch->info_mask_shared_by_all = BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |
1365                                         BIT(IIO_CHAN_INFO_SAMP_FREQ);
1366
1367         if (adc->dev_data->type == DFSDM_AUDIO) {
1368                 ch->ext_info = dfsdm_adc_audio_ext_info;
1369         } else {
1370                 ch->scan_type.shift = 8;
1371         }
1372         ch->scan_type.sign = 's';
1373         ch->scan_type.realbits = 24;
1374         ch->scan_type.storagebits = 32;
1375
1376         return stm32_dfsdm_chan_configure(adc->dfsdm,
1377                                           &adc->dfsdm->ch_list[ch->channel]);
1378 }
1379
1380 static int stm32_dfsdm_audio_init(struct iio_dev *indio_dev)
1381 {
1382         struct iio_chan_spec *ch;
1383         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1384         struct stm32_dfsdm_channel *d_ch;
1385         int ret;
1386
1387         ch = devm_kzalloc(&indio_dev->dev, sizeof(*ch), GFP_KERNEL);
1388         if (!ch)
1389                 return -ENOMEM;
1390
1391         ch->scan_index = 0;
1392
1393         ret = stm32_dfsdm_adc_chan_init_one(indio_dev, ch);
1394         if (ret < 0) {
1395                 dev_err(&indio_dev->dev, "Channels init failed\n");
1396                 return ret;
1397         }
1398         ch->info_mask_separate = BIT(IIO_CHAN_INFO_SAMP_FREQ);
1399
1400         d_ch = &adc->dfsdm->ch_list[ch->channel];
1401         if (d_ch->src != DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL)
1402                 adc->spi_freq = adc->dfsdm->spi_master_freq;
1403
1404         indio_dev->num_channels = 1;
1405         indio_dev->channels = ch;
1406
1407         return stm32_dfsdm_dma_request(indio_dev);
1408 }
1409
1410 static int stm32_dfsdm_adc_init(struct iio_dev *indio_dev)
1411 {
1412         struct iio_chan_spec *ch;
1413         struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1414         int num_ch;
1415         int ret, chan_idx;
1416
1417         adc->oversamp = DFSDM_DEFAULT_OVERSAMPLING;
1418         ret = stm32_dfsdm_compute_osrs(&adc->dfsdm->fl_list[adc->fl_id], 0,
1419                                        adc->oversamp);
1420         if (ret < 0)
1421                 return ret;
1422
1423         num_ch = of_property_count_u32_elems(indio_dev->dev.of_node,
1424                                              "st,adc-channels");
1425         if (num_ch < 0 || num_ch > adc->dfsdm->num_chs) {
1426                 dev_err(&indio_dev->dev, "Bad st,adc-channels\n");
1427                 return num_ch < 0 ? num_ch : -EINVAL;
1428         }
1429
1430         /* Bind to SD modulator IIO device */
1431         adc->hwc = devm_iio_hw_consumer_alloc(&indio_dev->dev);
1432         if (IS_ERR(adc->hwc))
1433                 return -EPROBE_DEFER;
1434
1435         ch = devm_kcalloc(&indio_dev->dev, num_ch, sizeof(*ch),
1436                           GFP_KERNEL);
1437         if (!ch)
1438                 return -ENOMEM;
1439
1440         for (chan_idx = 0; chan_idx < num_ch; chan_idx++) {
1441                 ch[chan_idx].scan_index = chan_idx;
1442                 ret = stm32_dfsdm_adc_chan_init_one(indio_dev, &ch[chan_idx]);
1443                 if (ret < 0) {
1444                         dev_err(&indio_dev->dev, "Channels init failed\n");
1445                         return ret;
1446                 }
1447         }
1448
1449         indio_dev->num_channels = num_ch;
1450         indio_dev->channels = ch;
1451
1452         init_completion(&adc->completion);
1453
1454         /* Optionally request DMA */
1455         if (stm32_dfsdm_dma_request(indio_dev)) {
1456                 dev_dbg(&indio_dev->dev, "No DMA support\n");
1457                 return 0;
1458         }
1459
1460         ret = iio_triggered_buffer_setup(indio_dev,
1461                                          &iio_pollfunc_store_time,
1462                                          &stm32_dfsdm_adc_trigger_handler,
1463                                          &stm32_dfsdm_buffer_setup_ops);
1464         if (ret) {
1465                 stm32_dfsdm_dma_release(indio_dev);
1466                 dev_err(&indio_dev->dev, "buffer setup failed\n");
1467                 return ret;
1468         }
1469
1470         /* lptimer/timer hardware triggers */
1471         indio_dev->modes |= INDIO_HARDWARE_TRIGGERED;
1472
1473         return 0;
1474 }
1475
1476 static const struct stm32_dfsdm_dev_data stm32h7_dfsdm_adc_data = {
1477         .type = DFSDM_IIO,
1478         .init = stm32_dfsdm_adc_init,
1479 };
1480
1481 static const struct stm32_dfsdm_dev_data stm32h7_dfsdm_audio_data = {
1482         .type = DFSDM_AUDIO,
1483         .init = stm32_dfsdm_audio_init,
1484 };
1485
1486 static const struct of_device_id stm32_dfsdm_adc_match[] = {
1487         {
1488                 .compatible = "st,stm32-dfsdm-adc",
1489                 .data = &stm32h7_dfsdm_adc_data,
1490         },
1491         {
1492                 .compatible = "st,stm32-dfsdm-dmic",
1493                 .data = &stm32h7_dfsdm_audio_data,
1494         },
1495         {}
1496 };
1497
1498 static int stm32_dfsdm_adc_probe(struct platform_device *pdev)
1499 {
1500         struct device *dev = &pdev->dev;
1501         struct stm32_dfsdm_adc *adc;
1502         struct device_node *np = dev->of_node;
1503         const struct stm32_dfsdm_dev_data *dev_data;
1504         struct iio_dev *iio;
1505         char *name;
1506         int ret, irq, val;
1507
1508         dev_data = of_device_get_match_data(dev);
1509         iio = devm_iio_device_alloc(dev, sizeof(*adc));
1510         if (!iio) {
1511                 dev_err(dev, "%s: Failed to allocate IIO\n", __func__);
1512                 return -ENOMEM;
1513         }
1514
1515         adc = iio_priv(iio);
1516         adc->dfsdm = dev_get_drvdata(dev->parent);
1517
1518         iio->dev.parent = dev;
1519         iio->dev.of_node = np;
1520         iio->modes = INDIO_DIRECT_MODE;
1521
1522         platform_set_drvdata(pdev, adc);
1523
1524         ret = of_property_read_u32(dev->of_node, "reg", &adc->fl_id);
1525         if (ret != 0 || adc->fl_id >= adc->dfsdm->num_fls) {
1526                 dev_err(dev, "Missing or bad reg property\n");
1527                 return -EINVAL;
1528         }
1529
1530         name = devm_kzalloc(dev, sizeof("dfsdm-adc0"), GFP_KERNEL);
1531         if (!name)
1532                 return -ENOMEM;
1533         if (dev_data->type == DFSDM_AUDIO) {
1534                 iio->info = &stm32_dfsdm_info_audio;
1535                 snprintf(name, sizeof("dfsdm-pdm0"), "dfsdm-pdm%d", adc->fl_id);
1536         } else {
1537                 iio->info = &stm32_dfsdm_info_adc;
1538                 snprintf(name, sizeof("dfsdm-adc0"), "dfsdm-adc%d", adc->fl_id);
1539         }
1540         iio->name = name;
1541
1542         /*
1543          * In a first step IRQs generated for channels are not treated.
1544          * So IRQ associated to filter instance 0 is dedicated to the Filter 0.
1545          */
1546         irq = platform_get_irq(pdev, 0);
1547         if (irq < 0) {
1548                 if (irq != -EPROBE_DEFER)
1549                         dev_err(dev, "Failed to get IRQ: %d\n", irq);
1550                 return irq;
1551         }
1552
1553         ret = devm_request_irq(dev, irq, stm32_dfsdm_irq,
1554                                0, pdev->name, adc);
1555         if (ret < 0) {
1556                 dev_err(dev, "Failed to request IRQ\n");
1557                 return ret;
1558         }
1559
1560         ret = of_property_read_u32(dev->of_node, "st,filter-order", &val);
1561         if (ret < 0) {
1562                 dev_err(dev, "Failed to set filter order\n");
1563                 return ret;
1564         }
1565
1566         adc->dfsdm->fl_list[adc->fl_id].ford = val;
1567
1568         ret = of_property_read_u32(dev->of_node, "st,filter0-sync", &val);
1569         if (!ret)
1570                 adc->dfsdm->fl_list[adc->fl_id].sync_mode = val;
1571
1572         adc->dev_data = dev_data;
1573         ret = dev_data->init(iio);
1574         if (ret < 0)
1575                 return ret;
1576
1577         ret = iio_device_register(iio);
1578         if (ret < 0)
1579                 goto err_cleanup;
1580
1581         if (dev_data->type == DFSDM_AUDIO) {
1582                 ret = of_platform_populate(np, NULL, NULL, dev);
1583                 if (ret < 0) {
1584                         dev_err(dev, "Failed to find an audio DAI\n");
1585                         goto err_unregister;
1586                 }
1587         }
1588
1589         return 0;
1590
1591 err_unregister:
1592         iio_device_unregister(iio);
1593 err_cleanup:
1594         stm32_dfsdm_dma_release(iio);
1595
1596         return ret;
1597 }
1598
1599 static int stm32_dfsdm_adc_remove(struct platform_device *pdev)
1600 {
1601         struct stm32_dfsdm_adc *adc = platform_get_drvdata(pdev);
1602         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1603
1604         if (adc->dev_data->type == DFSDM_AUDIO)
1605                 of_platform_depopulate(&pdev->dev);
1606         iio_device_unregister(indio_dev);
1607         stm32_dfsdm_dma_release(indio_dev);
1608
1609         return 0;
1610 }
1611
1612 static int __maybe_unused stm32_dfsdm_adc_suspend(struct device *dev)
1613 {
1614         struct stm32_dfsdm_adc *adc = dev_get_drvdata(dev);
1615         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1616
1617         if (iio_buffer_enabled(indio_dev))
1618                 __stm32_dfsdm_predisable(indio_dev);
1619
1620         return 0;
1621 }
1622
1623 static int __maybe_unused stm32_dfsdm_adc_resume(struct device *dev)
1624 {
1625         struct stm32_dfsdm_adc *adc = dev_get_drvdata(dev);
1626         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1627         const struct iio_chan_spec *chan;
1628         struct stm32_dfsdm_channel *ch;
1629         int i, ret;
1630
1631         /* restore channels configuration */
1632         for (i = 0; i < indio_dev->num_channels; i++) {
1633                 chan = indio_dev->channels + i;
1634                 ch = &adc->dfsdm->ch_list[chan->channel];
1635                 ret = stm32_dfsdm_chan_configure(adc->dfsdm, ch);
1636                 if (ret)
1637                         return ret;
1638         }
1639
1640         if (iio_buffer_enabled(indio_dev))
1641                 __stm32_dfsdm_postenable(indio_dev);
1642
1643         return 0;
1644 }
1645
1646 static SIMPLE_DEV_PM_OPS(stm32_dfsdm_adc_pm_ops,
1647                          stm32_dfsdm_adc_suspend, stm32_dfsdm_adc_resume);
1648
1649 static struct platform_driver stm32_dfsdm_adc_driver = {
1650         .driver = {
1651                 .name = "stm32-dfsdm-adc",
1652                 .of_match_table = stm32_dfsdm_adc_match,
1653                 .pm = &stm32_dfsdm_adc_pm_ops,
1654         },
1655         .probe = stm32_dfsdm_adc_probe,
1656         .remove = stm32_dfsdm_adc_remove,
1657 };
1658 module_platform_driver(stm32_dfsdm_adc_driver);
1659
1660 MODULE_DESCRIPTION("STM32 sigma delta ADC");
1661 MODULE_AUTHOR("Arnaud Pouliquen <arnaud.pouliquen@st.com>");
1662 MODULE_LICENSE("GPL v2");