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