Merge branch 'for-4.14' of git://git.kernel.org/pub/scm/linux/kernel/git/tj/wq
[sfrench/cifs-2.6.git] / drivers / iio / adc / stm32-adc.c
1 /*
2  * This file is part of STM32 ADC driver
3  *
4  * Copyright (C) 2016, STMicroelectronics - All Rights Reserved
5  * Author: Fabrice Gasnier <fabrice.gasnier@st.com>.
6  *
7  * License type: GPLv2
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU General Public License version 2 as published by
11  * the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15  * or FITNESS FOR A PARTICULAR PURPOSE.
16  * See the GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along with
19  * this program. If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <linux/clk.h>
23 #include <linux/delay.h>
24 #include <linux/dma-mapping.h>
25 #include <linux/dmaengine.h>
26 #include <linux/iio/iio.h>
27 #include <linux/iio/buffer.h>
28 #include <linux/iio/timer/stm32-timer-trigger.h>
29 #include <linux/iio/trigger.h>
30 #include <linux/iio/trigger_consumer.h>
31 #include <linux/iio/triggered_buffer.h>
32 #include <linux/interrupt.h>
33 #include <linux/io.h>
34 #include <linux/iopoll.h>
35 #include <linux/module.h>
36 #include <linux/platform_device.h>
37 #include <linux/of.h>
38 #include <linux/of_device.h>
39
40 #include "stm32-adc-core.h"
41
42 /* STM32F4 - Registers for each ADC instance */
43 #define STM32F4_ADC_SR                  0x00
44 #define STM32F4_ADC_CR1                 0x04
45 #define STM32F4_ADC_CR2                 0x08
46 #define STM32F4_ADC_SMPR1               0x0C
47 #define STM32F4_ADC_SMPR2               0x10
48 #define STM32F4_ADC_HTR                 0x24
49 #define STM32F4_ADC_LTR                 0x28
50 #define STM32F4_ADC_SQR1                0x2C
51 #define STM32F4_ADC_SQR2                0x30
52 #define STM32F4_ADC_SQR3                0x34
53 #define STM32F4_ADC_JSQR                0x38
54 #define STM32F4_ADC_JDR1                0x3C
55 #define STM32F4_ADC_JDR2                0x40
56 #define STM32F4_ADC_JDR3                0x44
57 #define STM32F4_ADC_JDR4                0x48
58 #define STM32F4_ADC_DR                  0x4C
59
60 /* STM32F4_ADC_SR - bit fields */
61 #define STM32F4_STRT                    BIT(4)
62 #define STM32F4_EOC                     BIT(1)
63
64 /* STM32F4_ADC_CR1 - bit fields */
65 #define STM32F4_RES_SHIFT               24
66 #define STM32F4_RES_MASK                GENMASK(25, 24)
67 #define STM32F4_SCAN                    BIT(8)
68 #define STM32F4_EOCIE                   BIT(5)
69
70 /* STM32F4_ADC_CR2 - bit fields */
71 #define STM32F4_SWSTART                 BIT(30)
72 #define STM32F4_EXTEN_SHIFT             28
73 #define STM32F4_EXTEN_MASK              GENMASK(29, 28)
74 #define STM32F4_EXTSEL_SHIFT            24
75 #define STM32F4_EXTSEL_MASK             GENMASK(27, 24)
76 #define STM32F4_EOCS                    BIT(10)
77 #define STM32F4_DDS                     BIT(9)
78 #define STM32F4_DMA                     BIT(8)
79 #define STM32F4_ADON                    BIT(0)
80
81 /* STM32H7 - Registers for each ADC instance */
82 #define STM32H7_ADC_ISR                 0x00
83 #define STM32H7_ADC_IER                 0x04
84 #define STM32H7_ADC_CR                  0x08
85 #define STM32H7_ADC_CFGR                0x0C
86 #define STM32H7_ADC_SMPR1               0x14
87 #define STM32H7_ADC_SMPR2               0x18
88 #define STM32H7_ADC_PCSEL               0x1C
89 #define STM32H7_ADC_SQR1                0x30
90 #define STM32H7_ADC_SQR2                0x34
91 #define STM32H7_ADC_SQR3                0x38
92 #define STM32H7_ADC_SQR4                0x3C
93 #define STM32H7_ADC_DR                  0x40
94 #define STM32H7_ADC_CALFACT             0xC4
95 #define STM32H7_ADC_CALFACT2            0xC8
96
97 /* STM32H7_ADC_ISR - bit fields */
98 #define STM32H7_EOC                     BIT(2)
99 #define STM32H7_ADRDY                   BIT(0)
100
101 /* STM32H7_ADC_IER - bit fields */
102 #define STM32H7_EOCIE                   STM32H7_EOC
103
104 /* STM32H7_ADC_CR - bit fields */
105 #define STM32H7_ADCAL                   BIT(31)
106 #define STM32H7_ADCALDIF                BIT(30)
107 #define STM32H7_DEEPPWD                 BIT(29)
108 #define STM32H7_ADVREGEN                BIT(28)
109 #define STM32H7_LINCALRDYW6             BIT(27)
110 #define STM32H7_LINCALRDYW5             BIT(26)
111 #define STM32H7_LINCALRDYW4             BIT(25)
112 #define STM32H7_LINCALRDYW3             BIT(24)
113 #define STM32H7_LINCALRDYW2             BIT(23)
114 #define STM32H7_LINCALRDYW1             BIT(22)
115 #define STM32H7_ADCALLIN                BIT(16)
116 #define STM32H7_BOOST                   BIT(8)
117 #define STM32H7_ADSTP                   BIT(4)
118 #define STM32H7_ADSTART                 BIT(2)
119 #define STM32H7_ADDIS                   BIT(1)
120 #define STM32H7_ADEN                    BIT(0)
121
122 /* STM32H7_ADC_CFGR bit fields */
123 #define STM32H7_EXTEN_SHIFT             10
124 #define STM32H7_EXTEN_MASK              GENMASK(11, 10)
125 #define STM32H7_EXTSEL_SHIFT            5
126 #define STM32H7_EXTSEL_MASK             GENMASK(9, 5)
127 #define STM32H7_RES_SHIFT               2
128 #define STM32H7_RES_MASK                GENMASK(4, 2)
129 #define STM32H7_DMNGT_SHIFT             0
130 #define STM32H7_DMNGT_MASK              GENMASK(1, 0)
131
132 enum stm32h7_adc_dmngt {
133         STM32H7_DMNGT_DR_ONLY,          /* Regular data in DR only */
134         STM32H7_DMNGT_DMA_ONESHOT,      /* DMA one shot mode */
135         STM32H7_DMNGT_DFSDM,            /* DFSDM mode */
136         STM32H7_DMNGT_DMA_CIRC,         /* DMA circular mode */
137 };
138
139 /* STM32H7_ADC_CALFACT - bit fields */
140 #define STM32H7_CALFACT_D_SHIFT         16
141 #define STM32H7_CALFACT_D_MASK          GENMASK(26, 16)
142 #define STM32H7_CALFACT_S_SHIFT         0
143 #define STM32H7_CALFACT_S_MASK          GENMASK(10, 0)
144
145 /* STM32H7_ADC_CALFACT2 - bit fields */
146 #define STM32H7_LINCALFACT_SHIFT        0
147 #define STM32H7_LINCALFACT_MASK         GENMASK(29, 0)
148
149 /* Number of linear calibration shadow registers / LINCALRDYW control bits */
150 #define STM32H7_LINCALFACT_NUM          6
151
152 /* BOOST bit must be set on STM32H7 when ADC clock is above 20MHz */
153 #define STM32H7_BOOST_CLKRATE           20000000UL
154
155 #define STM32_ADC_MAX_SQ                16      /* SQ1..SQ16 */
156 #define STM32_ADC_MAX_SMP               7       /* SMPx range is [0..7] */
157 #define STM32_ADC_TIMEOUT_US            100000
158 #define STM32_ADC_TIMEOUT       (msecs_to_jiffies(STM32_ADC_TIMEOUT_US / 1000))
159
160 #define STM32_DMA_BUFFER_SIZE           PAGE_SIZE
161
162 /* External trigger enable */
163 enum stm32_adc_exten {
164         STM32_EXTEN_SWTRIG,
165         STM32_EXTEN_HWTRIG_RISING_EDGE,
166         STM32_EXTEN_HWTRIG_FALLING_EDGE,
167         STM32_EXTEN_HWTRIG_BOTH_EDGES,
168 };
169
170 /* extsel - trigger mux selection value */
171 enum stm32_adc_extsel {
172         STM32_EXT0,
173         STM32_EXT1,
174         STM32_EXT2,
175         STM32_EXT3,
176         STM32_EXT4,
177         STM32_EXT5,
178         STM32_EXT6,
179         STM32_EXT7,
180         STM32_EXT8,
181         STM32_EXT9,
182         STM32_EXT10,
183         STM32_EXT11,
184         STM32_EXT12,
185         STM32_EXT13,
186         STM32_EXT14,
187         STM32_EXT15,
188 };
189
190 /**
191  * struct stm32_adc_trig_info - ADC trigger info
192  * @name:               name of the trigger, corresponding to its source
193  * @extsel:             trigger selection
194  */
195 struct stm32_adc_trig_info {
196         const char *name;
197         enum stm32_adc_extsel extsel;
198 };
199
200 /**
201  * struct stm32_adc_calib - optional adc calibration data
202  * @calfact_s: Calibration offset for single ended channels
203  * @calfact_d: Calibration offset in differential
204  * @lincalfact: Linearity calibration factor
205  */
206 struct stm32_adc_calib {
207         u32                     calfact_s;
208         u32                     calfact_d;
209         u32                     lincalfact[STM32H7_LINCALFACT_NUM];
210 };
211
212 /**
213  * stm32_adc_regs - stm32 ADC misc registers & bitfield desc
214  * @reg:                register offset
215  * @mask:               bitfield mask
216  * @shift:              left shift
217  */
218 struct stm32_adc_regs {
219         int reg;
220         int mask;
221         int shift;
222 };
223
224 /**
225  * stm32_adc_regspec - stm32 registers definition, compatible dependent data
226  * @dr:                 data register offset
227  * @ier_eoc:            interrupt enable register & eocie bitfield
228  * @isr_eoc:            interrupt status register & eoc bitfield
229  * @sqr:                reference to sequence registers array
230  * @exten:              trigger control register & bitfield
231  * @extsel:             trigger selection register & bitfield
232  * @res:                resolution selection register & bitfield
233  * @smpr:               smpr1 & smpr2 registers offset array
234  * @smp_bits:           smpr1 & smpr2 index and bitfields
235  */
236 struct stm32_adc_regspec {
237         const u32 dr;
238         const struct stm32_adc_regs ier_eoc;
239         const struct stm32_adc_regs isr_eoc;
240         const struct stm32_adc_regs *sqr;
241         const struct stm32_adc_regs exten;
242         const struct stm32_adc_regs extsel;
243         const struct stm32_adc_regs res;
244         const u32 smpr[2];
245         const struct stm32_adc_regs *smp_bits;
246 };
247
248 struct stm32_adc;
249
250 /**
251  * stm32_adc_cfg - stm32 compatible configuration data
252  * @regs:               registers descriptions
253  * @adc_info:           per instance input channels definitions
254  * @trigs:              external trigger sources
255  * @clk_required:       clock is required
256  * @selfcalib:          optional routine for self-calibration
257  * @prepare:            optional prepare routine (power-up, enable)
258  * @start_conv:         routine to start conversions
259  * @stop_conv:          routine to stop conversions
260  * @unprepare:          optional unprepare routine (disable, power-down)
261  * @smp_cycles:         programmable sampling time (ADC clock cycles)
262  */
263 struct stm32_adc_cfg {
264         const struct stm32_adc_regspec  *regs;
265         const struct stm32_adc_info     *adc_info;
266         struct stm32_adc_trig_info      *trigs;
267         bool clk_required;
268         int (*selfcalib)(struct stm32_adc *);
269         int (*prepare)(struct stm32_adc *);
270         void (*start_conv)(struct stm32_adc *, bool dma);
271         void (*stop_conv)(struct stm32_adc *);
272         void (*unprepare)(struct stm32_adc *);
273         const unsigned int *smp_cycles;
274 };
275
276 /**
277  * struct stm32_adc - private data of each ADC IIO instance
278  * @common:             reference to ADC block common data
279  * @offset:             ADC instance register offset in ADC block
280  * @cfg:                compatible configuration data
281  * @completion:         end of single conversion completion
282  * @buffer:             data buffer
283  * @clk:                clock for this adc instance
284  * @irq:                interrupt for this adc instance
285  * @lock:               spinlock
286  * @bufi:               data buffer index
287  * @num_conv:           expected number of scan conversions
288  * @res:                data resolution (e.g. RES bitfield value)
289  * @trigger_polarity:   external trigger polarity (e.g. exten)
290  * @dma_chan:           dma channel
291  * @rx_buf:             dma rx buffer cpu address
292  * @rx_dma_buf:         dma rx buffer bus address
293  * @rx_buf_sz:          dma rx buffer size
294  * @pcsel               bitmask to preselect channels on some devices
295  * @smpr_val:           sampling time settings (e.g. smpr1 / smpr2)
296  * @cal:                optional calibration data on some devices
297  */
298 struct stm32_adc {
299         struct stm32_adc_common *common;
300         u32                     offset;
301         const struct stm32_adc_cfg      *cfg;
302         struct completion       completion;
303         u16                     buffer[STM32_ADC_MAX_SQ];
304         struct clk              *clk;
305         int                     irq;
306         spinlock_t              lock;           /* interrupt lock */
307         unsigned int            bufi;
308         unsigned int            num_conv;
309         u32                     res;
310         u32                     trigger_polarity;
311         struct dma_chan         *dma_chan;
312         u8                      *rx_buf;
313         dma_addr_t              rx_dma_buf;
314         unsigned int            rx_buf_sz;
315         u32                     pcsel;
316         u32                     smpr_val[2];
317         struct stm32_adc_calib  cal;
318 };
319
320 /**
321  * struct stm32_adc_chan_spec - specification of stm32 adc channel
322  * @type:       IIO channel type
323  * @channel:    channel number (single ended)
324  * @name:       channel name (single ended)
325  */
326 struct stm32_adc_chan_spec {
327         enum iio_chan_type      type;
328         int                     channel;
329         const char              *name;
330 };
331
332 /**
333  * struct stm32_adc_info - stm32 ADC, per instance config data
334  * @channels:           Reference to stm32 channels spec
335  * @max_channels:       Number of channels
336  * @resolutions:        available resolutions
337  * @num_res:            number of available resolutions
338  */
339 struct stm32_adc_info {
340         const struct stm32_adc_chan_spec *channels;
341         int max_channels;
342         const unsigned int *resolutions;
343         const unsigned int num_res;
344 };
345
346 /*
347  * Input definitions common for all instances:
348  * stm32f4 can have up to 16 channels
349  * stm32h7 can have up to 20 channels
350  */
351 static const struct stm32_adc_chan_spec stm32_adc_channels[] = {
352         { IIO_VOLTAGE, 0, "in0" },
353         { IIO_VOLTAGE, 1, "in1" },
354         { IIO_VOLTAGE, 2, "in2" },
355         { IIO_VOLTAGE, 3, "in3" },
356         { IIO_VOLTAGE, 4, "in4" },
357         { IIO_VOLTAGE, 5, "in5" },
358         { IIO_VOLTAGE, 6, "in6" },
359         { IIO_VOLTAGE, 7, "in7" },
360         { IIO_VOLTAGE, 8, "in8" },
361         { IIO_VOLTAGE, 9, "in9" },
362         { IIO_VOLTAGE, 10, "in10" },
363         { IIO_VOLTAGE, 11, "in11" },
364         { IIO_VOLTAGE, 12, "in12" },
365         { IIO_VOLTAGE, 13, "in13" },
366         { IIO_VOLTAGE, 14, "in14" },
367         { IIO_VOLTAGE, 15, "in15" },
368         { IIO_VOLTAGE, 16, "in16" },
369         { IIO_VOLTAGE, 17, "in17" },
370         { IIO_VOLTAGE, 18, "in18" },
371         { IIO_VOLTAGE, 19, "in19" },
372 };
373
374 static const unsigned int stm32f4_adc_resolutions[] = {
375         /* sorted values so the index matches RES[1:0] in STM32F4_ADC_CR1 */
376         12, 10, 8, 6,
377 };
378
379 static const struct stm32_adc_info stm32f4_adc_info = {
380         .channels = stm32_adc_channels,
381         .max_channels = 16,
382         .resolutions = stm32f4_adc_resolutions,
383         .num_res = ARRAY_SIZE(stm32f4_adc_resolutions),
384 };
385
386 static const unsigned int stm32h7_adc_resolutions[] = {
387         /* sorted values so the index matches RES[2:0] in STM32H7_ADC_CFGR */
388         16, 14, 12, 10, 8,
389 };
390
391 static const struct stm32_adc_info stm32h7_adc_info = {
392         .channels = stm32_adc_channels,
393         .max_channels = 20,
394         .resolutions = stm32h7_adc_resolutions,
395         .num_res = ARRAY_SIZE(stm32h7_adc_resolutions),
396 };
397
398 /**
399  * stm32f4_sq - describe regular sequence registers
400  * - L: sequence len (register & bit field)
401  * - SQ1..SQ16: sequence entries (register & bit field)
402  */
403 static const struct stm32_adc_regs stm32f4_sq[STM32_ADC_MAX_SQ + 1] = {
404         /* L: len bit field description to be kept as first element */
405         { STM32F4_ADC_SQR1, GENMASK(23, 20), 20 },
406         /* SQ1..SQ16 registers & bit fields (reg, mask, shift) */
407         { STM32F4_ADC_SQR3, GENMASK(4, 0), 0 },
408         { STM32F4_ADC_SQR3, GENMASK(9, 5), 5 },
409         { STM32F4_ADC_SQR3, GENMASK(14, 10), 10 },
410         { STM32F4_ADC_SQR3, GENMASK(19, 15), 15 },
411         { STM32F4_ADC_SQR3, GENMASK(24, 20), 20 },
412         { STM32F4_ADC_SQR3, GENMASK(29, 25), 25 },
413         { STM32F4_ADC_SQR2, GENMASK(4, 0), 0 },
414         { STM32F4_ADC_SQR2, GENMASK(9, 5), 5 },
415         { STM32F4_ADC_SQR2, GENMASK(14, 10), 10 },
416         { STM32F4_ADC_SQR2, GENMASK(19, 15), 15 },
417         { STM32F4_ADC_SQR2, GENMASK(24, 20), 20 },
418         { STM32F4_ADC_SQR2, GENMASK(29, 25), 25 },
419         { STM32F4_ADC_SQR1, GENMASK(4, 0), 0 },
420         { STM32F4_ADC_SQR1, GENMASK(9, 5), 5 },
421         { STM32F4_ADC_SQR1, GENMASK(14, 10), 10 },
422         { STM32F4_ADC_SQR1, GENMASK(19, 15), 15 },
423 };
424
425 /* STM32F4 external trigger sources for all instances */
426 static struct stm32_adc_trig_info stm32f4_adc_trigs[] = {
427         { TIM1_CH1, STM32_EXT0 },
428         { TIM1_CH2, STM32_EXT1 },
429         { TIM1_CH3, STM32_EXT2 },
430         { TIM2_CH2, STM32_EXT3 },
431         { TIM2_CH3, STM32_EXT4 },
432         { TIM2_CH4, STM32_EXT5 },
433         { TIM2_TRGO, STM32_EXT6 },
434         { TIM3_CH1, STM32_EXT7 },
435         { TIM3_TRGO, STM32_EXT8 },
436         { TIM4_CH4, STM32_EXT9 },
437         { TIM5_CH1, STM32_EXT10 },
438         { TIM5_CH2, STM32_EXT11 },
439         { TIM5_CH3, STM32_EXT12 },
440         { TIM8_CH1, STM32_EXT13 },
441         { TIM8_TRGO, STM32_EXT14 },
442         {}, /* sentinel */
443 };
444
445 /**
446  * stm32f4_smp_bits[] - describe sampling time register index & bit fields
447  * Sorted so it can be indexed by channel number.
448  */
449 static const struct stm32_adc_regs stm32f4_smp_bits[] = {
450         /* STM32F4_ADC_SMPR2: smpr[] index, mask, shift for SMP0 to SMP9 */
451         { 1, GENMASK(2, 0), 0 },
452         { 1, GENMASK(5, 3), 3 },
453         { 1, GENMASK(8, 6), 6 },
454         { 1, GENMASK(11, 9), 9 },
455         { 1, GENMASK(14, 12), 12 },
456         { 1, GENMASK(17, 15), 15 },
457         { 1, GENMASK(20, 18), 18 },
458         { 1, GENMASK(23, 21), 21 },
459         { 1, GENMASK(26, 24), 24 },
460         { 1, GENMASK(29, 27), 27 },
461         /* STM32F4_ADC_SMPR1, smpr[] index, mask, shift for SMP10 to SMP18 */
462         { 0, GENMASK(2, 0), 0 },
463         { 0, GENMASK(5, 3), 3 },
464         { 0, GENMASK(8, 6), 6 },
465         { 0, GENMASK(11, 9), 9 },
466         { 0, GENMASK(14, 12), 12 },
467         { 0, GENMASK(17, 15), 15 },
468         { 0, GENMASK(20, 18), 18 },
469         { 0, GENMASK(23, 21), 21 },
470         { 0, GENMASK(26, 24), 24 },
471 };
472
473 /* STM32F4 programmable sampling time (ADC clock cycles) */
474 static const unsigned int stm32f4_adc_smp_cycles[STM32_ADC_MAX_SMP + 1] = {
475         3, 15, 28, 56, 84, 112, 144, 480,
476 };
477
478 static const struct stm32_adc_regspec stm32f4_adc_regspec = {
479         .dr = STM32F4_ADC_DR,
480         .ier_eoc = { STM32F4_ADC_CR1, STM32F4_EOCIE },
481         .isr_eoc = { STM32F4_ADC_SR, STM32F4_EOC },
482         .sqr = stm32f4_sq,
483         .exten = { STM32F4_ADC_CR2, STM32F4_EXTEN_MASK, STM32F4_EXTEN_SHIFT },
484         .extsel = { STM32F4_ADC_CR2, STM32F4_EXTSEL_MASK,
485                     STM32F4_EXTSEL_SHIFT },
486         .res = { STM32F4_ADC_CR1, STM32F4_RES_MASK, STM32F4_RES_SHIFT },
487         .smpr = { STM32F4_ADC_SMPR1, STM32F4_ADC_SMPR2 },
488         .smp_bits = stm32f4_smp_bits,
489 };
490
491 static const struct stm32_adc_regs stm32h7_sq[STM32_ADC_MAX_SQ + 1] = {
492         /* L: len bit field description to be kept as first element */
493         { STM32H7_ADC_SQR1, GENMASK(3, 0), 0 },
494         /* SQ1..SQ16 registers & bit fields (reg, mask, shift) */
495         { STM32H7_ADC_SQR1, GENMASK(10, 6), 6 },
496         { STM32H7_ADC_SQR1, GENMASK(16, 12), 12 },
497         { STM32H7_ADC_SQR1, GENMASK(22, 18), 18 },
498         { STM32H7_ADC_SQR1, GENMASK(28, 24), 24 },
499         { STM32H7_ADC_SQR2, GENMASK(4, 0), 0 },
500         { STM32H7_ADC_SQR2, GENMASK(10, 6), 6 },
501         { STM32H7_ADC_SQR2, GENMASK(16, 12), 12 },
502         { STM32H7_ADC_SQR2, GENMASK(22, 18), 18 },
503         { STM32H7_ADC_SQR2, GENMASK(28, 24), 24 },
504         { STM32H7_ADC_SQR3, GENMASK(4, 0), 0 },
505         { STM32H7_ADC_SQR3, GENMASK(10, 6), 6 },
506         { STM32H7_ADC_SQR3, GENMASK(16, 12), 12 },
507         { STM32H7_ADC_SQR3, GENMASK(22, 18), 18 },
508         { STM32H7_ADC_SQR3, GENMASK(28, 24), 24 },
509         { STM32H7_ADC_SQR4, GENMASK(4, 0), 0 },
510         { STM32H7_ADC_SQR4, GENMASK(10, 6), 6 },
511 };
512
513 /* STM32H7 external trigger sources for all instances */
514 static struct stm32_adc_trig_info stm32h7_adc_trigs[] = {
515         { TIM1_CH1, STM32_EXT0 },
516         { TIM1_CH2, STM32_EXT1 },
517         { TIM1_CH3, STM32_EXT2 },
518         { TIM2_CH2, STM32_EXT3 },
519         { TIM3_TRGO, STM32_EXT4 },
520         { TIM4_CH4, STM32_EXT5 },
521         { TIM8_TRGO, STM32_EXT7 },
522         { TIM8_TRGO2, STM32_EXT8 },
523         { TIM1_TRGO, STM32_EXT9 },
524         { TIM1_TRGO2, STM32_EXT10 },
525         { TIM2_TRGO, STM32_EXT11 },
526         { TIM4_TRGO, STM32_EXT12 },
527         { TIM6_TRGO, STM32_EXT13 },
528         { TIM3_CH4, STM32_EXT15 },
529         {},
530 };
531
532 /**
533  * stm32h7_smp_bits - describe sampling time register index & bit fields
534  * Sorted so it can be indexed by channel number.
535  */
536 static const struct stm32_adc_regs stm32h7_smp_bits[] = {
537         /* STM32H7_ADC_SMPR1, smpr[] index, mask, shift for SMP0 to SMP9 */
538         { 0, GENMASK(2, 0), 0 },
539         { 0, GENMASK(5, 3), 3 },
540         { 0, GENMASK(8, 6), 6 },
541         { 0, GENMASK(11, 9), 9 },
542         { 0, GENMASK(14, 12), 12 },
543         { 0, GENMASK(17, 15), 15 },
544         { 0, GENMASK(20, 18), 18 },
545         { 0, GENMASK(23, 21), 21 },
546         { 0, GENMASK(26, 24), 24 },
547         { 0, GENMASK(29, 27), 27 },
548         /* STM32H7_ADC_SMPR2, smpr[] index, mask, shift for SMP10 to SMP19 */
549         { 1, GENMASK(2, 0), 0 },
550         { 1, GENMASK(5, 3), 3 },
551         { 1, GENMASK(8, 6), 6 },
552         { 1, GENMASK(11, 9), 9 },
553         { 1, GENMASK(14, 12), 12 },
554         { 1, GENMASK(17, 15), 15 },
555         { 1, GENMASK(20, 18), 18 },
556         { 1, GENMASK(23, 21), 21 },
557         { 1, GENMASK(26, 24), 24 },
558         { 1, GENMASK(29, 27), 27 },
559 };
560
561 /* STM32H7 programmable sampling time (ADC clock cycles, rounded down) */
562 static const unsigned int stm32h7_adc_smp_cycles[STM32_ADC_MAX_SMP + 1] = {
563         1, 2, 8, 16, 32, 64, 387, 810,
564 };
565
566 static const struct stm32_adc_regspec stm32h7_adc_regspec = {
567         .dr = STM32H7_ADC_DR,
568         .ier_eoc = { STM32H7_ADC_IER, STM32H7_EOCIE },
569         .isr_eoc = { STM32H7_ADC_ISR, STM32H7_EOC },
570         .sqr = stm32h7_sq,
571         .exten = { STM32H7_ADC_CFGR, STM32H7_EXTEN_MASK, STM32H7_EXTEN_SHIFT },
572         .extsel = { STM32H7_ADC_CFGR, STM32H7_EXTSEL_MASK,
573                     STM32H7_EXTSEL_SHIFT },
574         .res = { STM32H7_ADC_CFGR, STM32H7_RES_MASK, STM32H7_RES_SHIFT },
575         .smpr = { STM32H7_ADC_SMPR1, STM32H7_ADC_SMPR2 },
576         .smp_bits = stm32h7_smp_bits,
577 };
578
579 /**
580  * STM32 ADC registers access routines
581  * @adc: stm32 adc instance
582  * @reg: reg offset in adc instance
583  *
584  * Note: All instances share same base, with 0x0, 0x100 or 0x200 offset resp.
585  * for adc1, adc2 and adc3.
586  */
587 static u32 stm32_adc_readl(struct stm32_adc *adc, u32 reg)
588 {
589         return readl_relaxed(adc->common->base + adc->offset + reg);
590 }
591
592 #define stm32_adc_readl_addr(addr)      stm32_adc_readl(adc, addr)
593
594 #define stm32_adc_readl_poll_timeout(reg, val, cond, sleep_us, timeout_us) \
595         readx_poll_timeout(stm32_adc_readl_addr, reg, val, \
596                            cond, sleep_us, timeout_us)
597
598 static u16 stm32_adc_readw(struct stm32_adc *adc, u32 reg)
599 {
600         return readw_relaxed(adc->common->base + adc->offset + reg);
601 }
602
603 static void stm32_adc_writel(struct stm32_adc *adc, u32 reg, u32 val)
604 {
605         writel_relaxed(val, adc->common->base + adc->offset + reg);
606 }
607
608 static void stm32_adc_set_bits(struct stm32_adc *adc, u32 reg, u32 bits)
609 {
610         unsigned long flags;
611
612         spin_lock_irqsave(&adc->lock, flags);
613         stm32_adc_writel(adc, reg, stm32_adc_readl(adc, reg) | bits);
614         spin_unlock_irqrestore(&adc->lock, flags);
615 }
616
617 static void stm32_adc_clr_bits(struct stm32_adc *adc, u32 reg, u32 bits)
618 {
619         unsigned long flags;
620
621         spin_lock_irqsave(&adc->lock, flags);
622         stm32_adc_writel(adc, reg, stm32_adc_readl(adc, reg) & ~bits);
623         spin_unlock_irqrestore(&adc->lock, flags);
624 }
625
626 /**
627  * stm32_adc_conv_irq_enable() - Enable end of conversion interrupt
628  * @adc: stm32 adc instance
629  */
630 static void stm32_adc_conv_irq_enable(struct stm32_adc *adc)
631 {
632         stm32_adc_set_bits(adc, adc->cfg->regs->ier_eoc.reg,
633                            adc->cfg->regs->ier_eoc.mask);
634 };
635
636 /**
637  * stm32_adc_conv_irq_disable() - Disable end of conversion interrupt
638  * @adc: stm32 adc instance
639  */
640 static void stm32_adc_conv_irq_disable(struct stm32_adc *adc)
641 {
642         stm32_adc_clr_bits(adc, adc->cfg->regs->ier_eoc.reg,
643                            adc->cfg->regs->ier_eoc.mask);
644 }
645
646 static void stm32_adc_set_res(struct stm32_adc *adc)
647 {
648         const struct stm32_adc_regs *res = &adc->cfg->regs->res;
649         u32 val;
650
651         val = stm32_adc_readl(adc, res->reg);
652         val = (val & ~res->mask) | (adc->res << res->shift);
653         stm32_adc_writel(adc, res->reg, val);
654 }
655
656 /**
657  * stm32f4_adc_start_conv() - Start conversions for regular channels.
658  * @adc: stm32 adc instance
659  * @dma: use dma to transfer conversion result
660  *
661  * Start conversions for regular channels.
662  * Also take care of normal or DMA mode. Circular DMA may be used for regular
663  * conversions, in IIO buffer modes. Otherwise, use ADC interrupt with direct
664  * DR read instead (e.g. read_raw, or triggered buffer mode without DMA).
665  */
666 static void stm32f4_adc_start_conv(struct stm32_adc *adc, bool dma)
667 {
668         stm32_adc_set_bits(adc, STM32F4_ADC_CR1, STM32F4_SCAN);
669
670         if (dma)
671                 stm32_adc_set_bits(adc, STM32F4_ADC_CR2,
672                                    STM32F4_DMA | STM32F4_DDS);
673
674         stm32_adc_set_bits(adc, STM32F4_ADC_CR2, STM32F4_EOCS | STM32F4_ADON);
675
676         /* Wait for Power-up time (tSTAB from datasheet) */
677         usleep_range(2, 3);
678
679         /* Software start ? (e.g. trigger detection disabled ?) */
680         if (!(stm32_adc_readl(adc, STM32F4_ADC_CR2) & STM32F4_EXTEN_MASK))
681                 stm32_adc_set_bits(adc, STM32F4_ADC_CR2, STM32F4_SWSTART);
682 }
683
684 static void stm32f4_adc_stop_conv(struct stm32_adc *adc)
685 {
686         stm32_adc_clr_bits(adc, STM32F4_ADC_CR2, STM32F4_EXTEN_MASK);
687         stm32_adc_clr_bits(adc, STM32F4_ADC_SR, STM32F4_STRT);
688
689         stm32_adc_clr_bits(adc, STM32F4_ADC_CR1, STM32F4_SCAN);
690         stm32_adc_clr_bits(adc, STM32F4_ADC_CR2,
691                            STM32F4_ADON | STM32F4_DMA | STM32F4_DDS);
692 }
693
694 static void stm32h7_adc_start_conv(struct stm32_adc *adc, bool dma)
695 {
696         enum stm32h7_adc_dmngt dmngt;
697         unsigned long flags;
698         u32 val;
699
700         if (dma)
701                 dmngt = STM32H7_DMNGT_DMA_CIRC;
702         else
703                 dmngt = STM32H7_DMNGT_DR_ONLY;
704
705         spin_lock_irqsave(&adc->lock, flags);
706         val = stm32_adc_readl(adc, STM32H7_ADC_CFGR);
707         val = (val & ~STM32H7_DMNGT_MASK) | (dmngt << STM32H7_DMNGT_SHIFT);
708         stm32_adc_writel(adc, STM32H7_ADC_CFGR, val);
709         spin_unlock_irqrestore(&adc->lock, flags);
710
711         stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADSTART);
712 }
713
714 static void stm32h7_adc_stop_conv(struct stm32_adc *adc)
715 {
716         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
717         int ret;
718         u32 val;
719
720         stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADSTP);
721
722         ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
723                                            !(val & (STM32H7_ADSTART)),
724                                            100, STM32_ADC_TIMEOUT_US);
725         if (ret)
726                 dev_warn(&indio_dev->dev, "stop failed\n");
727
728         stm32_adc_clr_bits(adc, STM32H7_ADC_CFGR, STM32H7_DMNGT_MASK);
729 }
730
731 static void stm32h7_adc_exit_pwr_down(struct stm32_adc *adc)
732 {
733         /* Exit deep power down, then enable ADC voltage regulator */
734         stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_DEEPPWD);
735         stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADVREGEN);
736
737         if (adc->common->rate > STM32H7_BOOST_CLKRATE)
738                 stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_BOOST);
739
740         /* Wait for startup time */
741         usleep_range(10, 20);
742 }
743
744 static void stm32h7_adc_enter_pwr_down(struct stm32_adc *adc)
745 {
746         stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_BOOST);
747
748         /* Setting DEEPPWD disables ADC vreg and clears ADVREGEN */
749         stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_DEEPPWD);
750 }
751
752 static int stm32h7_adc_enable(struct stm32_adc *adc)
753 {
754         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
755         int ret;
756         u32 val;
757
758         /* Clear ADRDY by writing one, then enable ADC */
759         stm32_adc_set_bits(adc, STM32H7_ADC_ISR, STM32H7_ADRDY);
760         stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADEN);
761
762         /* Poll for ADRDY to be set (after adc startup time) */
763         ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_ISR, val,
764                                            val & STM32H7_ADRDY,
765                                            100, STM32_ADC_TIMEOUT_US);
766         if (ret) {
767                 stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_ADEN);
768                 dev_err(&indio_dev->dev, "Failed to enable ADC\n");
769         }
770
771         return ret;
772 }
773
774 static void stm32h7_adc_disable(struct stm32_adc *adc)
775 {
776         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
777         int ret;
778         u32 val;
779
780         /* Disable ADC and wait until it's effectively disabled */
781         stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADDIS);
782         ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
783                                            !(val & STM32H7_ADEN), 100,
784                                            STM32_ADC_TIMEOUT_US);
785         if (ret)
786                 dev_warn(&indio_dev->dev, "Failed to disable\n");
787 }
788
789 /**
790  * stm32h7_adc_read_selfcalib() - read calibration shadow regs, save result
791  * @adc: stm32 adc instance
792  */
793 static int stm32h7_adc_read_selfcalib(struct stm32_adc *adc)
794 {
795         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
796         int i, ret;
797         u32 lincalrdyw_mask, val;
798
799         /* Enable adc so LINCALRDYW1..6 bits are writable */
800         ret = stm32h7_adc_enable(adc);
801         if (ret)
802                 return ret;
803
804         /* Read linearity calibration */
805         lincalrdyw_mask = STM32H7_LINCALRDYW6;
806         for (i = STM32H7_LINCALFACT_NUM - 1; i >= 0; i--) {
807                 /* Clear STM32H7_LINCALRDYW[6..1]: transfer calib to CALFACT2 */
808                 stm32_adc_clr_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
809
810                 /* Poll: wait calib data to be ready in CALFACT2 register */
811                 ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
812                                                    !(val & lincalrdyw_mask),
813                                                    100, STM32_ADC_TIMEOUT_US);
814                 if (ret) {
815                         dev_err(&indio_dev->dev, "Failed to read calfact\n");
816                         goto disable;
817                 }
818
819                 val = stm32_adc_readl(adc, STM32H7_ADC_CALFACT2);
820                 adc->cal.lincalfact[i] = (val & STM32H7_LINCALFACT_MASK);
821                 adc->cal.lincalfact[i] >>= STM32H7_LINCALFACT_SHIFT;
822
823                 lincalrdyw_mask >>= 1;
824         }
825
826         /* Read offset calibration */
827         val = stm32_adc_readl(adc, STM32H7_ADC_CALFACT);
828         adc->cal.calfact_s = (val & STM32H7_CALFACT_S_MASK);
829         adc->cal.calfact_s >>= STM32H7_CALFACT_S_SHIFT;
830         adc->cal.calfact_d = (val & STM32H7_CALFACT_D_MASK);
831         adc->cal.calfact_d >>= STM32H7_CALFACT_D_SHIFT;
832
833 disable:
834         stm32h7_adc_disable(adc);
835
836         return ret;
837 }
838
839 /**
840  * stm32h7_adc_restore_selfcalib() - Restore saved self-calibration result
841  * @adc: stm32 adc instance
842  * Note: ADC must be enabled, with no on-going conversions.
843  */
844 static int stm32h7_adc_restore_selfcalib(struct stm32_adc *adc)
845 {
846         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
847         int i, ret;
848         u32 lincalrdyw_mask, val;
849
850         val = (adc->cal.calfact_s << STM32H7_CALFACT_S_SHIFT) |
851                 (adc->cal.calfact_d << STM32H7_CALFACT_D_SHIFT);
852         stm32_adc_writel(adc, STM32H7_ADC_CALFACT, val);
853
854         lincalrdyw_mask = STM32H7_LINCALRDYW6;
855         for (i = STM32H7_LINCALFACT_NUM - 1; i >= 0; i--) {
856                 /*
857                  * Write saved calibration data to shadow registers:
858                  * Write CALFACT2, and set LINCALRDYW[6..1] bit to trigger
859                  * data write. Then poll to wait for complete transfer.
860                  */
861                 val = adc->cal.lincalfact[i] << STM32H7_LINCALFACT_SHIFT;
862                 stm32_adc_writel(adc, STM32H7_ADC_CALFACT2, val);
863                 stm32_adc_set_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
864                 ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
865                                                    val & lincalrdyw_mask,
866                                                    100, STM32_ADC_TIMEOUT_US);
867                 if (ret) {
868                         dev_err(&indio_dev->dev, "Failed to write calfact\n");
869                         return ret;
870                 }
871
872                 /*
873                  * Read back calibration data, has two effects:
874                  * - It ensures bits LINCALRDYW[6..1] are kept cleared
875                  *   for next time calibration needs to be restored.
876                  * - BTW, bit clear triggers a read, then check data has been
877                  *   correctly written.
878                  */
879                 stm32_adc_clr_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
880                 ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
881                                                    !(val & lincalrdyw_mask),
882                                                    100, STM32_ADC_TIMEOUT_US);
883                 if (ret) {
884                         dev_err(&indio_dev->dev, "Failed to read calfact\n");
885                         return ret;
886                 }
887                 val = stm32_adc_readl(adc, STM32H7_ADC_CALFACT2);
888                 if (val != adc->cal.lincalfact[i] << STM32H7_LINCALFACT_SHIFT) {
889                         dev_err(&indio_dev->dev, "calfact not consistent\n");
890                         return -EIO;
891                 }
892
893                 lincalrdyw_mask >>= 1;
894         }
895
896         return 0;
897 }
898
899 /**
900  * Fixed timeout value for ADC calibration.
901  * worst cases:
902  * - low clock frequency
903  * - maximum prescalers
904  * Calibration requires:
905  * - 131,072 ADC clock cycle for the linear calibration
906  * - 20 ADC clock cycle for the offset calibration
907  *
908  * Set to 100ms for now
909  */
910 #define STM32H7_ADC_CALIB_TIMEOUT_US            100000
911
912 /**
913  * stm32h7_adc_selfcalib() - Procedure to calibrate ADC (from power down)
914  * @adc: stm32 adc instance
915  * Exit from power down, calibrate ADC, then return to power down.
916  */
917 static int stm32h7_adc_selfcalib(struct stm32_adc *adc)
918 {
919         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
920         int ret;
921         u32 val;
922
923         stm32h7_adc_exit_pwr_down(adc);
924
925         /*
926          * Select calibration mode:
927          * - Offset calibration for single ended inputs
928          * - No linearity calibration (do it later, before reading it)
929          */
930         stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_ADCALDIF);
931         stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_ADCALLIN);
932
933         /* Start calibration, then wait for completion */
934         stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADCAL);
935         ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
936                                            !(val & STM32H7_ADCAL), 100,
937                                            STM32H7_ADC_CALIB_TIMEOUT_US);
938         if (ret) {
939                 dev_err(&indio_dev->dev, "calibration failed\n");
940                 goto pwr_dwn;
941         }
942
943         /*
944          * Select calibration mode, then start calibration:
945          * - Offset calibration for differential input
946          * - Linearity calibration (needs to be done only once for single/diff)
947          *   will run simultaneously with offset calibration.
948          */
949         stm32_adc_set_bits(adc, STM32H7_ADC_CR,
950                            STM32H7_ADCALDIF | STM32H7_ADCALLIN);
951         stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADCAL);
952         ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
953                                            !(val & STM32H7_ADCAL), 100,
954                                            STM32H7_ADC_CALIB_TIMEOUT_US);
955         if (ret) {
956                 dev_err(&indio_dev->dev, "calibration failed\n");
957                 goto pwr_dwn;
958         }
959
960         stm32_adc_clr_bits(adc, STM32H7_ADC_CR,
961                            STM32H7_ADCALDIF | STM32H7_ADCALLIN);
962
963         /* Read calibration result for future reference */
964         ret = stm32h7_adc_read_selfcalib(adc);
965
966 pwr_dwn:
967         stm32h7_adc_enter_pwr_down(adc);
968
969         return ret;
970 }
971
972 /**
973  * stm32h7_adc_prepare() - Leave power down mode to enable ADC.
974  * @adc: stm32 adc instance
975  * Leave power down mode.
976  * Enable ADC.
977  * Restore calibration data.
978  * Pre-select channels that may be used in PCSEL (required by input MUX / IO).
979  */
980 static int stm32h7_adc_prepare(struct stm32_adc *adc)
981 {
982         int ret;
983
984         stm32h7_adc_exit_pwr_down(adc);
985
986         ret = stm32h7_adc_enable(adc);
987         if (ret)
988                 goto pwr_dwn;
989
990         ret = stm32h7_adc_restore_selfcalib(adc);
991         if (ret)
992                 goto disable;
993
994         stm32_adc_writel(adc, STM32H7_ADC_PCSEL, adc->pcsel);
995
996         return 0;
997
998 disable:
999         stm32h7_adc_disable(adc);
1000 pwr_dwn:
1001         stm32h7_adc_enter_pwr_down(adc);
1002
1003         return ret;
1004 }
1005
1006 static void stm32h7_adc_unprepare(struct stm32_adc *adc)
1007 {
1008         stm32h7_adc_disable(adc);
1009         stm32h7_adc_enter_pwr_down(adc);
1010 }
1011
1012 /**
1013  * stm32_adc_conf_scan_seq() - Build regular channels scan sequence
1014  * @indio_dev: IIO device
1015  * @scan_mask: channels to be converted
1016  *
1017  * Conversion sequence :
1018  * Apply sampling time settings for all channels.
1019  * Configure ADC scan sequence based on selected channels in scan_mask.
1020  * Add channels to SQR registers, from scan_mask LSB to MSB, then
1021  * program sequence len.
1022  */
1023 static int stm32_adc_conf_scan_seq(struct iio_dev *indio_dev,
1024                                    const unsigned long *scan_mask)
1025 {
1026         struct stm32_adc *adc = iio_priv(indio_dev);
1027         const struct stm32_adc_regs *sqr = adc->cfg->regs->sqr;
1028         const struct iio_chan_spec *chan;
1029         u32 val, bit;
1030         int i = 0;
1031
1032         /* Apply sampling time settings */
1033         stm32_adc_writel(adc, adc->cfg->regs->smpr[0], adc->smpr_val[0]);
1034         stm32_adc_writel(adc, adc->cfg->regs->smpr[1], adc->smpr_val[1]);
1035
1036         for_each_set_bit(bit, scan_mask, indio_dev->masklength) {
1037                 chan = indio_dev->channels + bit;
1038                 /*
1039                  * Assign one channel per SQ entry in regular
1040                  * sequence, starting with SQ1.
1041                  */
1042                 i++;
1043                 if (i > STM32_ADC_MAX_SQ)
1044                         return -EINVAL;
1045
1046                 dev_dbg(&indio_dev->dev, "%s chan %d to SQ%d\n",
1047                         __func__, chan->channel, i);
1048
1049                 val = stm32_adc_readl(adc, sqr[i].reg);
1050                 val &= ~sqr[i].mask;
1051                 val |= chan->channel << sqr[i].shift;
1052                 stm32_adc_writel(adc, sqr[i].reg, val);
1053         }
1054
1055         if (!i)
1056                 return -EINVAL;
1057
1058         /* Sequence len */
1059         val = stm32_adc_readl(adc, sqr[0].reg);
1060         val &= ~sqr[0].mask;
1061         val |= ((i - 1) << sqr[0].shift);
1062         stm32_adc_writel(adc, sqr[0].reg, val);
1063
1064         return 0;
1065 }
1066
1067 /**
1068  * stm32_adc_get_trig_extsel() - Get external trigger selection
1069  * @trig: trigger
1070  *
1071  * Returns trigger extsel value, if trig matches, -EINVAL otherwise.
1072  */
1073 static int stm32_adc_get_trig_extsel(struct iio_dev *indio_dev,
1074                                      struct iio_trigger *trig)
1075 {
1076         struct stm32_adc *adc = iio_priv(indio_dev);
1077         int i;
1078
1079         /* lookup triggers registered by stm32 timer trigger driver */
1080         for (i = 0; adc->cfg->trigs[i].name; i++) {
1081                 /**
1082                  * Checking both stm32 timer trigger type and trig name
1083                  * should be safe against arbitrary trigger names.
1084                  */
1085                 if (is_stm32_timer_trigger(trig) &&
1086                     !strcmp(adc->cfg->trigs[i].name, trig->name)) {
1087                         return adc->cfg->trigs[i].extsel;
1088                 }
1089         }
1090
1091         return -EINVAL;
1092 }
1093
1094 /**
1095  * stm32_adc_set_trig() - Set a regular trigger
1096  * @indio_dev: IIO device
1097  * @trig: IIO trigger
1098  *
1099  * Set trigger source/polarity (e.g. SW, or HW with polarity) :
1100  * - if HW trigger disabled (e.g. trig == NULL, conversion launched by sw)
1101  * - if HW trigger enabled, set source & polarity
1102  */
1103 static int stm32_adc_set_trig(struct iio_dev *indio_dev,
1104                               struct iio_trigger *trig)
1105 {
1106         struct stm32_adc *adc = iio_priv(indio_dev);
1107         u32 val, extsel = 0, exten = STM32_EXTEN_SWTRIG;
1108         unsigned long flags;
1109         int ret;
1110
1111         if (trig) {
1112                 ret = stm32_adc_get_trig_extsel(indio_dev, trig);
1113                 if (ret < 0)
1114                         return ret;
1115
1116                 /* set trigger source and polarity (default to rising edge) */
1117                 extsel = ret;
1118                 exten = adc->trigger_polarity + STM32_EXTEN_HWTRIG_RISING_EDGE;
1119         }
1120
1121         spin_lock_irqsave(&adc->lock, flags);
1122         val = stm32_adc_readl(adc, adc->cfg->regs->exten.reg);
1123         val &= ~(adc->cfg->regs->exten.mask | adc->cfg->regs->extsel.mask);
1124         val |= exten << adc->cfg->regs->exten.shift;
1125         val |= extsel << adc->cfg->regs->extsel.shift;
1126         stm32_adc_writel(adc,  adc->cfg->regs->exten.reg, val);
1127         spin_unlock_irqrestore(&adc->lock, flags);
1128
1129         return 0;
1130 }
1131
1132 static int stm32_adc_set_trig_pol(struct iio_dev *indio_dev,
1133                                   const struct iio_chan_spec *chan,
1134                                   unsigned int type)
1135 {
1136         struct stm32_adc *adc = iio_priv(indio_dev);
1137
1138         adc->trigger_polarity = type;
1139
1140         return 0;
1141 }
1142
1143 static int stm32_adc_get_trig_pol(struct iio_dev *indio_dev,
1144                                   const struct iio_chan_spec *chan)
1145 {
1146         struct stm32_adc *adc = iio_priv(indio_dev);
1147
1148         return adc->trigger_polarity;
1149 }
1150
1151 static const char * const stm32_trig_pol_items[] = {
1152         "rising-edge", "falling-edge", "both-edges",
1153 };
1154
1155 static const struct iio_enum stm32_adc_trig_pol = {
1156         .items = stm32_trig_pol_items,
1157         .num_items = ARRAY_SIZE(stm32_trig_pol_items),
1158         .get = stm32_adc_get_trig_pol,
1159         .set = stm32_adc_set_trig_pol,
1160 };
1161
1162 /**
1163  * stm32_adc_single_conv() - Performs a single conversion
1164  * @indio_dev: IIO device
1165  * @chan: IIO channel
1166  * @res: conversion result
1167  *
1168  * The function performs a single conversion on a given channel:
1169  * - Apply sampling time settings
1170  * - Program sequencer with one channel (e.g. in SQ1 with len = 1)
1171  * - Use SW trigger
1172  * - Start conversion, then wait for interrupt completion.
1173  */
1174 static int stm32_adc_single_conv(struct iio_dev *indio_dev,
1175                                  const struct iio_chan_spec *chan,
1176                                  int *res)
1177 {
1178         struct stm32_adc *adc = iio_priv(indio_dev);
1179         const struct stm32_adc_regspec *regs = adc->cfg->regs;
1180         long timeout;
1181         u32 val;
1182         int ret;
1183
1184         reinit_completion(&adc->completion);
1185
1186         adc->bufi = 0;
1187
1188         if (adc->cfg->prepare) {
1189                 ret = adc->cfg->prepare(adc);
1190                 if (ret)
1191                         return ret;
1192         }
1193
1194         /* Apply sampling time settings */
1195         stm32_adc_writel(adc, regs->smpr[0], adc->smpr_val[0]);
1196         stm32_adc_writel(adc, regs->smpr[1], adc->smpr_val[1]);
1197
1198         /* Program chan number in regular sequence (SQ1) */
1199         val = stm32_adc_readl(adc, regs->sqr[1].reg);
1200         val &= ~regs->sqr[1].mask;
1201         val |= chan->channel << regs->sqr[1].shift;
1202         stm32_adc_writel(adc, regs->sqr[1].reg, val);
1203
1204         /* Set regular sequence len (0 for 1 conversion) */
1205         stm32_adc_clr_bits(adc, regs->sqr[0].reg, regs->sqr[0].mask);
1206
1207         /* Trigger detection disabled (conversion can be launched in SW) */
1208         stm32_adc_clr_bits(adc, regs->exten.reg, regs->exten.mask);
1209
1210         stm32_adc_conv_irq_enable(adc);
1211
1212         adc->cfg->start_conv(adc, false);
1213
1214         timeout = wait_for_completion_interruptible_timeout(
1215                                         &adc->completion, STM32_ADC_TIMEOUT);
1216         if (timeout == 0) {
1217                 ret = -ETIMEDOUT;
1218         } else if (timeout < 0) {
1219                 ret = timeout;
1220         } else {
1221                 *res = adc->buffer[0];
1222                 ret = IIO_VAL_INT;
1223         }
1224
1225         adc->cfg->stop_conv(adc);
1226
1227         stm32_adc_conv_irq_disable(adc);
1228
1229         if (adc->cfg->unprepare)
1230                 adc->cfg->unprepare(adc);
1231
1232         return ret;
1233 }
1234
1235 static int stm32_adc_read_raw(struct iio_dev *indio_dev,
1236                               struct iio_chan_spec const *chan,
1237                               int *val, int *val2, long mask)
1238 {
1239         struct stm32_adc *adc = iio_priv(indio_dev);
1240         int ret;
1241
1242         switch (mask) {
1243         case IIO_CHAN_INFO_RAW:
1244                 ret = iio_device_claim_direct_mode(indio_dev);
1245                 if (ret)
1246                         return ret;
1247                 if (chan->type == IIO_VOLTAGE)
1248                         ret = stm32_adc_single_conv(indio_dev, chan, val);
1249                 else
1250                         ret = -EINVAL;
1251                 iio_device_release_direct_mode(indio_dev);
1252                 return ret;
1253
1254         case IIO_CHAN_INFO_SCALE:
1255                 *val = adc->common->vref_mv;
1256                 *val2 = chan->scan_type.realbits;
1257                 return IIO_VAL_FRACTIONAL_LOG2;
1258
1259         default:
1260                 return -EINVAL;
1261         }
1262 }
1263
1264 static irqreturn_t stm32_adc_isr(int irq, void *data)
1265 {
1266         struct stm32_adc *adc = data;
1267         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1268         const struct stm32_adc_regspec *regs = adc->cfg->regs;
1269         u32 status = stm32_adc_readl(adc, regs->isr_eoc.reg);
1270
1271         if (status & regs->isr_eoc.mask) {
1272                 /* Reading DR also clears EOC status flag */
1273                 adc->buffer[adc->bufi] = stm32_adc_readw(adc, regs->dr);
1274                 if (iio_buffer_enabled(indio_dev)) {
1275                         adc->bufi++;
1276                         if (adc->bufi >= adc->num_conv) {
1277                                 stm32_adc_conv_irq_disable(adc);
1278                                 iio_trigger_poll(indio_dev->trig);
1279                         }
1280                 } else {
1281                         complete(&adc->completion);
1282                 }
1283                 return IRQ_HANDLED;
1284         }
1285
1286         return IRQ_NONE;
1287 }
1288
1289 /**
1290  * stm32_adc_validate_trigger() - validate trigger for stm32 adc
1291  * @indio_dev: IIO device
1292  * @trig: new trigger
1293  *
1294  * Returns: 0 if trig matches one of the triggers registered by stm32 adc
1295  * driver, -EINVAL otherwise.
1296  */
1297 static int stm32_adc_validate_trigger(struct iio_dev *indio_dev,
1298                                       struct iio_trigger *trig)
1299 {
1300         return stm32_adc_get_trig_extsel(indio_dev, trig) < 0 ? -EINVAL : 0;
1301 }
1302
1303 static int stm32_adc_set_watermark(struct iio_dev *indio_dev, unsigned int val)
1304 {
1305         struct stm32_adc *adc = iio_priv(indio_dev);
1306         unsigned int watermark = STM32_DMA_BUFFER_SIZE / 2;
1307
1308         /*
1309          * dma cyclic transfers are used, buffer is split into two periods.
1310          * There should be :
1311          * - always one buffer (period) dma is working on
1312          * - one buffer (period) driver can push with iio_trigger_poll().
1313          */
1314         watermark = min(watermark, val * (unsigned)(sizeof(u16)));
1315         adc->rx_buf_sz = watermark * 2;
1316
1317         return 0;
1318 }
1319
1320 static int stm32_adc_update_scan_mode(struct iio_dev *indio_dev,
1321                                       const unsigned long *scan_mask)
1322 {
1323         struct stm32_adc *adc = iio_priv(indio_dev);
1324         int ret;
1325
1326         adc->num_conv = bitmap_weight(scan_mask, indio_dev->masklength);
1327
1328         ret = stm32_adc_conf_scan_seq(indio_dev, scan_mask);
1329         if (ret)
1330                 return ret;
1331
1332         return 0;
1333 }
1334
1335 static int stm32_adc_of_xlate(struct iio_dev *indio_dev,
1336                               const struct of_phandle_args *iiospec)
1337 {
1338         int i;
1339
1340         for (i = 0; i < indio_dev->num_channels; i++)
1341                 if (indio_dev->channels[i].channel == iiospec->args[0])
1342                         return i;
1343
1344         return -EINVAL;
1345 }
1346
1347 /**
1348  * stm32_adc_debugfs_reg_access - read or write register value
1349  *
1350  * To read a value from an ADC register:
1351  *   echo [ADC reg offset] > direct_reg_access
1352  *   cat direct_reg_access
1353  *
1354  * To write a value in a ADC register:
1355  *   echo [ADC_reg_offset] [value] > direct_reg_access
1356  */
1357 static int stm32_adc_debugfs_reg_access(struct iio_dev *indio_dev,
1358                                         unsigned reg, unsigned writeval,
1359                                         unsigned *readval)
1360 {
1361         struct stm32_adc *adc = iio_priv(indio_dev);
1362
1363         if (!readval)
1364                 stm32_adc_writel(adc, reg, writeval);
1365         else
1366                 *readval = stm32_adc_readl(adc, reg);
1367
1368         return 0;
1369 }
1370
1371 static const struct iio_info stm32_adc_iio_info = {
1372         .read_raw = stm32_adc_read_raw,
1373         .validate_trigger = stm32_adc_validate_trigger,
1374         .hwfifo_set_watermark = stm32_adc_set_watermark,
1375         .update_scan_mode = stm32_adc_update_scan_mode,
1376         .debugfs_reg_access = stm32_adc_debugfs_reg_access,
1377         .of_xlate = stm32_adc_of_xlate,
1378         .driver_module = THIS_MODULE,
1379 };
1380
1381 static unsigned int stm32_adc_dma_residue(struct stm32_adc *adc)
1382 {
1383         struct dma_tx_state state;
1384         enum dma_status status;
1385
1386         status = dmaengine_tx_status(adc->dma_chan,
1387                                      adc->dma_chan->cookie,
1388                                      &state);
1389         if (status == DMA_IN_PROGRESS) {
1390                 /* Residue is size in bytes from end of buffer */
1391                 unsigned int i = adc->rx_buf_sz - state.residue;
1392                 unsigned int size;
1393
1394                 /* Return available bytes */
1395                 if (i >= adc->bufi)
1396                         size = i - adc->bufi;
1397                 else
1398                         size = adc->rx_buf_sz + i - adc->bufi;
1399
1400                 return size;
1401         }
1402
1403         return 0;
1404 }
1405
1406 static void stm32_adc_dma_buffer_done(void *data)
1407 {
1408         struct iio_dev *indio_dev = data;
1409
1410         iio_trigger_poll_chained(indio_dev->trig);
1411 }
1412
1413 static int stm32_adc_dma_start(struct iio_dev *indio_dev)
1414 {
1415         struct stm32_adc *adc = iio_priv(indio_dev);
1416         struct dma_async_tx_descriptor *desc;
1417         dma_cookie_t cookie;
1418         int ret;
1419
1420         if (!adc->dma_chan)
1421                 return 0;
1422
1423         dev_dbg(&indio_dev->dev, "%s size=%d watermark=%d\n", __func__,
1424                 adc->rx_buf_sz, adc->rx_buf_sz / 2);
1425
1426         /* Prepare a DMA cyclic transaction */
1427         desc = dmaengine_prep_dma_cyclic(adc->dma_chan,
1428                                          adc->rx_dma_buf,
1429                                          adc->rx_buf_sz, adc->rx_buf_sz / 2,
1430                                          DMA_DEV_TO_MEM,
1431                                          DMA_PREP_INTERRUPT);
1432         if (!desc)
1433                 return -EBUSY;
1434
1435         desc->callback = stm32_adc_dma_buffer_done;
1436         desc->callback_param = indio_dev;
1437
1438         cookie = dmaengine_submit(desc);
1439         ret = dma_submit_error(cookie);
1440         if (ret) {
1441                 dmaengine_terminate_all(adc->dma_chan);
1442                 return ret;
1443         }
1444
1445         /* Issue pending DMA requests */
1446         dma_async_issue_pending(adc->dma_chan);
1447
1448         return 0;
1449 }
1450
1451 static int stm32_adc_buffer_postenable(struct iio_dev *indio_dev)
1452 {
1453         struct stm32_adc *adc = iio_priv(indio_dev);
1454         int ret;
1455
1456         if (adc->cfg->prepare) {
1457                 ret = adc->cfg->prepare(adc);
1458                 if (ret)
1459                         return ret;
1460         }
1461
1462         ret = stm32_adc_set_trig(indio_dev, indio_dev->trig);
1463         if (ret) {
1464                 dev_err(&indio_dev->dev, "Can't set trigger\n");
1465                 goto err_unprepare;
1466         }
1467
1468         ret = stm32_adc_dma_start(indio_dev);
1469         if (ret) {
1470                 dev_err(&indio_dev->dev, "Can't start dma\n");
1471                 goto err_clr_trig;
1472         }
1473
1474         ret = iio_triggered_buffer_postenable(indio_dev);
1475         if (ret < 0)
1476                 goto err_stop_dma;
1477
1478         /* Reset adc buffer index */
1479         adc->bufi = 0;
1480
1481         if (!adc->dma_chan)
1482                 stm32_adc_conv_irq_enable(adc);
1483
1484         adc->cfg->start_conv(adc, !!adc->dma_chan);
1485
1486         return 0;
1487
1488 err_stop_dma:
1489         if (adc->dma_chan)
1490                 dmaengine_terminate_all(adc->dma_chan);
1491 err_clr_trig:
1492         stm32_adc_set_trig(indio_dev, NULL);
1493 err_unprepare:
1494         if (adc->cfg->unprepare)
1495                 adc->cfg->unprepare(adc);
1496
1497         return ret;
1498 }
1499
1500 static int stm32_adc_buffer_predisable(struct iio_dev *indio_dev)
1501 {
1502         struct stm32_adc *adc = iio_priv(indio_dev);
1503         int ret;
1504
1505         adc->cfg->stop_conv(adc);
1506         if (!adc->dma_chan)
1507                 stm32_adc_conv_irq_disable(adc);
1508
1509         ret = iio_triggered_buffer_predisable(indio_dev);
1510         if (ret < 0)
1511                 dev_err(&indio_dev->dev, "predisable failed\n");
1512
1513         if (adc->dma_chan)
1514                 dmaengine_terminate_all(adc->dma_chan);
1515
1516         if (stm32_adc_set_trig(indio_dev, NULL))
1517                 dev_err(&indio_dev->dev, "Can't clear trigger\n");
1518
1519         if (adc->cfg->unprepare)
1520                 adc->cfg->unprepare(adc);
1521
1522         return ret;
1523 }
1524
1525 static const struct iio_buffer_setup_ops stm32_adc_buffer_setup_ops = {
1526         .postenable = &stm32_adc_buffer_postenable,
1527         .predisable = &stm32_adc_buffer_predisable,
1528 };
1529
1530 static irqreturn_t stm32_adc_trigger_handler(int irq, void *p)
1531 {
1532         struct iio_poll_func *pf = p;
1533         struct iio_dev *indio_dev = pf->indio_dev;
1534         struct stm32_adc *adc = iio_priv(indio_dev);
1535
1536         dev_dbg(&indio_dev->dev, "%s bufi=%d\n", __func__, adc->bufi);
1537
1538         if (!adc->dma_chan) {
1539                 /* reset buffer index */
1540                 adc->bufi = 0;
1541                 iio_push_to_buffers_with_timestamp(indio_dev, adc->buffer,
1542                                                    pf->timestamp);
1543         } else {
1544                 int residue = stm32_adc_dma_residue(adc);
1545
1546                 while (residue >= indio_dev->scan_bytes) {
1547                         u16 *buffer = (u16 *)&adc->rx_buf[adc->bufi];
1548
1549                         iio_push_to_buffers_with_timestamp(indio_dev, buffer,
1550                                                            pf->timestamp);
1551                         residue -= indio_dev->scan_bytes;
1552                         adc->bufi += indio_dev->scan_bytes;
1553                         if (adc->bufi >= adc->rx_buf_sz)
1554                                 adc->bufi = 0;
1555                 }
1556         }
1557
1558         iio_trigger_notify_done(indio_dev->trig);
1559
1560         /* re-enable eoc irq */
1561         if (!adc->dma_chan)
1562                 stm32_adc_conv_irq_enable(adc);
1563
1564         return IRQ_HANDLED;
1565 }
1566
1567 static const struct iio_chan_spec_ext_info stm32_adc_ext_info[] = {
1568         IIO_ENUM("trigger_polarity", IIO_SHARED_BY_ALL, &stm32_adc_trig_pol),
1569         {
1570                 .name = "trigger_polarity_available",
1571                 .shared = IIO_SHARED_BY_ALL,
1572                 .read = iio_enum_available_read,
1573                 .private = (uintptr_t)&stm32_adc_trig_pol,
1574         },
1575         {},
1576 };
1577
1578 static int stm32_adc_of_get_resolution(struct iio_dev *indio_dev)
1579 {
1580         struct device_node *node = indio_dev->dev.of_node;
1581         struct stm32_adc *adc = iio_priv(indio_dev);
1582         unsigned int i;
1583         u32 res;
1584
1585         if (of_property_read_u32(node, "assigned-resolution-bits", &res))
1586                 res = adc->cfg->adc_info->resolutions[0];
1587
1588         for (i = 0; i < adc->cfg->adc_info->num_res; i++)
1589                 if (res == adc->cfg->adc_info->resolutions[i])
1590                         break;
1591         if (i >= adc->cfg->adc_info->num_res) {
1592                 dev_err(&indio_dev->dev, "Bad resolution: %u bits\n", res);
1593                 return -EINVAL;
1594         }
1595
1596         dev_dbg(&indio_dev->dev, "Using %u bits resolution\n", res);
1597         adc->res = i;
1598
1599         return 0;
1600 }
1601
1602 static void stm32_adc_smpr_init(struct stm32_adc *adc, int channel, u32 smp_ns)
1603 {
1604         const struct stm32_adc_regs *smpr = &adc->cfg->regs->smp_bits[channel];
1605         u32 period_ns, shift = smpr->shift, mask = smpr->mask;
1606         unsigned int smp, r = smpr->reg;
1607
1608         /* Determine sampling time (ADC clock cycles) */
1609         period_ns = NSEC_PER_SEC / adc->common->rate;
1610         for (smp = 0; smp <= STM32_ADC_MAX_SMP; smp++)
1611                 if ((period_ns * adc->cfg->smp_cycles[smp]) >= smp_ns)
1612                         break;
1613         if (smp > STM32_ADC_MAX_SMP)
1614                 smp = STM32_ADC_MAX_SMP;
1615
1616         /* pre-build sampling time registers (e.g. smpr1, smpr2) */
1617         adc->smpr_val[r] = (adc->smpr_val[r] & ~mask) | (smp << shift);
1618 }
1619
1620 static void stm32_adc_chan_init_one(struct iio_dev *indio_dev,
1621                                     struct iio_chan_spec *chan,
1622                                     const struct stm32_adc_chan_spec *channel,
1623                                     int scan_index, u32 smp)
1624 {
1625         struct stm32_adc *adc = iio_priv(indio_dev);
1626
1627         chan->type = channel->type;
1628         chan->channel = channel->channel;
1629         chan->datasheet_name = channel->name;
1630         chan->scan_index = scan_index;
1631         chan->indexed = 1;
1632         chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
1633         chan->info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE);
1634         chan->scan_type.sign = 'u';
1635         chan->scan_type.realbits = adc->cfg->adc_info->resolutions[adc->res];
1636         chan->scan_type.storagebits = 16;
1637         chan->ext_info = stm32_adc_ext_info;
1638
1639         /* Prepare sampling time settings */
1640         stm32_adc_smpr_init(adc, chan->channel, smp);
1641
1642         /* pre-build selected channels mask */
1643         adc->pcsel |= BIT(chan->channel);
1644 }
1645
1646 static int stm32_adc_chan_of_init(struct iio_dev *indio_dev)
1647 {
1648         struct device_node *node = indio_dev->dev.of_node;
1649         struct stm32_adc *adc = iio_priv(indio_dev);
1650         const struct stm32_adc_info *adc_info = adc->cfg->adc_info;
1651         struct property *prop;
1652         const __be32 *cur;
1653         struct iio_chan_spec *channels;
1654         int scan_index = 0, num_channels, ret;
1655         u32 val, smp = 0;
1656
1657         num_channels = of_property_count_u32_elems(node, "st,adc-channels");
1658         if (num_channels < 0 ||
1659             num_channels >= adc_info->max_channels) {
1660                 dev_err(&indio_dev->dev, "Bad st,adc-channels?\n");
1661                 return num_channels < 0 ? num_channels : -EINVAL;
1662         }
1663
1664         /* Optional sample time is provided either for each, or all channels */
1665         ret = of_property_count_u32_elems(node, "st,min-sample-time-nsecs");
1666         if (ret > 1 && ret != num_channels) {
1667                 dev_err(&indio_dev->dev, "Invalid st,min-sample-time-nsecs\n");
1668                 return -EINVAL;
1669         }
1670
1671         channels = devm_kcalloc(&indio_dev->dev, num_channels,
1672                                 sizeof(struct iio_chan_spec), GFP_KERNEL);
1673         if (!channels)
1674                 return -ENOMEM;
1675
1676         of_property_for_each_u32(node, "st,adc-channels", prop, cur, val) {
1677                 if (val >= adc_info->max_channels) {
1678                         dev_err(&indio_dev->dev, "Invalid channel %d\n", val);
1679                         return -EINVAL;
1680                 }
1681
1682                 /*
1683                  * Using of_property_read_u32_index(), smp value will only be
1684                  * modified if valid u32 value can be decoded. This allows to
1685                  * get either no value, 1 shared value for all indexes, or one
1686                  * value per channel.
1687                  */
1688                 of_property_read_u32_index(node, "st,min-sample-time-nsecs",
1689                                            scan_index, &smp);
1690
1691                 stm32_adc_chan_init_one(indio_dev, &channels[scan_index],
1692                                         &adc_info->channels[val],
1693                                         scan_index, smp);
1694                 scan_index++;
1695         }
1696
1697         indio_dev->num_channels = scan_index;
1698         indio_dev->channels = channels;
1699
1700         return 0;
1701 }
1702
1703 static int stm32_adc_dma_request(struct iio_dev *indio_dev)
1704 {
1705         struct stm32_adc *adc = iio_priv(indio_dev);
1706         struct dma_slave_config config;
1707         int ret;
1708
1709         adc->dma_chan = dma_request_slave_channel(&indio_dev->dev, "rx");
1710         if (!adc->dma_chan)
1711                 return 0;
1712
1713         adc->rx_buf = dma_alloc_coherent(adc->dma_chan->device->dev,
1714                                          STM32_DMA_BUFFER_SIZE,
1715                                          &adc->rx_dma_buf, GFP_KERNEL);
1716         if (!adc->rx_buf) {
1717                 ret = -ENOMEM;
1718                 goto err_release;
1719         }
1720
1721         /* Configure DMA channel to read data register */
1722         memset(&config, 0, sizeof(config));
1723         config.src_addr = (dma_addr_t)adc->common->phys_base;
1724         config.src_addr += adc->offset + adc->cfg->regs->dr;
1725         config.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
1726
1727         ret = dmaengine_slave_config(adc->dma_chan, &config);
1728         if (ret)
1729                 goto err_free;
1730
1731         return 0;
1732
1733 err_free:
1734         dma_free_coherent(adc->dma_chan->device->dev, STM32_DMA_BUFFER_SIZE,
1735                           adc->rx_buf, adc->rx_dma_buf);
1736 err_release:
1737         dma_release_channel(adc->dma_chan);
1738
1739         return ret;
1740 }
1741
1742 static int stm32_adc_probe(struct platform_device *pdev)
1743 {
1744         struct iio_dev *indio_dev;
1745         struct device *dev = &pdev->dev;
1746         struct stm32_adc *adc;
1747         int ret;
1748
1749         if (!pdev->dev.of_node)
1750                 return -ENODEV;
1751
1752         indio_dev = devm_iio_device_alloc(&pdev->dev, sizeof(*adc));
1753         if (!indio_dev)
1754                 return -ENOMEM;
1755
1756         adc = iio_priv(indio_dev);
1757         adc->common = dev_get_drvdata(pdev->dev.parent);
1758         spin_lock_init(&adc->lock);
1759         init_completion(&adc->completion);
1760         adc->cfg = (const struct stm32_adc_cfg *)
1761                 of_match_device(dev->driver->of_match_table, dev)->data;
1762
1763         indio_dev->name = dev_name(&pdev->dev);
1764         indio_dev->dev.parent = &pdev->dev;
1765         indio_dev->dev.of_node = pdev->dev.of_node;
1766         indio_dev->info = &stm32_adc_iio_info;
1767         indio_dev->modes = INDIO_DIRECT_MODE;
1768
1769         platform_set_drvdata(pdev, adc);
1770
1771         ret = of_property_read_u32(pdev->dev.of_node, "reg", &adc->offset);
1772         if (ret != 0) {
1773                 dev_err(&pdev->dev, "missing reg property\n");
1774                 return -EINVAL;
1775         }
1776
1777         adc->irq = platform_get_irq(pdev, 0);
1778         if (adc->irq < 0) {
1779                 dev_err(&pdev->dev, "failed to get irq\n");
1780                 return adc->irq;
1781         }
1782
1783         ret = devm_request_irq(&pdev->dev, adc->irq, stm32_adc_isr,
1784                                0, pdev->name, adc);
1785         if (ret) {
1786                 dev_err(&pdev->dev, "failed to request IRQ\n");
1787                 return ret;
1788         }
1789
1790         adc->clk = devm_clk_get(&pdev->dev, NULL);
1791         if (IS_ERR(adc->clk)) {
1792                 ret = PTR_ERR(adc->clk);
1793                 if (ret == -ENOENT && !adc->cfg->clk_required) {
1794                         adc->clk = NULL;
1795                 } else {
1796                         dev_err(&pdev->dev, "Can't get clock\n");
1797                         return ret;
1798                 }
1799         }
1800
1801         if (adc->clk) {
1802                 ret = clk_prepare_enable(adc->clk);
1803                 if (ret < 0) {
1804                         dev_err(&pdev->dev, "clk enable failed\n");
1805                         return ret;
1806                 }
1807         }
1808
1809         ret = stm32_adc_of_get_resolution(indio_dev);
1810         if (ret < 0)
1811                 goto err_clk_disable;
1812         stm32_adc_set_res(adc);
1813
1814         if (adc->cfg->selfcalib) {
1815                 ret = adc->cfg->selfcalib(adc);
1816                 if (ret)
1817                         goto err_clk_disable;
1818         }
1819
1820         ret = stm32_adc_chan_of_init(indio_dev);
1821         if (ret < 0)
1822                 goto err_clk_disable;
1823
1824         ret = stm32_adc_dma_request(indio_dev);
1825         if (ret < 0)
1826                 goto err_clk_disable;
1827
1828         ret = iio_triggered_buffer_setup(indio_dev,
1829                                          &iio_pollfunc_store_time,
1830                                          &stm32_adc_trigger_handler,
1831                                          &stm32_adc_buffer_setup_ops);
1832         if (ret) {
1833                 dev_err(&pdev->dev, "buffer setup failed\n");
1834                 goto err_dma_disable;
1835         }
1836
1837         ret = iio_device_register(indio_dev);
1838         if (ret) {
1839                 dev_err(&pdev->dev, "iio dev register failed\n");
1840                 goto err_buffer_cleanup;
1841         }
1842
1843         return 0;
1844
1845 err_buffer_cleanup:
1846         iio_triggered_buffer_cleanup(indio_dev);
1847
1848 err_dma_disable:
1849         if (adc->dma_chan) {
1850                 dma_free_coherent(adc->dma_chan->device->dev,
1851                                   STM32_DMA_BUFFER_SIZE,
1852                                   adc->rx_buf, adc->rx_dma_buf);
1853                 dma_release_channel(adc->dma_chan);
1854         }
1855 err_clk_disable:
1856         if (adc->clk)
1857                 clk_disable_unprepare(adc->clk);
1858
1859         return ret;
1860 }
1861
1862 static int stm32_adc_remove(struct platform_device *pdev)
1863 {
1864         struct stm32_adc *adc = platform_get_drvdata(pdev);
1865         struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1866
1867         iio_device_unregister(indio_dev);
1868         iio_triggered_buffer_cleanup(indio_dev);
1869         if (adc->dma_chan) {
1870                 dma_free_coherent(adc->dma_chan->device->dev,
1871                                   STM32_DMA_BUFFER_SIZE,
1872                                   adc->rx_buf, adc->rx_dma_buf);
1873                 dma_release_channel(adc->dma_chan);
1874         }
1875         if (adc->clk)
1876                 clk_disable_unprepare(adc->clk);
1877
1878         return 0;
1879 }
1880
1881 static const struct stm32_adc_cfg stm32f4_adc_cfg = {
1882         .regs = &stm32f4_adc_regspec,
1883         .adc_info = &stm32f4_adc_info,
1884         .trigs = stm32f4_adc_trigs,
1885         .clk_required = true,
1886         .start_conv = stm32f4_adc_start_conv,
1887         .stop_conv = stm32f4_adc_stop_conv,
1888         .smp_cycles = stm32f4_adc_smp_cycles,
1889 };
1890
1891 static const struct stm32_adc_cfg stm32h7_adc_cfg = {
1892         .regs = &stm32h7_adc_regspec,
1893         .adc_info = &stm32h7_adc_info,
1894         .trigs = stm32h7_adc_trigs,
1895         .selfcalib = stm32h7_adc_selfcalib,
1896         .start_conv = stm32h7_adc_start_conv,
1897         .stop_conv = stm32h7_adc_stop_conv,
1898         .prepare = stm32h7_adc_prepare,
1899         .unprepare = stm32h7_adc_unprepare,
1900         .smp_cycles = stm32h7_adc_smp_cycles,
1901 };
1902
1903 static const struct of_device_id stm32_adc_of_match[] = {
1904         { .compatible = "st,stm32f4-adc", .data = (void *)&stm32f4_adc_cfg },
1905         { .compatible = "st,stm32h7-adc", .data = (void *)&stm32h7_adc_cfg },
1906         {},
1907 };
1908 MODULE_DEVICE_TABLE(of, stm32_adc_of_match);
1909
1910 static struct platform_driver stm32_adc_driver = {
1911         .probe = stm32_adc_probe,
1912         .remove = stm32_adc_remove,
1913         .driver = {
1914                 .name = "stm32-adc",
1915                 .of_match_table = stm32_adc_of_match,
1916         },
1917 };
1918 module_platform_driver(stm32_adc_driver);
1919
1920 MODULE_AUTHOR("Fabrice Gasnier <fabrice.gasnier@st.com>");
1921 MODULE_DESCRIPTION("STMicroelectronics STM32 ADC IIO driver");
1922 MODULE_LICENSE("GPL v2");
1923 MODULE_ALIAS("platform:stm32-adc");