Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * This file is the ADC part of the STM32 DFSDM driver
0004  *
0005  * Copyright (C) 2017, STMicroelectronics - All Rights Reserved
0006  * Author: Arnaud Pouliquen <arnaud.pouliquen@st.com>.
0007  */
0008 
0009 #include <linux/dmaengine.h>
0010 #include <linux/dma-mapping.h>
0011 #include <linux/iio/adc/stm32-dfsdm-adc.h>
0012 #include <linux/iio/buffer.h>
0013 #include <linux/iio/hw-consumer.h>
0014 #include <linux/iio/sysfs.h>
0015 #include <linux/iio/timer/stm32-lptim-trigger.h>
0016 #include <linux/iio/timer/stm32-timer-trigger.h>
0017 #include <linux/iio/trigger.h>
0018 #include <linux/iio/trigger_consumer.h>
0019 #include <linux/iio/triggered_buffer.h>
0020 #include <linux/interrupt.h>
0021 #include <linux/module.h>
0022 #include <linux/of_device.h>
0023 #include <linux/platform_device.h>
0024 #include <linux/regmap.h>
0025 #include <linux/slab.h>
0026 
0027 #include "stm32-dfsdm.h"
0028 
0029 #define DFSDM_DMA_BUFFER_SIZE (4 * PAGE_SIZE)
0030 
0031 /* Conversion timeout */
0032 #define DFSDM_TIMEOUT_US 100000
0033 #define DFSDM_TIMEOUT (msecs_to_jiffies(DFSDM_TIMEOUT_US / 1000))
0034 
0035 /* Oversampling attribute default */
0036 #define DFSDM_DEFAULT_OVERSAMPLING  100
0037 
0038 /* Oversampling max values */
0039 #define DFSDM_MAX_INT_OVERSAMPLING 256
0040 #define DFSDM_MAX_FL_OVERSAMPLING 1024
0041 
0042 /* Limit filter output resolution to 31 bits. (i.e. sample range is +/-2^30) */
0043 #define DFSDM_DATA_MAX BIT(30)
0044 /*
0045  * Data are output as two's complement data in a 24 bit field.
0046  * Data from filters are in the range +/-2^(n-1)
0047  * 2^(n-1) maximum positive value cannot be coded in 2's complement n bits
0048  * An extra bit is required to avoid wrap-around of the binary code for 2^(n-1)
0049  * So, the resolution of samples from filter is actually limited to 23 bits
0050  */
0051 #define DFSDM_DATA_RES 24
0052 
0053 /* Filter configuration */
0054 #define DFSDM_CR1_CFG_MASK (DFSDM_CR1_RCH_MASK | DFSDM_CR1_RCONT_MASK | \
0055                 DFSDM_CR1_RSYNC_MASK | DFSDM_CR1_JSYNC_MASK | \
0056                 DFSDM_CR1_JSCAN_MASK)
0057 
0058 enum sd_converter_type {
0059     DFSDM_AUDIO,
0060     DFSDM_IIO,
0061 };
0062 
0063 struct stm32_dfsdm_dev_data {
0064     int type;
0065     int (*init)(struct device *dev, struct iio_dev *indio_dev);
0066     unsigned int num_channels;
0067     const struct regmap_config *regmap_cfg;
0068 };
0069 
0070 struct stm32_dfsdm_adc {
0071     struct stm32_dfsdm *dfsdm;
0072     const struct stm32_dfsdm_dev_data *dev_data;
0073     unsigned int fl_id;
0074     unsigned int nconv;
0075     unsigned long smask;
0076 
0077     /* ADC specific */
0078     unsigned int oversamp;
0079     struct iio_hw_consumer *hwc;
0080     struct completion completion;
0081     u32 *buffer;
0082 
0083     /* Audio specific */
0084     unsigned int spi_freq;  /* SPI bus clock frequency */
0085     unsigned int sample_freq; /* Sample frequency after filter decimation */
0086     int (*cb)(const void *data, size_t size, void *cb_priv);
0087     void *cb_priv;
0088 
0089     /* DMA */
0090     u8 *rx_buf;
0091     unsigned int bufi; /* Buffer current position */
0092     unsigned int buf_sz; /* Buffer size */
0093     struct dma_chan *dma_chan;
0094     dma_addr_t dma_buf;
0095 };
0096 
0097 struct stm32_dfsdm_str2field {
0098     const char  *name;
0099     unsigned int    val;
0100 };
0101 
0102 /* DFSDM channel serial interface type */
0103 static const struct stm32_dfsdm_str2field stm32_dfsdm_chan_type[] = {
0104     { "SPI_R", 0 }, /* SPI with data on rising edge */
0105     { "SPI_F", 1 }, /* SPI with data on falling edge */
0106     { "MANCH_R", 2 }, /* Manchester codec, rising edge = logic 0 */
0107     { "MANCH_F", 3 }, /* Manchester codec, falling edge = logic 1 */
0108     {},
0109 };
0110 
0111 /* DFSDM channel clock source */
0112 static const struct stm32_dfsdm_str2field stm32_dfsdm_chan_src[] = {
0113     /* External SPI clock (CLKIN x) */
0114     { "CLKIN", DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL },
0115     /* Internal SPI clock (CLKOUT) */
0116     { "CLKOUT", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL },
0117     /* Internal SPI clock divided by 2 (falling edge) */
0118     { "CLKOUT_F", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_FALLING },
0119     /* Internal SPI clock divided by 2 (falling edge) */
0120     { "CLKOUT_R", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_RISING },
0121     {},
0122 };
0123 
0124 static int stm32_dfsdm_str2val(const char *str,
0125                    const struct stm32_dfsdm_str2field *list)
0126 {
0127     const struct stm32_dfsdm_str2field *p = list;
0128 
0129     for (p = list; p && p->name; p++)
0130         if (!strcmp(p->name, str))
0131             return p->val;
0132 
0133     return -EINVAL;
0134 }
0135 
0136 /**
0137  * struct stm32_dfsdm_trig_info - DFSDM trigger info
0138  * @name:       name of the trigger, corresponding to its source
0139  * @jextsel:        trigger signal selection
0140  */
0141 struct stm32_dfsdm_trig_info {
0142     const char *name;
0143     unsigned int jextsel;
0144 };
0145 
0146 /* hardware injected trigger enable, edge selection */
0147 enum stm32_dfsdm_jexten {
0148     STM32_DFSDM_JEXTEN_DISABLED,
0149     STM32_DFSDM_JEXTEN_RISING_EDGE,
0150     STM32_DFSDM_JEXTEN_FALLING_EDGE,
0151     STM32_DFSDM_EXTEN_BOTH_EDGES,
0152 };
0153 
0154 static const struct stm32_dfsdm_trig_info stm32_dfsdm_trigs[] = {
0155     { TIM1_TRGO, 0 },
0156     { TIM1_TRGO2, 1 },
0157     { TIM8_TRGO, 2 },
0158     { TIM8_TRGO2, 3 },
0159     { TIM3_TRGO, 4 },
0160     { TIM4_TRGO, 5 },
0161     { TIM16_OC1, 6 },
0162     { TIM6_TRGO, 7 },
0163     { TIM7_TRGO, 8 },
0164     { LPTIM1_OUT, 26 },
0165     { LPTIM2_OUT, 27 },
0166     { LPTIM3_OUT, 28 },
0167     {},
0168 };
0169 
0170 static int stm32_dfsdm_get_jextsel(struct iio_dev *indio_dev,
0171                    struct iio_trigger *trig)
0172 {
0173     int i;
0174 
0175     /* lookup triggers registered by stm32 timer trigger driver */
0176     for (i = 0; stm32_dfsdm_trigs[i].name; i++) {
0177         /**
0178          * Checking both stm32 timer trigger type and trig name
0179          * should be safe against arbitrary trigger names.
0180          */
0181         if ((is_stm32_timer_trigger(trig) ||
0182              is_stm32_lptim_trigger(trig)) &&
0183             !strcmp(stm32_dfsdm_trigs[i].name, trig->name)) {
0184             return stm32_dfsdm_trigs[i].jextsel;
0185         }
0186     }
0187 
0188     return -EINVAL;
0189 }
0190 
0191 static int stm32_dfsdm_compute_osrs(struct stm32_dfsdm_filter *fl,
0192                     unsigned int fast, unsigned int oversamp)
0193 {
0194     unsigned int i, d, fosr, iosr;
0195     u64 res, max;
0196     int bits, shift;
0197     unsigned int m = 1; /* multiplication factor */
0198     unsigned int p = fl->ford;  /* filter order (ford) */
0199     struct stm32_dfsdm_filter_osr *flo = &fl->flo[fast];
0200 
0201     pr_debug("Requested oversampling: %d\n", oversamp);
0202     /*
0203      * This function tries to compute filter oversampling and integrator
0204      * oversampling, base on oversampling ratio requested by user.
0205      *
0206      * Decimation d depends on the filter order and the oversampling ratios.
0207      * ford: filter order
0208      * fosr: filter over sampling ratio
0209      * iosr: integrator over sampling ratio
0210      */
0211     if (fl->ford == DFSDM_FASTSINC_ORDER) {
0212         m = 2;
0213         p = 2;
0214     }
0215 
0216     /*
0217      * Look for filter and integrator oversampling ratios which allows
0218      * to maximize data output resolution.
0219      */
0220     for (fosr = 1; fosr <= DFSDM_MAX_FL_OVERSAMPLING; fosr++) {
0221         for (iosr = 1; iosr <= DFSDM_MAX_INT_OVERSAMPLING; iosr++) {
0222             if (fast)
0223                 d = fosr * iosr;
0224             else if (fl->ford == DFSDM_FASTSINC_ORDER)
0225                 d = fosr * (iosr + 3) + 2;
0226             else
0227                 d = fosr * (iosr - 1 + p) + p;
0228 
0229             if (d > oversamp)
0230                 break;
0231             else if (d != oversamp)
0232                 continue;
0233             /*
0234              * Check resolution (limited to signed 32 bits)
0235              *   res <= 2^31
0236              * Sincx filters:
0237              *   res = m * fosr^p x iosr (with m=1, p=ford)
0238              * FastSinc filter
0239              *   res = m * fosr^p x iosr (with m=2, p=2)
0240              */
0241             res = fosr;
0242             for (i = p - 1; i > 0; i--) {
0243                 res = res * (u64)fosr;
0244                 if (res > DFSDM_DATA_MAX)
0245                     break;
0246             }
0247             if (res > DFSDM_DATA_MAX)
0248                 continue;
0249 
0250             res = res * (u64)m * (u64)iosr;
0251             if (res > DFSDM_DATA_MAX)
0252                 continue;
0253 
0254             if (res >= flo->res) {
0255                 flo->res = res;
0256                 flo->fosr = fosr;
0257                 flo->iosr = iosr;
0258 
0259                 bits = fls(flo->res);
0260                 /* 8 LBSs in data register contain chan info */
0261                 max = flo->res << 8;
0262 
0263                 /* if resolution is not a power of two */
0264                 if (flo->res > BIT(bits - 1))
0265                     bits++;
0266                 else
0267                     max--;
0268 
0269                 shift = DFSDM_DATA_RES - bits;
0270                 /*
0271                  * Compute right/left shift
0272                  * Right shift is performed by hardware
0273                  * when transferring samples to data register.
0274                  * Left shift is done by software on buffer
0275                  */
0276                 if (shift > 0) {
0277                     /* Resolution is lower than 24 bits */
0278                     flo->rshift = 0;
0279                     flo->lshift = shift;
0280                 } else {
0281                     /*
0282                      * If resolution is 24 bits or more,
0283                      * max positive value may be ambiguous
0284                      * (equal to max negative value as sign
0285                      * bit is dropped).
0286                      * Reduce resolution to 23 bits (rshift)
0287                      * to keep the sign on bit 23 and treat
0288                      * saturation before rescaling on 24
0289                      * bits (lshift).
0290                      */
0291                     flo->rshift = 1 - shift;
0292                     flo->lshift = 1;
0293                     max >>= flo->rshift;
0294                 }
0295                 flo->max = (s32)max;
0296                 flo->bits = bits;
0297 
0298                 pr_debug("fast %d, fosr %d, iosr %d, res 0x%llx/%d bits, rshift %d, lshift %d\n",
0299                      fast, flo->fosr, flo->iosr,
0300                      flo->res, bits, flo->rshift,
0301                      flo->lshift);
0302             }
0303         }
0304     }
0305 
0306     if (!flo->res)
0307         return -EINVAL;
0308 
0309     return 0;
0310 }
0311 
0312 static int stm32_dfsdm_compute_all_osrs(struct iio_dev *indio_dev,
0313                     unsigned int oversamp)
0314 {
0315     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0316     struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[adc->fl_id];
0317     int ret0, ret1;
0318 
0319     memset(&fl->flo[0], 0, sizeof(fl->flo[0]));
0320     memset(&fl->flo[1], 0, sizeof(fl->flo[1]));
0321 
0322     ret0 = stm32_dfsdm_compute_osrs(fl, 0, oversamp);
0323     ret1 = stm32_dfsdm_compute_osrs(fl, 1, oversamp);
0324     if (ret0 < 0 && ret1 < 0) {
0325         dev_err(&indio_dev->dev,
0326             "Filter parameters not found: errors %d/%d\n",
0327             ret0, ret1);
0328         return -EINVAL;
0329     }
0330 
0331     return 0;
0332 }
0333 
0334 static int stm32_dfsdm_start_channel(struct iio_dev *indio_dev)
0335 {
0336     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0337     struct regmap *regmap = adc->dfsdm->regmap;
0338     const struct iio_chan_spec *chan;
0339     unsigned int bit;
0340     int ret;
0341 
0342     for_each_set_bit(bit, &adc->smask, sizeof(adc->smask) * BITS_PER_BYTE) {
0343         chan = indio_dev->channels + bit;
0344         ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(chan->channel),
0345                      DFSDM_CHCFGR1_CHEN_MASK,
0346                      DFSDM_CHCFGR1_CHEN(1));
0347         if (ret < 0)
0348             return ret;
0349     }
0350 
0351     return 0;
0352 }
0353 
0354 static void stm32_dfsdm_stop_channel(struct iio_dev *indio_dev)
0355 {
0356     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0357     struct regmap *regmap = adc->dfsdm->regmap;
0358     const struct iio_chan_spec *chan;
0359     unsigned int bit;
0360 
0361     for_each_set_bit(bit, &adc->smask, sizeof(adc->smask) * BITS_PER_BYTE) {
0362         chan = indio_dev->channels + bit;
0363         regmap_update_bits(regmap, DFSDM_CHCFGR1(chan->channel),
0364                    DFSDM_CHCFGR1_CHEN_MASK,
0365                    DFSDM_CHCFGR1_CHEN(0));
0366     }
0367 }
0368 
0369 static int stm32_dfsdm_chan_configure(struct stm32_dfsdm *dfsdm,
0370                       struct stm32_dfsdm_channel *ch)
0371 {
0372     unsigned int id = ch->id;
0373     struct regmap *regmap = dfsdm->regmap;
0374     int ret;
0375 
0376     ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
0377                  DFSDM_CHCFGR1_SITP_MASK,
0378                  DFSDM_CHCFGR1_SITP(ch->type));
0379     if (ret < 0)
0380         return ret;
0381     ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
0382                  DFSDM_CHCFGR1_SPICKSEL_MASK,
0383                  DFSDM_CHCFGR1_SPICKSEL(ch->src));
0384     if (ret < 0)
0385         return ret;
0386     return regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
0387                   DFSDM_CHCFGR1_CHINSEL_MASK,
0388                   DFSDM_CHCFGR1_CHINSEL(ch->alt_si));
0389 }
0390 
0391 static int stm32_dfsdm_start_filter(struct stm32_dfsdm_adc *adc,
0392                     unsigned int fl_id,
0393                     struct iio_trigger *trig)
0394 {
0395     struct stm32_dfsdm *dfsdm = adc->dfsdm;
0396     int ret;
0397 
0398     /* Enable filter */
0399     ret = regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
0400                  DFSDM_CR1_DFEN_MASK, DFSDM_CR1_DFEN(1));
0401     if (ret < 0)
0402         return ret;
0403 
0404     /* Nothing more to do for injected (scan mode/triggered) conversions */
0405     if (adc->nconv > 1 || trig)
0406         return 0;
0407 
0408     /* Software start (single or continuous) regular conversion */
0409     return regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
0410                   DFSDM_CR1_RSWSTART_MASK,
0411                   DFSDM_CR1_RSWSTART(1));
0412 }
0413 
0414 static void stm32_dfsdm_stop_filter(struct stm32_dfsdm *dfsdm,
0415                     unsigned int fl_id)
0416 {
0417     /* Disable conversion */
0418     regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
0419                DFSDM_CR1_DFEN_MASK, DFSDM_CR1_DFEN(0));
0420 }
0421 
0422 static int stm32_dfsdm_filter_set_trig(struct iio_dev *indio_dev,
0423                        unsigned int fl_id,
0424                        struct iio_trigger *trig)
0425 {
0426     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0427     struct regmap *regmap = adc->dfsdm->regmap;
0428     u32 jextsel = 0, jexten = STM32_DFSDM_JEXTEN_DISABLED;
0429     int ret;
0430 
0431     if (trig) {
0432         ret = stm32_dfsdm_get_jextsel(indio_dev, trig);
0433         if (ret < 0)
0434             return ret;
0435 
0436         /* set trigger source and polarity (default to rising edge) */
0437         jextsel = ret;
0438         jexten = STM32_DFSDM_JEXTEN_RISING_EDGE;
0439     }
0440 
0441     ret = regmap_update_bits(regmap, DFSDM_CR1(fl_id),
0442                  DFSDM_CR1_JEXTSEL_MASK | DFSDM_CR1_JEXTEN_MASK,
0443                  DFSDM_CR1_JEXTSEL(jextsel) |
0444                  DFSDM_CR1_JEXTEN(jexten));
0445     if (ret < 0)
0446         return ret;
0447 
0448     return 0;
0449 }
0450 
0451 static int stm32_dfsdm_channels_configure(struct iio_dev *indio_dev,
0452                       unsigned int fl_id,
0453                       struct iio_trigger *trig)
0454 {
0455     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0456     struct regmap *regmap = adc->dfsdm->regmap;
0457     struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[fl_id];
0458     struct stm32_dfsdm_filter_osr *flo = &fl->flo[0];
0459     const struct iio_chan_spec *chan;
0460     unsigned int bit;
0461     int ret;
0462 
0463     fl->fast = 0;
0464 
0465     /*
0466      * In continuous mode, use fast mode configuration,
0467      * if it provides a better resolution.
0468      */
0469     if (adc->nconv == 1 && !trig && iio_buffer_enabled(indio_dev)) {
0470         if (fl->flo[1].res >= fl->flo[0].res) {
0471             fl->fast = 1;
0472             flo = &fl->flo[1];
0473         }
0474     }
0475 
0476     if (!flo->res)
0477         return -EINVAL;
0478 
0479     dev_dbg(&indio_dev->dev, "Samples actual resolution: %d bits",
0480         min(flo->bits, (u32)DFSDM_DATA_RES - 1));
0481 
0482     for_each_set_bit(bit, &adc->smask,
0483              sizeof(adc->smask) * BITS_PER_BYTE) {
0484         chan = indio_dev->channels + bit;
0485 
0486         ret = regmap_update_bits(regmap,
0487                      DFSDM_CHCFGR2(chan->channel),
0488                      DFSDM_CHCFGR2_DTRBS_MASK,
0489                      DFSDM_CHCFGR2_DTRBS(flo->rshift));
0490         if (ret)
0491             return ret;
0492     }
0493 
0494     return 0;
0495 }
0496 
0497 static int stm32_dfsdm_filter_configure(struct iio_dev *indio_dev,
0498                     unsigned int fl_id,
0499                     struct iio_trigger *trig)
0500 {
0501     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0502     struct regmap *regmap = adc->dfsdm->regmap;
0503     struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[fl_id];
0504     struct stm32_dfsdm_filter_osr *flo = &fl->flo[fl->fast];
0505     u32 cr1;
0506     const struct iio_chan_spec *chan;
0507     unsigned int bit, jchg = 0;
0508     int ret;
0509 
0510     /* Average integrator oversampling */
0511     ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_IOSR_MASK,
0512                  DFSDM_FCR_IOSR(flo->iosr - 1));
0513     if (ret)
0514         return ret;
0515 
0516     /* Filter order and Oversampling */
0517     ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_FOSR_MASK,
0518                  DFSDM_FCR_FOSR(flo->fosr - 1));
0519     if (ret)
0520         return ret;
0521 
0522     ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_FORD_MASK,
0523                  DFSDM_FCR_FORD(fl->ford));
0524     if (ret)
0525         return ret;
0526 
0527     ret = stm32_dfsdm_filter_set_trig(indio_dev, fl_id, trig);
0528     if (ret)
0529         return ret;
0530 
0531     ret = regmap_update_bits(regmap, DFSDM_CR1(fl_id),
0532                  DFSDM_CR1_FAST_MASK,
0533                  DFSDM_CR1_FAST(fl->fast));
0534     if (ret)
0535         return ret;
0536 
0537     /*
0538      * DFSDM modes configuration W.R.T audio/iio type modes
0539      * ----------------------------------------------------------------
0540      * Modes         | regular |  regular     | injected | injected   |
0541      *               |         |  continuous  |          | + scan     |
0542      * --------------|---------|--------------|----------|------------|
0543      * single conv   |    x    |              |          |            |
0544      * (1 chan)      |         |              |          |            |
0545      * --------------|---------|--------------|----------|------------|
0546      * 1 Audio chan  |         | sample freq  |          |            |
0547      *               |         | or sync_mode |          |            |
0548      * --------------|---------|--------------|----------|------------|
0549      * 1 IIO chan    |         | sample freq  | trigger  |            |
0550      *               |         | or sync_mode |          |            |
0551      * --------------|---------|--------------|----------|------------|
0552      * 2+ IIO chans  |         |              |          | trigger or |
0553      *               |         |              |          | sync_mode  |
0554      * ----------------------------------------------------------------
0555      */
0556     if (adc->nconv == 1 && !trig) {
0557         bit = __ffs(adc->smask);
0558         chan = indio_dev->channels + bit;
0559 
0560         /* Use regular conversion for single channel without trigger */
0561         cr1 = DFSDM_CR1_RCH(chan->channel);
0562 
0563         /* Continuous conversions triggered by SPI clk in buffer mode */
0564         if (iio_buffer_enabled(indio_dev))
0565             cr1 |= DFSDM_CR1_RCONT(1);
0566 
0567         cr1 |= DFSDM_CR1_RSYNC(fl->sync_mode);
0568     } else {
0569         /* Use injected conversion for multiple channels */
0570         for_each_set_bit(bit, &adc->smask,
0571                  sizeof(adc->smask) * BITS_PER_BYTE) {
0572             chan = indio_dev->channels + bit;
0573             jchg |= BIT(chan->channel);
0574         }
0575         ret = regmap_write(regmap, DFSDM_JCHGR(fl_id), jchg);
0576         if (ret < 0)
0577             return ret;
0578 
0579         /* Use scan mode for multiple channels */
0580         cr1 = DFSDM_CR1_JSCAN((adc->nconv > 1) ? 1 : 0);
0581 
0582         /*
0583          * Continuous conversions not supported in injected mode,
0584          * either use:
0585          * - conversions in sync with filter 0
0586          * - triggered conversions
0587          */
0588         if (!fl->sync_mode && !trig)
0589             return -EINVAL;
0590         cr1 |= DFSDM_CR1_JSYNC(fl->sync_mode);
0591     }
0592 
0593     return regmap_update_bits(regmap, DFSDM_CR1(fl_id), DFSDM_CR1_CFG_MASK,
0594                   cr1);
0595 }
0596 
0597 static int stm32_dfsdm_channel_parse_of(struct stm32_dfsdm *dfsdm,
0598                     struct iio_dev *indio_dev,
0599                     struct iio_chan_spec *ch)
0600 {
0601     struct stm32_dfsdm_channel *df_ch;
0602     const char *of_str;
0603     int chan_idx = ch->scan_index;
0604     int ret, val;
0605 
0606     ret = of_property_read_u32_index(indio_dev->dev.of_node,
0607                      "st,adc-channels", chan_idx,
0608                      &ch->channel);
0609     if (ret < 0) {
0610         dev_err(&indio_dev->dev,
0611             " Error parsing 'st,adc-channels' for idx %d\n",
0612             chan_idx);
0613         return ret;
0614     }
0615     if (ch->channel >= dfsdm->num_chs) {
0616         dev_err(&indio_dev->dev,
0617             " Error bad channel number %d (max = %d)\n",
0618             ch->channel, dfsdm->num_chs);
0619         return -EINVAL;
0620     }
0621 
0622     ret = of_property_read_string_index(indio_dev->dev.of_node,
0623                         "st,adc-channel-names", chan_idx,
0624                         &ch->datasheet_name);
0625     if (ret < 0) {
0626         dev_err(&indio_dev->dev,
0627             " Error parsing 'st,adc-channel-names' for idx %d\n",
0628             chan_idx);
0629         return ret;
0630     }
0631 
0632     df_ch =  &dfsdm->ch_list[ch->channel];
0633     df_ch->id = ch->channel;
0634 
0635     ret = of_property_read_string_index(indio_dev->dev.of_node,
0636                         "st,adc-channel-types", chan_idx,
0637                         &of_str);
0638     if (!ret) {
0639         val = stm32_dfsdm_str2val(of_str, stm32_dfsdm_chan_type);
0640         if (val < 0)
0641             return val;
0642     } else {
0643         val = 0;
0644     }
0645     df_ch->type = val;
0646 
0647     ret = of_property_read_string_index(indio_dev->dev.of_node,
0648                         "st,adc-channel-clk-src", chan_idx,
0649                         &of_str);
0650     if (!ret) {
0651         val = stm32_dfsdm_str2val(of_str, stm32_dfsdm_chan_src);
0652         if (val < 0)
0653             return val;
0654     } else {
0655         val = 0;
0656     }
0657     df_ch->src = val;
0658 
0659     ret = of_property_read_u32_index(indio_dev->dev.of_node,
0660                      "st,adc-alt-channel", chan_idx,
0661                      &df_ch->alt_si);
0662     if (ret < 0)
0663         df_ch->alt_si = 0;
0664 
0665     return 0;
0666 }
0667 
0668 static ssize_t dfsdm_adc_audio_get_spiclk(struct iio_dev *indio_dev,
0669                       uintptr_t priv,
0670                       const struct iio_chan_spec *chan,
0671                       char *buf)
0672 {
0673     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0674 
0675     return snprintf(buf, PAGE_SIZE, "%d\n", adc->spi_freq);
0676 }
0677 
0678 static int dfsdm_adc_set_samp_freq(struct iio_dev *indio_dev,
0679                    unsigned int sample_freq,
0680                    unsigned int spi_freq)
0681 {
0682     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0683     unsigned int oversamp;
0684     int ret;
0685 
0686     oversamp = DIV_ROUND_CLOSEST(spi_freq, sample_freq);
0687     if (spi_freq % sample_freq)
0688         dev_dbg(&indio_dev->dev,
0689             "Rate not accurate. requested (%u), actual (%u)\n",
0690             sample_freq, spi_freq / oversamp);
0691 
0692     ret = stm32_dfsdm_compute_all_osrs(indio_dev, oversamp);
0693     if (ret < 0)
0694         return ret;
0695 
0696     adc->sample_freq = spi_freq / oversamp;
0697     adc->oversamp = oversamp;
0698 
0699     return 0;
0700 }
0701 
0702 static ssize_t dfsdm_adc_audio_set_spiclk(struct iio_dev *indio_dev,
0703                       uintptr_t priv,
0704                       const struct iio_chan_spec *chan,
0705                       const char *buf, size_t len)
0706 {
0707     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0708     struct stm32_dfsdm_channel *ch = &adc->dfsdm->ch_list[chan->channel];
0709     unsigned int sample_freq = adc->sample_freq;
0710     unsigned int spi_freq;
0711     int ret;
0712 
0713     dev_err(&indio_dev->dev, "enter %s\n", __func__);
0714     /* If DFSDM is master on SPI, SPI freq can not be updated */
0715     if (ch->src != DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL)
0716         return -EPERM;
0717 
0718     ret = kstrtoint(buf, 0, &spi_freq);
0719     if (ret)
0720         return ret;
0721 
0722     if (!spi_freq)
0723         return -EINVAL;
0724 
0725     if (sample_freq) {
0726         ret = dfsdm_adc_set_samp_freq(indio_dev, sample_freq, spi_freq);
0727         if (ret < 0)
0728             return ret;
0729     }
0730     adc->spi_freq = spi_freq;
0731 
0732     return len;
0733 }
0734 
0735 static int stm32_dfsdm_start_conv(struct iio_dev *indio_dev,
0736                   struct iio_trigger *trig)
0737 {
0738     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0739     struct regmap *regmap = adc->dfsdm->regmap;
0740     int ret;
0741 
0742     ret = stm32_dfsdm_channels_configure(indio_dev, adc->fl_id, trig);
0743     if (ret < 0)
0744         return ret;
0745 
0746     ret = stm32_dfsdm_start_channel(indio_dev);
0747     if (ret < 0)
0748         return ret;
0749 
0750     ret = stm32_dfsdm_filter_configure(indio_dev, adc->fl_id, trig);
0751     if (ret < 0)
0752         goto stop_channels;
0753 
0754     ret = stm32_dfsdm_start_filter(adc, adc->fl_id, trig);
0755     if (ret < 0)
0756         goto filter_unconfigure;
0757 
0758     return 0;
0759 
0760 filter_unconfigure:
0761     regmap_update_bits(regmap, DFSDM_CR1(adc->fl_id),
0762                DFSDM_CR1_CFG_MASK, 0);
0763 stop_channels:
0764     stm32_dfsdm_stop_channel(indio_dev);
0765 
0766     return ret;
0767 }
0768 
0769 static void stm32_dfsdm_stop_conv(struct iio_dev *indio_dev)
0770 {
0771     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0772     struct regmap *regmap = adc->dfsdm->regmap;
0773 
0774     stm32_dfsdm_stop_filter(adc->dfsdm, adc->fl_id);
0775 
0776     regmap_update_bits(regmap, DFSDM_CR1(adc->fl_id),
0777                DFSDM_CR1_CFG_MASK, 0);
0778 
0779     stm32_dfsdm_stop_channel(indio_dev);
0780 }
0781 
0782 static int stm32_dfsdm_set_watermark(struct iio_dev *indio_dev,
0783                      unsigned int val)
0784 {
0785     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0786     unsigned int watermark = DFSDM_DMA_BUFFER_SIZE / 2;
0787     unsigned int rx_buf_sz = DFSDM_DMA_BUFFER_SIZE;
0788 
0789     /*
0790      * DMA cyclic transfers are used, buffer is split into two periods.
0791      * There should be :
0792      * - always one buffer (period) DMA is working on
0793      * - one buffer (period) driver pushed to ASoC side.
0794      */
0795     watermark = min(watermark, val * (unsigned int)(sizeof(u32)));
0796     adc->buf_sz = min(rx_buf_sz, watermark * 2 * adc->nconv);
0797 
0798     return 0;
0799 }
0800 
0801 static unsigned int stm32_dfsdm_adc_dma_residue(struct stm32_dfsdm_adc *adc)
0802 {
0803     struct dma_tx_state state;
0804     enum dma_status status;
0805 
0806     status = dmaengine_tx_status(adc->dma_chan,
0807                      adc->dma_chan->cookie,
0808                      &state);
0809     if (status == DMA_IN_PROGRESS) {
0810         /* Residue is size in bytes from end of buffer */
0811         unsigned int i = adc->buf_sz - state.residue;
0812         unsigned int size;
0813 
0814         /* Return available bytes */
0815         if (i >= adc->bufi)
0816             size = i - adc->bufi;
0817         else
0818             size = adc->buf_sz + i - adc->bufi;
0819 
0820         return size;
0821     }
0822 
0823     return 0;
0824 }
0825 
0826 static inline void stm32_dfsdm_process_data(struct stm32_dfsdm_adc *adc,
0827                         s32 *buffer)
0828 {
0829     struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[adc->fl_id];
0830     struct stm32_dfsdm_filter_osr *flo = &fl->flo[fl->fast];
0831     unsigned int i = adc->nconv;
0832     s32 *ptr = buffer;
0833 
0834     while (i--) {
0835         /* Mask 8 LSB that contains the channel ID */
0836         *ptr &= 0xFFFFFF00;
0837         /* Convert 2^(n-1) sample to 2^(n-1)-1 to avoid wrap-around */
0838         if (*ptr > flo->max)
0839             *ptr -= 1;
0840         /*
0841          * Samples from filter are retrieved with 23 bits resolution
0842          * or less. Shift left to align MSB on 24 bits.
0843          */
0844         *ptr <<= flo->lshift;
0845 
0846         ptr++;
0847     }
0848 }
0849 
0850 static void stm32_dfsdm_dma_buffer_done(void *data)
0851 {
0852     struct iio_dev *indio_dev = data;
0853     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0854     int available = stm32_dfsdm_adc_dma_residue(adc);
0855     size_t old_pos;
0856 
0857     /*
0858      * FIXME: In Kernel interface does not support cyclic DMA buffer,and
0859      * offers only an interface to push data samples per samples.
0860      * For this reason IIO buffer interface is not used and interface is
0861      * bypassed using a private callback registered by ASoC.
0862      * This should be a temporary solution waiting a cyclic DMA engine
0863      * support in IIO.
0864      */
0865 
0866     dev_dbg(&indio_dev->dev, "pos = %d, available = %d\n",
0867         adc->bufi, available);
0868     old_pos = adc->bufi;
0869 
0870     while (available >= indio_dev->scan_bytes) {
0871         s32 *buffer = (s32 *)&adc->rx_buf[adc->bufi];
0872 
0873         stm32_dfsdm_process_data(adc, buffer);
0874 
0875         available -= indio_dev->scan_bytes;
0876         adc->bufi += indio_dev->scan_bytes;
0877         if (adc->bufi >= adc->buf_sz) {
0878             if (adc->cb)
0879                 adc->cb(&adc->rx_buf[old_pos],
0880                      adc->buf_sz - old_pos, adc->cb_priv);
0881             adc->bufi = 0;
0882             old_pos = 0;
0883         }
0884         /*
0885          * In DMA mode the trigger services of IIO are not used
0886          * (e.g. no call to iio_trigger_poll).
0887          * Calling irq handler associated to the hardware trigger is not
0888          * relevant as the conversions have already been done. Data
0889          * transfers are performed directly in DMA callback instead.
0890          * This implementation avoids to call trigger irq handler that
0891          * may sleep, in an atomic context (DMA irq handler context).
0892          */
0893         if (adc->dev_data->type == DFSDM_IIO)
0894             iio_push_to_buffers(indio_dev, buffer);
0895     }
0896     if (adc->cb)
0897         adc->cb(&adc->rx_buf[old_pos], adc->bufi - old_pos,
0898             adc->cb_priv);
0899 }
0900 
0901 static int stm32_dfsdm_adc_dma_start(struct iio_dev *indio_dev)
0902 {
0903     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0904     /*
0905      * The DFSDM supports half-word transfers. However, for 16 bits record,
0906      * 4 bytes buswidth is kept, to avoid losing samples LSBs when left
0907      * shift is required.
0908      */
0909     struct dma_slave_config config = {
0910         .src_addr = (dma_addr_t)adc->dfsdm->phys_base,
0911         .src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES,
0912     };
0913     struct dma_async_tx_descriptor *desc;
0914     dma_cookie_t cookie;
0915     int ret;
0916 
0917     if (!adc->dma_chan)
0918         return -EINVAL;
0919 
0920     dev_dbg(&indio_dev->dev, "size=%d watermark=%d\n",
0921         adc->buf_sz, adc->buf_sz / 2);
0922 
0923     if (adc->nconv == 1 && !indio_dev->trig)
0924         config.src_addr += DFSDM_RDATAR(adc->fl_id);
0925     else
0926         config.src_addr += DFSDM_JDATAR(adc->fl_id);
0927     ret = dmaengine_slave_config(adc->dma_chan, &config);
0928     if (ret)
0929         return ret;
0930 
0931     /* Prepare a DMA cyclic transaction */
0932     desc = dmaengine_prep_dma_cyclic(adc->dma_chan,
0933                      adc->dma_buf,
0934                      adc->buf_sz, adc->buf_sz / 2,
0935                      DMA_DEV_TO_MEM,
0936                      DMA_PREP_INTERRUPT);
0937     if (!desc)
0938         return -EBUSY;
0939 
0940     desc->callback = stm32_dfsdm_dma_buffer_done;
0941     desc->callback_param = indio_dev;
0942 
0943     cookie = dmaengine_submit(desc);
0944     ret = dma_submit_error(cookie);
0945     if (ret)
0946         goto err_stop_dma;
0947 
0948     /* Issue pending DMA requests */
0949     dma_async_issue_pending(adc->dma_chan);
0950 
0951     if (adc->nconv == 1 && !indio_dev->trig) {
0952         /* Enable regular DMA transfer*/
0953         ret = regmap_update_bits(adc->dfsdm->regmap,
0954                      DFSDM_CR1(adc->fl_id),
0955                      DFSDM_CR1_RDMAEN_MASK,
0956                      DFSDM_CR1_RDMAEN_MASK);
0957     } else {
0958         /* Enable injected DMA transfer*/
0959         ret = regmap_update_bits(adc->dfsdm->regmap,
0960                      DFSDM_CR1(adc->fl_id),
0961                      DFSDM_CR1_JDMAEN_MASK,
0962                      DFSDM_CR1_JDMAEN_MASK);
0963     }
0964 
0965     if (ret < 0)
0966         goto err_stop_dma;
0967 
0968     return 0;
0969 
0970 err_stop_dma:
0971     dmaengine_terminate_all(adc->dma_chan);
0972 
0973     return ret;
0974 }
0975 
0976 static void stm32_dfsdm_adc_dma_stop(struct iio_dev *indio_dev)
0977 {
0978     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0979 
0980     if (!adc->dma_chan)
0981         return;
0982 
0983     regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR1(adc->fl_id),
0984                DFSDM_CR1_RDMAEN_MASK | DFSDM_CR1_JDMAEN_MASK, 0);
0985     dmaengine_terminate_all(adc->dma_chan);
0986 }
0987 
0988 static int stm32_dfsdm_update_scan_mode(struct iio_dev *indio_dev,
0989                     const unsigned long *scan_mask)
0990 {
0991     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
0992 
0993     adc->nconv = bitmap_weight(scan_mask, indio_dev->masklength);
0994     adc->smask = *scan_mask;
0995 
0996     dev_dbg(&indio_dev->dev, "nconv=%d mask=%lx\n", adc->nconv, *scan_mask);
0997 
0998     return 0;
0999 }
1000 
1001 static int stm32_dfsdm_postenable(struct iio_dev *indio_dev)
1002 {
1003     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1004     int ret;
1005 
1006     /* Reset adc buffer index */
1007     adc->bufi = 0;
1008 
1009     if (adc->hwc) {
1010         ret = iio_hw_consumer_enable(adc->hwc);
1011         if (ret < 0)
1012             return ret;
1013     }
1014 
1015     ret = stm32_dfsdm_start_dfsdm(adc->dfsdm);
1016     if (ret < 0)
1017         goto err_stop_hwc;
1018 
1019     ret = stm32_dfsdm_adc_dma_start(indio_dev);
1020     if (ret) {
1021         dev_err(&indio_dev->dev, "Can't start DMA\n");
1022         goto stop_dfsdm;
1023     }
1024 
1025     ret = stm32_dfsdm_start_conv(indio_dev, indio_dev->trig);
1026     if (ret) {
1027         dev_err(&indio_dev->dev, "Can't start conversion\n");
1028         goto err_stop_dma;
1029     }
1030 
1031     return 0;
1032 
1033 err_stop_dma:
1034     stm32_dfsdm_adc_dma_stop(indio_dev);
1035 stop_dfsdm:
1036     stm32_dfsdm_stop_dfsdm(adc->dfsdm);
1037 err_stop_hwc:
1038     if (adc->hwc)
1039         iio_hw_consumer_disable(adc->hwc);
1040 
1041     return ret;
1042 }
1043 
1044 static int stm32_dfsdm_predisable(struct iio_dev *indio_dev)
1045 {
1046     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1047 
1048     stm32_dfsdm_stop_conv(indio_dev);
1049 
1050     stm32_dfsdm_adc_dma_stop(indio_dev);
1051 
1052     stm32_dfsdm_stop_dfsdm(adc->dfsdm);
1053 
1054     if (adc->hwc)
1055         iio_hw_consumer_disable(adc->hwc);
1056 
1057     return 0;
1058 }
1059 
1060 static const struct iio_buffer_setup_ops stm32_dfsdm_buffer_setup_ops = {
1061     .postenable = &stm32_dfsdm_postenable,
1062     .predisable = &stm32_dfsdm_predisable,
1063 };
1064 
1065 /**
1066  * stm32_dfsdm_get_buff_cb() - register a callback that will be called when
1067  *                             DMA transfer period is achieved.
1068  *
1069  * @iio_dev: Handle to IIO device.
1070  * @cb: Pointer to callback function:
1071  *      - data: pointer to data buffer
1072  *      - size: size in byte of the data buffer
1073  *      - private: pointer to consumer private structure.
1074  * @private: Pointer to consumer private structure.
1075  */
1076 int stm32_dfsdm_get_buff_cb(struct iio_dev *iio_dev,
1077                 int (*cb)(const void *data, size_t size,
1078                       void *private),
1079                 void *private)
1080 {
1081     struct stm32_dfsdm_adc *adc;
1082 
1083     if (!iio_dev)
1084         return -EINVAL;
1085     adc = iio_priv(iio_dev);
1086 
1087     adc->cb = cb;
1088     adc->cb_priv = private;
1089 
1090     return 0;
1091 }
1092 EXPORT_SYMBOL_GPL(stm32_dfsdm_get_buff_cb);
1093 
1094 /**
1095  * stm32_dfsdm_release_buff_cb - unregister buffer callback
1096  *
1097  * @iio_dev: Handle to IIO device.
1098  */
1099 int stm32_dfsdm_release_buff_cb(struct iio_dev *iio_dev)
1100 {
1101     struct stm32_dfsdm_adc *adc;
1102 
1103     if (!iio_dev)
1104         return -EINVAL;
1105     adc = iio_priv(iio_dev);
1106 
1107     adc->cb = NULL;
1108     adc->cb_priv = NULL;
1109 
1110     return 0;
1111 }
1112 EXPORT_SYMBOL_GPL(stm32_dfsdm_release_buff_cb);
1113 
1114 static int stm32_dfsdm_single_conv(struct iio_dev *indio_dev,
1115                    const struct iio_chan_spec *chan, int *res)
1116 {
1117     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1118     long timeout;
1119     int ret;
1120 
1121     reinit_completion(&adc->completion);
1122 
1123     adc->buffer = res;
1124 
1125     ret = stm32_dfsdm_start_dfsdm(adc->dfsdm);
1126     if (ret < 0)
1127         return ret;
1128 
1129     ret = regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1130                  DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(1));
1131     if (ret < 0)
1132         goto stop_dfsdm;
1133 
1134     adc->nconv = 1;
1135     adc->smask = BIT(chan->scan_index);
1136     ret = stm32_dfsdm_start_conv(indio_dev, NULL);
1137     if (ret < 0) {
1138         regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1139                    DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(0));
1140         goto stop_dfsdm;
1141     }
1142 
1143     timeout = wait_for_completion_interruptible_timeout(&adc->completion,
1144                                 DFSDM_TIMEOUT);
1145 
1146     /* Mask IRQ for regular conversion achievement*/
1147     regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1148                DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(0));
1149 
1150     if (timeout == 0)
1151         ret = -ETIMEDOUT;
1152     else if (timeout < 0)
1153         ret = timeout;
1154     else
1155         ret = IIO_VAL_INT;
1156 
1157     stm32_dfsdm_stop_conv(indio_dev);
1158 
1159     stm32_dfsdm_process_data(adc, res);
1160 
1161 stop_dfsdm:
1162     stm32_dfsdm_stop_dfsdm(adc->dfsdm);
1163 
1164     return ret;
1165 }
1166 
1167 static int stm32_dfsdm_write_raw(struct iio_dev *indio_dev,
1168                  struct iio_chan_spec const *chan,
1169                  int val, int val2, long mask)
1170 {
1171     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1172     struct stm32_dfsdm_channel *ch = &adc->dfsdm->ch_list[chan->channel];
1173     unsigned int spi_freq;
1174     int ret = -EINVAL;
1175 
1176     switch (ch->src) {
1177     case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL:
1178         spi_freq = adc->dfsdm->spi_master_freq;
1179         break;
1180     case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_FALLING:
1181     case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_RISING:
1182         spi_freq = adc->dfsdm->spi_master_freq / 2;
1183         break;
1184     default:
1185         spi_freq = adc->spi_freq;
1186     }
1187 
1188     switch (mask) {
1189     case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1190         ret = iio_device_claim_direct_mode(indio_dev);
1191         if (ret)
1192             return ret;
1193 
1194         ret = stm32_dfsdm_compute_all_osrs(indio_dev, val);
1195         if (!ret) {
1196             dev_dbg(&indio_dev->dev,
1197                 "Sampling rate changed from (%u) to (%u)\n",
1198                 adc->sample_freq, spi_freq / val);
1199             adc->oversamp = val;
1200             adc->sample_freq = spi_freq / val;
1201         }
1202         iio_device_release_direct_mode(indio_dev);
1203         return ret;
1204 
1205     case IIO_CHAN_INFO_SAMP_FREQ:
1206         if (!val)
1207             return -EINVAL;
1208 
1209         ret = iio_device_claim_direct_mode(indio_dev);
1210         if (ret)
1211             return ret;
1212 
1213         ret = dfsdm_adc_set_samp_freq(indio_dev, val, spi_freq);
1214         iio_device_release_direct_mode(indio_dev);
1215         return ret;
1216     }
1217 
1218     return -EINVAL;
1219 }
1220 
1221 static int stm32_dfsdm_read_raw(struct iio_dev *indio_dev,
1222                 struct iio_chan_spec const *chan, int *val,
1223                 int *val2, long mask)
1224 {
1225     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1226     int ret;
1227 
1228     switch (mask) {
1229     case IIO_CHAN_INFO_RAW:
1230         ret = iio_device_claim_direct_mode(indio_dev);
1231         if (ret)
1232             return ret;
1233         ret = iio_hw_consumer_enable(adc->hwc);
1234         if (ret < 0) {
1235             dev_err(&indio_dev->dev,
1236                 "%s: IIO enable failed (channel %d)\n",
1237                 __func__, chan->channel);
1238             iio_device_release_direct_mode(indio_dev);
1239             return ret;
1240         }
1241         ret = stm32_dfsdm_single_conv(indio_dev, chan, val);
1242         iio_hw_consumer_disable(adc->hwc);
1243         if (ret < 0) {
1244             dev_err(&indio_dev->dev,
1245                 "%s: Conversion failed (channel %d)\n",
1246                 __func__, chan->channel);
1247             iio_device_release_direct_mode(indio_dev);
1248             return ret;
1249         }
1250         iio_device_release_direct_mode(indio_dev);
1251         return IIO_VAL_INT;
1252 
1253     case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1254         *val = adc->oversamp;
1255 
1256         return IIO_VAL_INT;
1257 
1258     case IIO_CHAN_INFO_SAMP_FREQ:
1259         *val = adc->sample_freq;
1260 
1261         return IIO_VAL_INT;
1262     }
1263 
1264     return -EINVAL;
1265 }
1266 
1267 static int stm32_dfsdm_validate_trigger(struct iio_dev *indio_dev,
1268                     struct iio_trigger *trig)
1269 {
1270     return stm32_dfsdm_get_jextsel(indio_dev, trig) < 0 ? -EINVAL : 0;
1271 }
1272 
1273 static const struct iio_info stm32_dfsdm_info_audio = {
1274     .hwfifo_set_watermark = stm32_dfsdm_set_watermark,
1275     .read_raw = stm32_dfsdm_read_raw,
1276     .write_raw = stm32_dfsdm_write_raw,
1277     .update_scan_mode = stm32_dfsdm_update_scan_mode,
1278 };
1279 
1280 static const struct iio_info stm32_dfsdm_info_adc = {
1281     .hwfifo_set_watermark = stm32_dfsdm_set_watermark,
1282     .read_raw = stm32_dfsdm_read_raw,
1283     .write_raw = stm32_dfsdm_write_raw,
1284     .update_scan_mode = stm32_dfsdm_update_scan_mode,
1285     .validate_trigger = stm32_dfsdm_validate_trigger,
1286 };
1287 
1288 static irqreturn_t stm32_dfsdm_irq(int irq, void *arg)
1289 {
1290     struct iio_dev *indio_dev = arg;
1291     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1292     struct regmap *regmap = adc->dfsdm->regmap;
1293     unsigned int status, int_en;
1294 
1295     regmap_read(regmap, DFSDM_ISR(adc->fl_id), &status);
1296     regmap_read(regmap, DFSDM_CR2(adc->fl_id), &int_en);
1297 
1298     if (status & DFSDM_ISR_REOCF_MASK) {
1299         /* Read the data register clean the IRQ status */
1300         regmap_read(regmap, DFSDM_RDATAR(adc->fl_id), adc->buffer);
1301         complete(&adc->completion);
1302     }
1303 
1304     if (status & DFSDM_ISR_ROVRF_MASK) {
1305         if (int_en & DFSDM_CR2_ROVRIE_MASK)
1306             dev_warn(&indio_dev->dev, "Overrun detected\n");
1307         regmap_update_bits(regmap, DFSDM_ICR(adc->fl_id),
1308                    DFSDM_ICR_CLRROVRF_MASK,
1309                    DFSDM_ICR_CLRROVRF_MASK);
1310     }
1311 
1312     return IRQ_HANDLED;
1313 }
1314 
1315 /*
1316  * Define external info for SPI Frequency and audio sampling rate that can be
1317  * configured by ASoC driver through consumer.h API
1318  */
1319 static const struct iio_chan_spec_ext_info dfsdm_adc_audio_ext_info[] = {
1320     /* spi_clk_freq : clock freq on SPI/manchester bus used by channel */
1321     {
1322         .name = "spi_clk_freq",
1323         .shared = IIO_SHARED_BY_TYPE,
1324         .read = dfsdm_adc_audio_get_spiclk,
1325         .write = dfsdm_adc_audio_set_spiclk,
1326     },
1327     {},
1328 };
1329 
1330 static void stm32_dfsdm_dma_release(struct iio_dev *indio_dev)
1331 {
1332     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1333 
1334     if (adc->dma_chan) {
1335         dma_free_coherent(adc->dma_chan->device->dev,
1336                   DFSDM_DMA_BUFFER_SIZE,
1337                   adc->rx_buf, adc->dma_buf);
1338         dma_release_channel(adc->dma_chan);
1339     }
1340 }
1341 
1342 static int stm32_dfsdm_dma_request(struct device *dev,
1343                    struct iio_dev *indio_dev)
1344 {
1345     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1346 
1347     adc->dma_chan = dma_request_chan(dev, "rx");
1348     if (IS_ERR(adc->dma_chan)) {
1349         int ret = PTR_ERR(adc->dma_chan);
1350 
1351         adc->dma_chan = NULL;
1352         return ret;
1353     }
1354 
1355     adc->rx_buf = dma_alloc_coherent(adc->dma_chan->device->dev,
1356                      DFSDM_DMA_BUFFER_SIZE,
1357                      &adc->dma_buf, GFP_KERNEL);
1358     if (!adc->rx_buf) {
1359         dma_release_channel(adc->dma_chan);
1360         return -ENOMEM;
1361     }
1362 
1363     indio_dev->modes |= INDIO_BUFFER_SOFTWARE;
1364     indio_dev->setup_ops = &stm32_dfsdm_buffer_setup_ops;
1365 
1366     return 0;
1367 }
1368 
1369 static int stm32_dfsdm_adc_chan_init_one(struct iio_dev *indio_dev,
1370                      struct iio_chan_spec *ch)
1371 {
1372     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1373     int ret;
1374 
1375     ret = stm32_dfsdm_channel_parse_of(adc->dfsdm, indio_dev, ch);
1376     if (ret < 0)
1377         return ret;
1378 
1379     ch->type = IIO_VOLTAGE;
1380     ch->indexed = 1;
1381 
1382     /*
1383      * IIO_CHAN_INFO_RAW: used to compute regular conversion
1384      * IIO_CHAN_INFO_OVERSAMPLING_RATIO: used to set oversampling
1385      */
1386     ch->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
1387     ch->info_mask_shared_by_all = BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |
1388                     BIT(IIO_CHAN_INFO_SAMP_FREQ);
1389 
1390     if (adc->dev_data->type == DFSDM_AUDIO) {
1391         ch->ext_info = dfsdm_adc_audio_ext_info;
1392     } else {
1393         ch->scan_type.shift = 8;
1394     }
1395     ch->scan_type.sign = 's';
1396     ch->scan_type.realbits = 24;
1397     ch->scan_type.storagebits = 32;
1398 
1399     return stm32_dfsdm_chan_configure(adc->dfsdm,
1400                       &adc->dfsdm->ch_list[ch->channel]);
1401 }
1402 
1403 static int stm32_dfsdm_audio_init(struct device *dev, struct iio_dev *indio_dev)
1404 {
1405     struct iio_chan_spec *ch;
1406     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1407     struct stm32_dfsdm_channel *d_ch;
1408     int ret;
1409 
1410     ch = devm_kzalloc(&indio_dev->dev, sizeof(*ch), GFP_KERNEL);
1411     if (!ch)
1412         return -ENOMEM;
1413 
1414     ch->scan_index = 0;
1415 
1416     ret = stm32_dfsdm_adc_chan_init_one(indio_dev, ch);
1417     if (ret < 0) {
1418         dev_err(&indio_dev->dev, "Channels init failed\n");
1419         return ret;
1420     }
1421     ch->info_mask_separate = BIT(IIO_CHAN_INFO_SAMP_FREQ);
1422 
1423     d_ch = &adc->dfsdm->ch_list[ch->channel];
1424     if (d_ch->src != DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL)
1425         adc->spi_freq = adc->dfsdm->spi_master_freq;
1426 
1427     indio_dev->num_channels = 1;
1428     indio_dev->channels = ch;
1429 
1430     return stm32_dfsdm_dma_request(dev, indio_dev);
1431 }
1432 
1433 static int stm32_dfsdm_adc_init(struct device *dev, struct iio_dev *indio_dev)
1434 {
1435     struct iio_chan_spec *ch;
1436     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1437     int num_ch;
1438     int ret, chan_idx;
1439 
1440     adc->oversamp = DFSDM_DEFAULT_OVERSAMPLING;
1441     ret = stm32_dfsdm_compute_all_osrs(indio_dev, adc->oversamp);
1442     if (ret < 0)
1443         return ret;
1444 
1445     num_ch = of_property_count_u32_elems(indio_dev->dev.of_node,
1446                          "st,adc-channels");
1447     if (num_ch < 0 || num_ch > adc->dfsdm->num_chs) {
1448         dev_err(&indio_dev->dev, "Bad st,adc-channels\n");
1449         return num_ch < 0 ? num_ch : -EINVAL;
1450     }
1451 
1452     /* Bind to SD modulator IIO device */
1453     adc->hwc = devm_iio_hw_consumer_alloc(&indio_dev->dev);
1454     if (IS_ERR(adc->hwc))
1455         return -EPROBE_DEFER;
1456 
1457     ch = devm_kcalloc(&indio_dev->dev, num_ch, sizeof(*ch),
1458               GFP_KERNEL);
1459     if (!ch)
1460         return -ENOMEM;
1461 
1462     for (chan_idx = 0; chan_idx < num_ch; chan_idx++) {
1463         ch[chan_idx].scan_index = chan_idx;
1464         ret = stm32_dfsdm_adc_chan_init_one(indio_dev, &ch[chan_idx]);
1465         if (ret < 0) {
1466             dev_err(&indio_dev->dev, "Channels init failed\n");
1467             return ret;
1468         }
1469     }
1470 
1471     indio_dev->num_channels = num_ch;
1472     indio_dev->channels = ch;
1473 
1474     init_completion(&adc->completion);
1475 
1476     /* Optionally request DMA */
1477     ret = stm32_dfsdm_dma_request(dev, indio_dev);
1478     if (ret) {
1479         if (ret != -ENODEV)
1480             return dev_err_probe(dev, ret,
1481                          "DMA channel request failed with\n");
1482 
1483         dev_dbg(dev, "No DMA support\n");
1484         return 0;
1485     }
1486 
1487     ret = iio_triggered_buffer_setup(indio_dev,
1488                      &iio_pollfunc_store_time, NULL,
1489                      &stm32_dfsdm_buffer_setup_ops);
1490     if (ret) {
1491         stm32_dfsdm_dma_release(indio_dev);
1492         dev_err(&indio_dev->dev, "buffer setup failed\n");
1493         return ret;
1494     }
1495 
1496     /* lptimer/timer hardware triggers */
1497     indio_dev->modes |= INDIO_HARDWARE_TRIGGERED;
1498 
1499     return 0;
1500 }
1501 
1502 static const struct stm32_dfsdm_dev_data stm32h7_dfsdm_adc_data = {
1503     .type = DFSDM_IIO,
1504     .init = stm32_dfsdm_adc_init,
1505 };
1506 
1507 static const struct stm32_dfsdm_dev_data stm32h7_dfsdm_audio_data = {
1508     .type = DFSDM_AUDIO,
1509     .init = stm32_dfsdm_audio_init,
1510 };
1511 
1512 static const struct of_device_id stm32_dfsdm_adc_match[] = {
1513     {
1514         .compatible = "st,stm32-dfsdm-adc",
1515         .data = &stm32h7_dfsdm_adc_data,
1516     },
1517     {
1518         .compatible = "st,stm32-dfsdm-dmic",
1519         .data = &stm32h7_dfsdm_audio_data,
1520     },
1521     {}
1522 };
1523 
1524 static int stm32_dfsdm_adc_probe(struct platform_device *pdev)
1525 {
1526     struct device *dev = &pdev->dev;
1527     struct stm32_dfsdm_adc *adc;
1528     struct device_node *np = dev->of_node;
1529     const struct stm32_dfsdm_dev_data *dev_data;
1530     struct iio_dev *iio;
1531     char *name;
1532     int ret, irq, val;
1533 
1534     dev_data = of_device_get_match_data(dev);
1535     iio = devm_iio_device_alloc(dev, sizeof(*adc));
1536     if (!iio) {
1537         dev_err(dev, "%s: Failed to allocate IIO\n", __func__);
1538         return -ENOMEM;
1539     }
1540 
1541     adc = iio_priv(iio);
1542     adc->dfsdm = dev_get_drvdata(dev->parent);
1543 
1544     iio->dev.of_node = np;
1545     iio->modes = INDIO_DIRECT_MODE;
1546 
1547     platform_set_drvdata(pdev, iio);
1548 
1549     ret = of_property_read_u32(dev->of_node, "reg", &adc->fl_id);
1550     if (ret != 0 || adc->fl_id >= adc->dfsdm->num_fls) {
1551         dev_err(dev, "Missing or bad reg property\n");
1552         return -EINVAL;
1553     }
1554 
1555     name = devm_kzalloc(dev, sizeof("dfsdm-adc0"), GFP_KERNEL);
1556     if (!name)
1557         return -ENOMEM;
1558     if (dev_data->type == DFSDM_AUDIO) {
1559         iio->info = &stm32_dfsdm_info_audio;
1560         snprintf(name, sizeof("dfsdm-pdm0"), "dfsdm-pdm%d", adc->fl_id);
1561     } else {
1562         iio->info = &stm32_dfsdm_info_adc;
1563         snprintf(name, sizeof("dfsdm-adc0"), "dfsdm-adc%d", adc->fl_id);
1564     }
1565     iio->name = name;
1566 
1567     /*
1568      * In a first step IRQs generated for channels are not treated.
1569      * So IRQ associated to filter instance 0 is dedicated to the Filter 0.
1570      */
1571     irq = platform_get_irq(pdev, 0);
1572     if (irq < 0)
1573         return irq;
1574 
1575     ret = devm_request_irq(dev, irq, stm32_dfsdm_irq,
1576                    0, pdev->name, iio);
1577     if (ret < 0) {
1578         dev_err(dev, "Failed to request IRQ\n");
1579         return ret;
1580     }
1581 
1582     ret = of_property_read_u32(dev->of_node, "st,filter-order", &val);
1583     if (ret < 0) {
1584         dev_err(dev, "Failed to set filter order\n");
1585         return ret;
1586     }
1587 
1588     adc->dfsdm->fl_list[adc->fl_id].ford = val;
1589 
1590     ret = of_property_read_u32(dev->of_node, "st,filter0-sync", &val);
1591     if (!ret)
1592         adc->dfsdm->fl_list[adc->fl_id].sync_mode = val;
1593 
1594     adc->dev_data = dev_data;
1595     ret = dev_data->init(dev, iio);
1596     if (ret < 0)
1597         return ret;
1598 
1599     ret = iio_device_register(iio);
1600     if (ret < 0)
1601         goto err_cleanup;
1602 
1603     if (dev_data->type == DFSDM_AUDIO) {
1604         ret = of_platform_populate(np, NULL, NULL, dev);
1605         if (ret < 0) {
1606             dev_err(dev, "Failed to find an audio DAI\n");
1607             goto err_unregister;
1608         }
1609     }
1610 
1611     return 0;
1612 
1613 err_unregister:
1614     iio_device_unregister(iio);
1615 err_cleanup:
1616     stm32_dfsdm_dma_release(iio);
1617 
1618     return ret;
1619 }
1620 
1621 static int stm32_dfsdm_adc_remove(struct platform_device *pdev)
1622 {
1623     struct iio_dev *indio_dev = platform_get_drvdata(pdev);
1624     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1625 
1626     if (adc->dev_data->type == DFSDM_AUDIO)
1627         of_platform_depopulate(&pdev->dev);
1628     iio_device_unregister(indio_dev);
1629     stm32_dfsdm_dma_release(indio_dev);
1630 
1631     return 0;
1632 }
1633 
1634 static int stm32_dfsdm_adc_suspend(struct device *dev)
1635 {
1636     struct iio_dev *indio_dev = dev_get_drvdata(dev);
1637 
1638     if (iio_buffer_enabled(indio_dev))
1639         stm32_dfsdm_predisable(indio_dev);
1640 
1641     return 0;
1642 }
1643 
1644 static int stm32_dfsdm_adc_resume(struct device *dev)
1645 {
1646     struct iio_dev *indio_dev = dev_get_drvdata(dev);
1647     struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1648     const struct iio_chan_spec *chan;
1649     struct stm32_dfsdm_channel *ch;
1650     int i, ret;
1651 
1652     /* restore channels configuration */
1653     for (i = 0; i < indio_dev->num_channels; i++) {
1654         chan = indio_dev->channels + i;
1655         ch = &adc->dfsdm->ch_list[chan->channel];
1656         ret = stm32_dfsdm_chan_configure(adc->dfsdm, ch);
1657         if (ret)
1658             return ret;
1659     }
1660 
1661     if (iio_buffer_enabled(indio_dev))
1662         stm32_dfsdm_postenable(indio_dev);
1663 
1664     return 0;
1665 }
1666 
1667 static DEFINE_SIMPLE_DEV_PM_OPS(stm32_dfsdm_adc_pm_ops,
1668                 stm32_dfsdm_adc_suspend,
1669                 stm32_dfsdm_adc_resume);
1670 
1671 static struct platform_driver stm32_dfsdm_adc_driver = {
1672     .driver = {
1673         .name = "stm32-dfsdm-adc",
1674         .of_match_table = stm32_dfsdm_adc_match,
1675         .pm = pm_sleep_ptr(&stm32_dfsdm_adc_pm_ops),
1676     },
1677     .probe = stm32_dfsdm_adc_probe,
1678     .remove = stm32_dfsdm_adc_remove,
1679 };
1680 module_platform_driver(stm32_dfsdm_adc_driver);
1681 
1682 MODULE_DESCRIPTION("STM32 sigma delta ADC");
1683 MODULE_AUTHOR("Arnaud Pouliquen <arnaud.pouliquen@st.com>");
1684 MODULE_LICENSE("GPL v2");