xref: /openbmc/linux/drivers/iio/adc/stm32-adc.c (revision 8365a898)
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 stm32_adc *);
166 	void (*start_conv)(struct stm32_adc *, bool dma);
167 	void (*stop_conv)(struct stm32_adc *);
168 	void (*unprepare)(struct stm32_adc *);
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 stm32_adc *adc = dev_get_drvdata(dev);
542 
543 	if (adc->cfg->unprepare)
544 		adc->cfg->unprepare(adc);
545 
546 	if (adc->clk)
547 		clk_disable_unprepare(adc->clk);
548 
549 	return 0;
550 }
551 
552 static int stm32_adc_hw_start(struct device *dev)
553 {
554 	struct stm32_adc *adc = dev_get_drvdata(dev);
555 	int ret;
556 
557 	if (adc->clk) {
558 		ret = clk_prepare_enable(adc->clk);
559 		if (ret)
560 			return ret;
561 	}
562 
563 	stm32_adc_set_res(adc);
564 
565 	if (adc->cfg->prepare) {
566 		ret = adc->cfg->prepare(adc);
567 		if (ret)
568 			goto err_clk_dis;
569 	}
570 
571 	return 0;
572 
573 err_clk_dis:
574 	if (adc->clk)
575 		clk_disable_unprepare(adc->clk);
576 
577 	return ret;
578 }
579 
580 /**
581  * stm32f4_adc_start_conv() - Start conversions for regular channels.
582  * @adc: stm32 adc instance
583  * @dma: use dma to transfer conversion result
584  *
585  * Start conversions for regular channels.
586  * Also take care of normal or DMA mode. Circular DMA may be used for regular
587  * conversions, in IIO buffer modes. Otherwise, use ADC interrupt with direct
588  * DR read instead (e.g. read_raw, or triggered buffer mode without DMA).
589  */
590 static void stm32f4_adc_start_conv(struct stm32_adc *adc, bool dma)
591 {
592 	stm32_adc_set_bits(adc, STM32F4_ADC_CR1, STM32F4_SCAN);
593 
594 	if (dma)
595 		stm32_adc_set_bits(adc, STM32F4_ADC_CR2,
596 				   STM32F4_DMA | STM32F4_DDS);
597 
598 	stm32_adc_set_bits(adc, STM32F4_ADC_CR2, STM32F4_EOCS | STM32F4_ADON);
599 
600 	/* Wait for Power-up time (tSTAB from datasheet) */
601 	usleep_range(2, 3);
602 
603 	/* Software start ? (e.g. trigger detection disabled ?) */
604 	if (!(stm32_adc_readl(adc, STM32F4_ADC_CR2) & STM32F4_EXTEN_MASK))
605 		stm32_adc_set_bits(adc, STM32F4_ADC_CR2, STM32F4_SWSTART);
606 }
607 
608 static void stm32f4_adc_stop_conv(struct stm32_adc *adc)
609 {
610 	stm32_adc_clr_bits(adc, STM32F4_ADC_CR2, STM32F4_EXTEN_MASK);
611 	stm32_adc_clr_bits(adc, STM32F4_ADC_SR, STM32F4_STRT);
612 
613 	stm32_adc_clr_bits(adc, STM32F4_ADC_CR1, STM32F4_SCAN);
614 	stm32_adc_clr_bits(adc, STM32F4_ADC_CR2,
615 			   STM32F4_ADON | STM32F4_DMA | STM32F4_DDS);
616 }
617 
618 static void stm32h7_adc_start_conv(struct stm32_adc *adc, bool dma)
619 {
620 	enum stm32h7_adc_dmngt dmngt;
621 	unsigned long flags;
622 	u32 val;
623 
624 	if (dma)
625 		dmngt = STM32H7_DMNGT_DMA_CIRC;
626 	else
627 		dmngt = STM32H7_DMNGT_DR_ONLY;
628 
629 	spin_lock_irqsave(&adc->lock, flags);
630 	val = stm32_adc_readl(adc, STM32H7_ADC_CFGR);
631 	val = (val & ~STM32H7_DMNGT_MASK) | (dmngt << STM32H7_DMNGT_SHIFT);
632 	stm32_adc_writel(adc, STM32H7_ADC_CFGR, val);
633 	spin_unlock_irqrestore(&adc->lock, flags);
634 
635 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADSTART);
636 }
637 
638 static void stm32h7_adc_stop_conv(struct stm32_adc *adc)
639 {
640 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
641 	int ret;
642 	u32 val;
643 
644 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADSTP);
645 
646 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
647 					   !(val & (STM32H7_ADSTART)),
648 					   100, STM32_ADC_TIMEOUT_US);
649 	if (ret)
650 		dev_warn(&indio_dev->dev, "stop failed\n");
651 
652 	stm32_adc_clr_bits(adc, STM32H7_ADC_CFGR, STM32H7_DMNGT_MASK);
653 }
654 
655 static int stm32h7_adc_exit_pwr_down(struct stm32_adc *adc)
656 {
657 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
658 	int ret;
659 	u32 val;
660 
661 	/* Exit deep power down, then enable ADC voltage regulator */
662 	stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_DEEPPWD);
663 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADVREGEN);
664 
665 	if (adc->common->rate > STM32H7_BOOST_CLKRATE)
666 		stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_BOOST);
667 
668 	/* Wait for startup time */
669 	if (!adc->cfg->has_vregready) {
670 		usleep_range(10, 20);
671 		return 0;
672 	}
673 
674 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_ISR, val,
675 					   val & STM32MP1_VREGREADY, 100,
676 					   STM32_ADC_TIMEOUT_US);
677 	if (ret) {
678 		stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_DEEPPWD);
679 		dev_err(&indio_dev->dev, "Failed to exit power down\n");
680 	}
681 
682 	return ret;
683 }
684 
685 static void stm32h7_adc_enter_pwr_down(struct stm32_adc *adc)
686 {
687 	stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_BOOST);
688 
689 	/* Setting DEEPPWD disables ADC vreg and clears ADVREGEN */
690 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_DEEPPWD);
691 }
692 
693 static int stm32h7_adc_enable(struct stm32_adc *adc)
694 {
695 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
696 	int ret;
697 	u32 val;
698 
699 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADEN);
700 
701 	/* Poll for ADRDY to be set (after adc startup time) */
702 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_ISR, val,
703 					   val & STM32H7_ADRDY,
704 					   100, STM32_ADC_TIMEOUT_US);
705 	if (ret) {
706 		stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADDIS);
707 		dev_err(&indio_dev->dev, "Failed to enable ADC\n");
708 	} else {
709 		/* Clear ADRDY by writing one */
710 		stm32_adc_set_bits(adc, STM32H7_ADC_ISR, STM32H7_ADRDY);
711 	}
712 
713 	return ret;
714 }
715 
716 static void stm32h7_adc_disable(struct stm32_adc *adc)
717 {
718 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
719 	int ret;
720 	u32 val;
721 
722 	/* Disable ADC and wait until it's effectively disabled */
723 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADDIS);
724 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
725 					   !(val & STM32H7_ADEN), 100,
726 					   STM32_ADC_TIMEOUT_US);
727 	if (ret)
728 		dev_warn(&indio_dev->dev, "Failed to disable\n");
729 }
730 
731 /**
732  * stm32h7_adc_read_selfcalib() - read calibration shadow regs, save result
733  * @adc: stm32 adc instance
734  * Note: Must be called once ADC is enabled, so LINCALRDYW[1..6] are writable
735  */
736 static int stm32h7_adc_read_selfcalib(struct stm32_adc *adc)
737 {
738 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
739 	int i, ret;
740 	u32 lincalrdyw_mask, val;
741 
742 	/* Read linearity calibration */
743 	lincalrdyw_mask = STM32H7_LINCALRDYW6;
744 	for (i = STM32H7_LINCALFACT_NUM - 1; i >= 0; i--) {
745 		/* Clear STM32H7_LINCALRDYW[6..1]: transfer calib to CALFACT2 */
746 		stm32_adc_clr_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
747 
748 		/* Poll: wait calib data to be ready in CALFACT2 register */
749 		ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
750 						   !(val & lincalrdyw_mask),
751 						   100, STM32_ADC_TIMEOUT_US);
752 		if (ret) {
753 			dev_err(&indio_dev->dev, "Failed to read calfact\n");
754 			return ret;
755 		}
756 
757 		val = stm32_adc_readl(adc, STM32H7_ADC_CALFACT2);
758 		adc->cal.lincalfact[i] = (val & STM32H7_LINCALFACT_MASK);
759 		adc->cal.lincalfact[i] >>= STM32H7_LINCALFACT_SHIFT;
760 
761 		lincalrdyw_mask >>= 1;
762 	}
763 
764 	/* Read offset calibration */
765 	val = stm32_adc_readl(adc, STM32H7_ADC_CALFACT);
766 	adc->cal.calfact_s = (val & STM32H7_CALFACT_S_MASK);
767 	adc->cal.calfact_s >>= STM32H7_CALFACT_S_SHIFT;
768 	adc->cal.calfact_d = (val & STM32H7_CALFACT_D_MASK);
769 	adc->cal.calfact_d >>= STM32H7_CALFACT_D_SHIFT;
770 	adc->cal.calibrated = true;
771 
772 	return 0;
773 }
774 
775 /**
776  * stm32h7_adc_restore_selfcalib() - Restore saved self-calibration result
777  * @adc: stm32 adc instance
778  * Note: ADC must be enabled, with no on-going conversions.
779  */
780 static int stm32h7_adc_restore_selfcalib(struct stm32_adc *adc)
781 {
782 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
783 	int i, ret;
784 	u32 lincalrdyw_mask, val;
785 
786 	val = (adc->cal.calfact_s << STM32H7_CALFACT_S_SHIFT) |
787 		(adc->cal.calfact_d << STM32H7_CALFACT_D_SHIFT);
788 	stm32_adc_writel(adc, STM32H7_ADC_CALFACT, val);
789 
790 	lincalrdyw_mask = STM32H7_LINCALRDYW6;
791 	for (i = STM32H7_LINCALFACT_NUM - 1; i >= 0; i--) {
792 		/*
793 		 * Write saved calibration data to shadow registers:
794 		 * Write CALFACT2, and set LINCALRDYW[6..1] bit to trigger
795 		 * data write. Then poll to wait for complete transfer.
796 		 */
797 		val = adc->cal.lincalfact[i] << STM32H7_LINCALFACT_SHIFT;
798 		stm32_adc_writel(adc, STM32H7_ADC_CALFACT2, val);
799 		stm32_adc_set_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
800 		ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
801 						   val & lincalrdyw_mask,
802 						   100, STM32_ADC_TIMEOUT_US);
803 		if (ret) {
804 			dev_err(&indio_dev->dev, "Failed to write calfact\n");
805 			return ret;
806 		}
807 
808 		/*
809 		 * Read back calibration data, has two effects:
810 		 * - It ensures bits LINCALRDYW[6..1] are kept cleared
811 		 *   for next time calibration needs to be restored.
812 		 * - BTW, bit clear triggers a read, then check data has been
813 		 *   correctly written.
814 		 */
815 		stm32_adc_clr_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
816 		ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
817 						   !(val & lincalrdyw_mask),
818 						   100, STM32_ADC_TIMEOUT_US);
819 		if (ret) {
820 			dev_err(&indio_dev->dev, "Failed to read calfact\n");
821 			return ret;
822 		}
823 		val = stm32_adc_readl(adc, STM32H7_ADC_CALFACT2);
824 		if (val != adc->cal.lincalfact[i] << STM32H7_LINCALFACT_SHIFT) {
825 			dev_err(&indio_dev->dev, "calfact not consistent\n");
826 			return -EIO;
827 		}
828 
829 		lincalrdyw_mask >>= 1;
830 	}
831 
832 	return 0;
833 }
834 
835 /**
836  * Fixed timeout value for ADC calibration.
837  * worst cases:
838  * - low clock frequency
839  * - maximum prescalers
840  * Calibration requires:
841  * - 131,072 ADC clock cycle for the linear calibration
842  * - 20 ADC clock cycle for the offset calibration
843  *
844  * Set to 100ms for now
845  */
846 #define STM32H7_ADC_CALIB_TIMEOUT_US		100000
847 
848 /**
849  * stm32h7_adc_selfcalib() - Procedure to calibrate ADC
850  * @adc: stm32 adc instance
851  * Note: Must be called once ADC is out of power down.
852  */
853 static int stm32h7_adc_selfcalib(struct stm32_adc *adc)
854 {
855 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
856 	int ret;
857 	u32 val;
858 
859 	if (adc->cal.calibrated)
860 		return true;
861 
862 	/*
863 	 * Select calibration mode:
864 	 * - Offset calibration for single ended inputs
865 	 * - No linearity calibration (do it later, before reading it)
866 	 */
867 	stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_ADCALDIF);
868 	stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_ADCALLIN);
869 
870 	/* Start calibration, then wait for completion */
871 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADCAL);
872 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
873 					   !(val & STM32H7_ADCAL), 100,
874 					   STM32H7_ADC_CALIB_TIMEOUT_US);
875 	if (ret) {
876 		dev_err(&indio_dev->dev, "calibration failed\n");
877 		goto out;
878 	}
879 
880 	/*
881 	 * Select calibration mode, then start calibration:
882 	 * - Offset calibration for differential input
883 	 * - Linearity calibration (needs to be done only once for single/diff)
884 	 *   will run simultaneously with offset calibration.
885 	 */
886 	stm32_adc_set_bits(adc, STM32H7_ADC_CR,
887 			   STM32H7_ADCALDIF | STM32H7_ADCALLIN);
888 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADCAL);
889 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
890 					   !(val & STM32H7_ADCAL), 100,
891 					   STM32H7_ADC_CALIB_TIMEOUT_US);
892 	if (ret) {
893 		dev_err(&indio_dev->dev, "calibration failed\n");
894 		goto out;
895 	}
896 
897 out:
898 	stm32_adc_clr_bits(adc, STM32H7_ADC_CR,
899 			   STM32H7_ADCALDIF | STM32H7_ADCALLIN);
900 
901 	return ret;
902 }
903 
904 /**
905  * stm32h7_adc_prepare() - Leave power down mode to enable ADC.
906  * @adc: stm32 adc instance
907  * Leave power down mode.
908  * Configure channels as single ended or differential before enabling ADC.
909  * Enable ADC.
910  * Restore calibration data.
911  * Pre-select channels that may be used in PCSEL (required by input MUX / IO):
912  * - Only one input is selected for single ended (e.g. 'vinp')
913  * - Two inputs are selected for differential channels (e.g. 'vinp' & 'vinn')
914  */
915 static int stm32h7_adc_prepare(struct stm32_adc *adc)
916 {
917 	int calib, ret;
918 
919 	ret = stm32h7_adc_exit_pwr_down(adc);
920 	if (ret)
921 		return ret;
922 
923 	ret = stm32h7_adc_selfcalib(adc);
924 	if (ret < 0)
925 		goto pwr_dwn;
926 	calib = ret;
927 
928 	stm32_adc_writel(adc, STM32H7_ADC_DIFSEL, adc->difsel);
929 
930 	ret = stm32h7_adc_enable(adc);
931 	if (ret)
932 		goto pwr_dwn;
933 
934 	/* Either restore or read calibration result for future reference */
935 	if (calib)
936 		ret = stm32h7_adc_restore_selfcalib(adc);
937 	else
938 		ret = stm32h7_adc_read_selfcalib(adc);
939 	if (ret)
940 		goto disable;
941 
942 	stm32_adc_writel(adc, STM32H7_ADC_PCSEL, adc->pcsel);
943 
944 	return 0;
945 
946 disable:
947 	stm32h7_adc_disable(adc);
948 pwr_dwn:
949 	stm32h7_adc_enter_pwr_down(adc);
950 
951 	return ret;
952 }
953 
954 static void stm32h7_adc_unprepare(struct stm32_adc *adc)
955 {
956 	stm32h7_adc_disable(adc);
957 	stm32h7_adc_enter_pwr_down(adc);
958 }
959 
960 /**
961  * stm32_adc_conf_scan_seq() - Build regular channels scan sequence
962  * @indio_dev: IIO device
963  * @scan_mask: channels to be converted
964  *
965  * Conversion sequence :
966  * Apply sampling time settings for all channels.
967  * Configure ADC scan sequence based on selected channels in scan_mask.
968  * Add channels to SQR registers, from scan_mask LSB to MSB, then
969  * program sequence len.
970  */
971 static int stm32_adc_conf_scan_seq(struct iio_dev *indio_dev,
972 				   const unsigned long *scan_mask)
973 {
974 	struct stm32_adc *adc = iio_priv(indio_dev);
975 	const struct stm32_adc_regs *sqr = adc->cfg->regs->sqr;
976 	const struct iio_chan_spec *chan;
977 	u32 val, bit;
978 	int i = 0;
979 
980 	/* Apply sampling time settings */
981 	stm32_adc_writel(adc, adc->cfg->regs->smpr[0], adc->smpr_val[0]);
982 	stm32_adc_writel(adc, adc->cfg->regs->smpr[1], adc->smpr_val[1]);
983 
984 	for_each_set_bit(bit, scan_mask, indio_dev->masklength) {
985 		chan = indio_dev->channels + bit;
986 		/*
987 		 * Assign one channel per SQ entry in regular
988 		 * sequence, starting with SQ1.
989 		 */
990 		i++;
991 		if (i > STM32_ADC_MAX_SQ)
992 			return -EINVAL;
993 
994 		dev_dbg(&indio_dev->dev, "%s chan %d to SQ%d\n",
995 			__func__, chan->channel, i);
996 
997 		val = stm32_adc_readl(adc, sqr[i].reg);
998 		val &= ~sqr[i].mask;
999 		val |= chan->channel << sqr[i].shift;
1000 		stm32_adc_writel(adc, sqr[i].reg, val);
1001 	}
1002 
1003 	if (!i)
1004 		return -EINVAL;
1005 
1006 	/* Sequence len */
1007 	val = stm32_adc_readl(adc, sqr[0].reg);
1008 	val &= ~sqr[0].mask;
1009 	val |= ((i - 1) << sqr[0].shift);
1010 	stm32_adc_writel(adc, sqr[0].reg, val);
1011 
1012 	return 0;
1013 }
1014 
1015 /**
1016  * stm32_adc_get_trig_extsel() - Get external trigger selection
1017  * @indio_dev: IIO device structure
1018  * @trig: trigger
1019  *
1020  * Returns trigger extsel value, if trig matches, -EINVAL otherwise.
1021  */
1022 static int stm32_adc_get_trig_extsel(struct iio_dev *indio_dev,
1023 				     struct iio_trigger *trig)
1024 {
1025 	struct stm32_adc *adc = iio_priv(indio_dev);
1026 	int i;
1027 
1028 	/* lookup triggers registered by stm32 timer trigger driver */
1029 	for (i = 0; adc->cfg->trigs[i].name; i++) {
1030 		/**
1031 		 * Checking both stm32 timer trigger type and trig name
1032 		 * should be safe against arbitrary trigger names.
1033 		 */
1034 		if ((is_stm32_timer_trigger(trig) ||
1035 		     is_stm32_lptim_trigger(trig)) &&
1036 		    !strcmp(adc->cfg->trigs[i].name, trig->name)) {
1037 			return adc->cfg->trigs[i].extsel;
1038 		}
1039 	}
1040 
1041 	return -EINVAL;
1042 }
1043 
1044 /**
1045  * stm32_adc_set_trig() - Set a regular trigger
1046  * @indio_dev: IIO device
1047  * @trig: IIO trigger
1048  *
1049  * Set trigger source/polarity (e.g. SW, or HW with polarity) :
1050  * - if HW trigger disabled (e.g. trig == NULL, conversion launched by sw)
1051  * - if HW trigger enabled, set source & polarity
1052  */
1053 static int stm32_adc_set_trig(struct iio_dev *indio_dev,
1054 			      struct iio_trigger *trig)
1055 {
1056 	struct stm32_adc *adc = iio_priv(indio_dev);
1057 	u32 val, extsel = 0, exten = STM32_EXTEN_SWTRIG;
1058 	unsigned long flags;
1059 	int ret;
1060 
1061 	if (trig) {
1062 		ret = stm32_adc_get_trig_extsel(indio_dev, trig);
1063 		if (ret < 0)
1064 			return ret;
1065 
1066 		/* set trigger source and polarity (default to rising edge) */
1067 		extsel = ret;
1068 		exten = adc->trigger_polarity + STM32_EXTEN_HWTRIG_RISING_EDGE;
1069 	}
1070 
1071 	spin_lock_irqsave(&adc->lock, flags);
1072 	val = stm32_adc_readl(adc, adc->cfg->regs->exten.reg);
1073 	val &= ~(adc->cfg->regs->exten.mask | adc->cfg->regs->extsel.mask);
1074 	val |= exten << adc->cfg->regs->exten.shift;
1075 	val |= extsel << adc->cfg->regs->extsel.shift;
1076 	stm32_adc_writel(adc,  adc->cfg->regs->exten.reg, val);
1077 	spin_unlock_irqrestore(&adc->lock, flags);
1078 
1079 	return 0;
1080 }
1081 
1082 static int stm32_adc_set_trig_pol(struct iio_dev *indio_dev,
1083 				  const struct iio_chan_spec *chan,
1084 				  unsigned int type)
1085 {
1086 	struct stm32_adc *adc = iio_priv(indio_dev);
1087 
1088 	adc->trigger_polarity = type;
1089 
1090 	return 0;
1091 }
1092 
1093 static int stm32_adc_get_trig_pol(struct iio_dev *indio_dev,
1094 				  const struct iio_chan_spec *chan)
1095 {
1096 	struct stm32_adc *adc = iio_priv(indio_dev);
1097 
1098 	return adc->trigger_polarity;
1099 }
1100 
1101 static const char * const stm32_trig_pol_items[] = {
1102 	"rising-edge", "falling-edge", "both-edges",
1103 };
1104 
1105 static const struct iio_enum stm32_adc_trig_pol = {
1106 	.items = stm32_trig_pol_items,
1107 	.num_items = ARRAY_SIZE(stm32_trig_pol_items),
1108 	.get = stm32_adc_get_trig_pol,
1109 	.set = stm32_adc_set_trig_pol,
1110 };
1111 
1112 /**
1113  * stm32_adc_single_conv() - Performs a single conversion
1114  * @indio_dev: IIO device
1115  * @chan: IIO channel
1116  * @res: conversion result
1117  *
1118  * The function performs a single conversion on a given channel:
1119  * - Apply sampling time settings
1120  * - Program sequencer with one channel (e.g. in SQ1 with len = 1)
1121  * - Use SW trigger
1122  * - Start conversion, then wait for interrupt completion.
1123  */
1124 static int stm32_adc_single_conv(struct iio_dev *indio_dev,
1125 				 const struct iio_chan_spec *chan,
1126 				 int *res)
1127 {
1128 	struct stm32_adc *adc = iio_priv(indio_dev);
1129 	struct device *dev = indio_dev->dev.parent;
1130 	const struct stm32_adc_regspec *regs = adc->cfg->regs;
1131 	long timeout;
1132 	u32 val;
1133 	int ret;
1134 
1135 	reinit_completion(&adc->completion);
1136 
1137 	adc->bufi = 0;
1138 
1139 	ret = pm_runtime_get_sync(dev);
1140 	if (ret < 0) {
1141 		pm_runtime_put_noidle(dev);
1142 		return ret;
1143 	}
1144 
1145 	/* Apply sampling time settings */
1146 	stm32_adc_writel(adc, regs->smpr[0], adc->smpr_val[0]);
1147 	stm32_adc_writel(adc, regs->smpr[1], adc->smpr_val[1]);
1148 
1149 	/* Program chan number in regular sequence (SQ1) */
1150 	val = stm32_adc_readl(adc, regs->sqr[1].reg);
1151 	val &= ~regs->sqr[1].mask;
1152 	val |= chan->channel << regs->sqr[1].shift;
1153 	stm32_adc_writel(adc, regs->sqr[1].reg, val);
1154 
1155 	/* Set regular sequence len (0 for 1 conversion) */
1156 	stm32_adc_clr_bits(adc, regs->sqr[0].reg, regs->sqr[0].mask);
1157 
1158 	/* Trigger detection disabled (conversion can be launched in SW) */
1159 	stm32_adc_clr_bits(adc, regs->exten.reg, regs->exten.mask);
1160 
1161 	stm32_adc_conv_irq_enable(adc);
1162 
1163 	adc->cfg->start_conv(adc, false);
1164 
1165 	timeout = wait_for_completion_interruptible_timeout(
1166 					&adc->completion, STM32_ADC_TIMEOUT);
1167 	if (timeout == 0) {
1168 		ret = -ETIMEDOUT;
1169 	} else if (timeout < 0) {
1170 		ret = timeout;
1171 	} else {
1172 		*res = adc->buffer[0];
1173 		ret = IIO_VAL_INT;
1174 	}
1175 
1176 	adc->cfg->stop_conv(adc);
1177 
1178 	stm32_adc_conv_irq_disable(adc);
1179 
1180 	pm_runtime_mark_last_busy(dev);
1181 	pm_runtime_put_autosuspend(dev);
1182 
1183 	return ret;
1184 }
1185 
1186 static int stm32_adc_read_raw(struct iio_dev *indio_dev,
1187 			      struct iio_chan_spec const *chan,
1188 			      int *val, int *val2, long mask)
1189 {
1190 	struct stm32_adc *adc = iio_priv(indio_dev);
1191 	int ret;
1192 
1193 	switch (mask) {
1194 	case IIO_CHAN_INFO_RAW:
1195 		ret = iio_device_claim_direct_mode(indio_dev);
1196 		if (ret)
1197 			return ret;
1198 		if (chan->type == IIO_VOLTAGE)
1199 			ret = stm32_adc_single_conv(indio_dev, chan, val);
1200 		else
1201 			ret = -EINVAL;
1202 		iio_device_release_direct_mode(indio_dev);
1203 		return ret;
1204 
1205 	case IIO_CHAN_INFO_SCALE:
1206 		if (chan->differential) {
1207 			*val = adc->common->vref_mv * 2;
1208 			*val2 = chan->scan_type.realbits;
1209 		} else {
1210 			*val = adc->common->vref_mv;
1211 			*val2 = chan->scan_type.realbits;
1212 		}
1213 		return IIO_VAL_FRACTIONAL_LOG2;
1214 
1215 	case IIO_CHAN_INFO_OFFSET:
1216 		if (chan->differential)
1217 			/* ADC_full_scale / 2 */
1218 			*val = -((1 << chan->scan_type.realbits) / 2);
1219 		else
1220 			*val = 0;
1221 		return IIO_VAL_INT;
1222 
1223 	default:
1224 		return -EINVAL;
1225 	}
1226 }
1227 
1228 static irqreturn_t stm32_adc_threaded_isr(int irq, void *data)
1229 {
1230 	struct stm32_adc *adc = data;
1231 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1232 	const struct stm32_adc_regspec *regs = adc->cfg->regs;
1233 	u32 status = stm32_adc_readl(adc, regs->isr_eoc.reg);
1234 
1235 	if (status & regs->isr_ovr.mask)
1236 		dev_err(&indio_dev->dev, "Overrun, stopping: restart needed\n");
1237 
1238 	return IRQ_HANDLED;
1239 }
1240 
1241 static irqreturn_t stm32_adc_isr(int irq, void *data)
1242 {
1243 	struct stm32_adc *adc = data;
1244 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1245 	const struct stm32_adc_regspec *regs = adc->cfg->regs;
1246 	u32 status = stm32_adc_readl(adc, regs->isr_eoc.reg);
1247 
1248 	if (status & regs->isr_ovr.mask) {
1249 		/*
1250 		 * Overrun occurred on regular conversions: data for wrong
1251 		 * channel may be read. Unconditionally disable interrupts
1252 		 * to stop processing data and print error message.
1253 		 * Restarting the capture can be done by disabling, then
1254 		 * re-enabling it (e.g. write 0, then 1 to buffer/enable).
1255 		 */
1256 		stm32_adc_ovr_irq_disable(adc);
1257 		stm32_adc_conv_irq_disable(adc);
1258 		return IRQ_WAKE_THREAD;
1259 	}
1260 
1261 	if (status & regs->isr_eoc.mask) {
1262 		/* Reading DR also clears EOC status flag */
1263 		adc->buffer[adc->bufi] = stm32_adc_readw(adc, regs->dr);
1264 		if (iio_buffer_enabled(indio_dev)) {
1265 			adc->bufi++;
1266 			if (adc->bufi >= adc->num_conv) {
1267 				stm32_adc_conv_irq_disable(adc);
1268 				iio_trigger_poll(indio_dev->trig);
1269 			}
1270 		} else {
1271 			complete(&adc->completion);
1272 		}
1273 		return IRQ_HANDLED;
1274 	}
1275 
1276 	return IRQ_NONE;
1277 }
1278 
1279 /**
1280  * stm32_adc_validate_trigger() - validate trigger for stm32 adc
1281  * @indio_dev: IIO device
1282  * @trig: new trigger
1283  *
1284  * Returns: 0 if trig matches one of the triggers registered by stm32 adc
1285  * driver, -EINVAL otherwise.
1286  */
1287 static int stm32_adc_validate_trigger(struct iio_dev *indio_dev,
1288 				      struct iio_trigger *trig)
1289 {
1290 	return stm32_adc_get_trig_extsel(indio_dev, trig) < 0 ? -EINVAL : 0;
1291 }
1292 
1293 static int stm32_adc_set_watermark(struct iio_dev *indio_dev, unsigned int val)
1294 {
1295 	struct stm32_adc *adc = iio_priv(indio_dev);
1296 	unsigned int watermark = STM32_DMA_BUFFER_SIZE / 2;
1297 	unsigned int rx_buf_sz = STM32_DMA_BUFFER_SIZE;
1298 
1299 	/*
1300 	 * dma cyclic transfers are used, buffer is split into two periods.
1301 	 * There should be :
1302 	 * - always one buffer (period) dma is working on
1303 	 * - one buffer (period) driver can push with iio_trigger_poll().
1304 	 */
1305 	watermark = min(watermark, val * (unsigned)(sizeof(u16)));
1306 	adc->rx_buf_sz = min(rx_buf_sz, watermark * 2 * adc->num_conv);
1307 
1308 	return 0;
1309 }
1310 
1311 static int stm32_adc_update_scan_mode(struct iio_dev *indio_dev,
1312 				      const unsigned long *scan_mask)
1313 {
1314 	struct stm32_adc *adc = iio_priv(indio_dev);
1315 	struct device *dev = indio_dev->dev.parent;
1316 	int ret;
1317 
1318 	ret = pm_runtime_get_sync(dev);
1319 	if (ret < 0) {
1320 		pm_runtime_put_noidle(dev);
1321 		return ret;
1322 	}
1323 
1324 	adc->num_conv = bitmap_weight(scan_mask, indio_dev->masklength);
1325 
1326 	ret = stm32_adc_conf_scan_seq(indio_dev, scan_mask);
1327 	pm_runtime_mark_last_busy(dev);
1328 	pm_runtime_put_autosuspend(dev);
1329 
1330 	return ret;
1331 }
1332 
1333 static int stm32_adc_of_xlate(struct iio_dev *indio_dev,
1334 			      const struct of_phandle_args *iiospec)
1335 {
1336 	int i;
1337 
1338 	for (i = 0; i < indio_dev->num_channels; i++)
1339 		if (indio_dev->channels[i].channel == iiospec->args[0])
1340 			return i;
1341 
1342 	return -EINVAL;
1343 }
1344 
1345 /**
1346  * stm32_adc_debugfs_reg_access - read or write register value
1347  * @indio_dev: IIO device structure
1348  * @reg: register offset
1349  * @writeval: value to write
1350  * @readval: value to read
1351  *
1352  * To read a value from an ADC register:
1353  *   echo [ADC reg offset] > direct_reg_access
1354  *   cat direct_reg_access
1355  *
1356  * To write a value in a ADC register:
1357  *   echo [ADC_reg_offset] [value] > direct_reg_access
1358  */
1359 static int stm32_adc_debugfs_reg_access(struct iio_dev *indio_dev,
1360 					unsigned reg, unsigned writeval,
1361 					unsigned *readval)
1362 {
1363 	struct stm32_adc *adc = iio_priv(indio_dev);
1364 	struct device *dev = indio_dev->dev.parent;
1365 	int ret;
1366 
1367 	ret = pm_runtime_get_sync(dev);
1368 	if (ret < 0) {
1369 		pm_runtime_put_noidle(dev);
1370 		return ret;
1371 	}
1372 
1373 	if (!readval)
1374 		stm32_adc_writel(adc, reg, writeval);
1375 	else
1376 		*readval = stm32_adc_readl(adc, reg);
1377 
1378 	pm_runtime_mark_last_busy(dev);
1379 	pm_runtime_put_autosuspend(dev);
1380 
1381 	return 0;
1382 }
1383 
1384 static const struct iio_info stm32_adc_iio_info = {
1385 	.read_raw = stm32_adc_read_raw,
1386 	.validate_trigger = stm32_adc_validate_trigger,
1387 	.hwfifo_set_watermark = stm32_adc_set_watermark,
1388 	.update_scan_mode = stm32_adc_update_scan_mode,
1389 	.debugfs_reg_access = stm32_adc_debugfs_reg_access,
1390 	.of_xlate = stm32_adc_of_xlate,
1391 };
1392 
1393 static unsigned int stm32_adc_dma_residue(struct stm32_adc *adc)
1394 {
1395 	struct dma_tx_state state;
1396 	enum dma_status status;
1397 
1398 	status = dmaengine_tx_status(adc->dma_chan,
1399 				     adc->dma_chan->cookie,
1400 				     &state);
1401 	if (status == DMA_IN_PROGRESS) {
1402 		/* Residue is size in bytes from end of buffer */
1403 		unsigned int i = adc->rx_buf_sz - state.residue;
1404 		unsigned int size;
1405 
1406 		/* Return available bytes */
1407 		if (i >= adc->bufi)
1408 			size = i - adc->bufi;
1409 		else
1410 			size = adc->rx_buf_sz + i - adc->bufi;
1411 
1412 		return size;
1413 	}
1414 
1415 	return 0;
1416 }
1417 
1418 static void stm32_adc_dma_buffer_done(void *data)
1419 {
1420 	struct iio_dev *indio_dev = data;
1421 	struct stm32_adc *adc = iio_priv(indio_dev);
1422 	int residue = stm32_adc_dma_residue(adc);
1423 
1424 	/*
1425 	 * In DMA mode the trigger services of IIO are not used
1426 	 * (e.g. no call to iio_trigger_poll).
1427 	 * Calling irq handler associated to the hardware trigger is not
1428 	 * relevant as the conversions have already been done. Data
1429 	 * transfers are performed directly in DMA callback instead.
1430 	 * This implementation avoids to call trigger irq handler that
1431 	 * may sleep, in an atomic context (DMA irq handler context).
1432 	 */
1433 	dev_dbg(&indio_dev->dev, "%s bufi=%d\n", __func__, adc->bufi);
1434 
1435 	while (residue >= indio_dev->scan_bytes) {
1436 		u16 *buffer = (u16 *)&adc->rx_buf[adc->bufi];
1437 
1438 		iio_push_to_buffers(indio_dev, buffer);
1439 
1440 		residue -= indio_dev->scan_bytes;
1441 		adc->bufi += indio_dev->scan_bytes;
1442 		if (adc->bufi >= adc->rx_buf_sz)
1443 			adc->bufi = 0;
1444 	}
1445 }
1446 
1447 static int stm32_adc_dma_start(struct iio_dev *indio_dev)
1448 {
1449 	struct stm32_adc *adc = iio_priv(indio_dev);
1450 	struct dma_async_tx_descriptor *desc;
1451 	dma_cookie_t cookie;
1452 	int ret;
1453 
1454 	if (!adc->dma_chan)
1455 		return 0;
1456 
1457 	dev_dbg(&indio_dev->dev, "%s size=%d watermark=%d\n", __func__,
1458 		adc->rx_buf_sz, adc->rx_buf_sz / 2);
1459 
1460 	/* Prepare a DMA cyclic transaction */
1461 	desc = dmaengine_prep_dma_cyclic(adc->dma_chan,
1462 					 adc->rx_dma_buf,
1463 					 adc->rx_buf_sz, adc->rx_buf_sz / 2,
1464 					 DMA_DEV_TO_MEM,
1465 					 DMA_PREP_INTERRUPT);
1466 	if (!desc)
1467 		return -EBUSY;
1468 
1469 	desc->callback = stm32_adc_dma_buffer_done;
1470 	desc->callback_param = indio_dev;
1471 
1472 	cookie = dmaengine_submit(desc);
1473 	ret = dma_submit_error(cookie);
1474 	if (ret) {
1475 		dmaengine_terminate_sync(adc->dma_chan);
1476 		return ret;
1477 	}
1478 
1479 	/* Issue pending DMA requests */
1480 	dma_async_issue_pending(adc->dma_chan);
1481 
1482 	return 0;
1483 }
1484 
1485 static int __stm32_adc_buffer_postenable(struct iio_dev *indio_dev)
1486 {
1487 	struct stm32_adc *adc = iio_priv(indio_dev);
1488 	struct device *dev = indio_dev->dev.parent;
1489 	int ret;
1490 
1491 	ret = pm_runtime_get_sync(dev);
1492 	if (ret < 0) {
1493 		pm_runtime_put_noidle(dev);
1494 		return ret;
1495 	}
1496 
1497 	ret = stm32_adc_set_trig(indio_dev, indio_dev->trig);
1498 	if (ret) {
1499 		dev_err(&indio_dev->dev, "Can't set trigger\n");
1500 		goto err_pm_put;
1501 	}
1502 
1503 	ret = stm32_adc_dma_start(indio_dev);
1504 	if (ret) {
1505 		dev_err(&indio_dev->dev, "Can't start dma\n");
1506 		goto err_clr_trig;
1507 	}
1508 
1509 	/* Reset adc buffer index */
1510 	adc->bufi = 0;
1511 
1512 	stm32_adc_ovr_irq_enable(adc);
1513 
1514 	if (!adc->dma_chan)
1515 		stm32_adc_conv_irq_enable(adc);
1516 
1517 	adc->cfg->start_conv(adc, !!adc->dma_chan);
1518 
1519 	return 0;
1520 
1521 err_clr_trig:
1522 	stm32_adc_set_trig(indio_dev, NULL);
1523 err_pm_put:
1524 	pm_runtime_mark_last_busy(dev);
1525 	pm_runtime_put_autosuspend(dev);
1526 
1527 	return ret;
1528 }
1529 
1530 static int stm32_adc_buffer_postenable(struct iio_dev *indio_dev)
1531 {
1532 	int ret;
1533 
1534 	ret = iio_triggered_buffer_postenable(indio_dev);
1535 	if (ret < 0)
1536 		return ret;
1537 
1538 	ret = __stm32_adc_buffer_postenable(indio_dev);
1539 	if (ret < 0)
1540 		iio_triggered_buffer_predisable(indio_dev);
1541 
1542 	return ret;
1543 }
1544 
1545 static void __stm32_adc_buffer_predisable(struct iio_dev *indio_dev)
1546 {
1547 	struct stm32_adc *adc = iio_priv(indio_dev);
1548 	struct device *dev = indio_dev->dev.parent;
1549 
1550 	adc->cfg->stop_conv(adc);
1551 	if (!adc->dma_chan)
1552 		stm32_adc_conv_irq_disable(adc);
1553 
1554 	stm32_adc_ovr_irq_disable(adc);
1555 
1556 	if (adc->dma_chan)
1557 		dmaengine_terminate_sync(adc->dma_chan);
1558 
1559 	if (stm32_adc_set_trig(indio_dev, NULL))
1560 		dev_err(&indio_dev->dev, "Can't clear trigger\n");
1561 
1562 	pm_runtime_mark_last_busy(dev);
1563 	pm_runtime_put_autosuspend(dev);
1564 }
1565 
1566 static int stm32_adc_buffer_predisable(struct iio_dev *indio_dev)
1567 {
1568 	int ret;
1569 
1570 	__stm32_adc_buffer_predisable(indio_dev);
1571 
1572 	ret = iio_triggered_buffer_predisable(indio_dev);
1573 	if (ret < 0)
1574 		dev_err(&indio_dev->dev, "predisable failed\n");
1575 
1576 	return ret;
1577 }
1578 
1579 static const struct iio_buffer_setup_ops stm32_adc_buffer_setup_ops = {
1580 	.postenable = &stm32_adc_buffer_postenable,
1581 	.predisable = &stm32_adc_buffer_predisable,
1582 };
1583 
1584 static irqreturn_t stm32_adc_trigger_handler(int irq, void *p)
1585 {
1586 	struct iio_poll_func *pf = p;
1587 	struct iio_dev *indio_dev = pf->indio_dev;
1588 	struct stm32_adc *adc = iio_priv(indio_dev);
1589 
1590 	dev_dbg(&indio_dev->dev, "%s bufi=%d\n", __func__, adc->bufi);
1591 
1592 	if (!adc->dma_chan) {
1593 		/* reset buffer index */
1594 		adc->bufi = 0;
1595 		iio_push_to_buffers_with_timestamp(indio_dev, adc->buffer,
1596 						   pf->timestamp);
1597 	} else {
1598 		int residue = stm32_adc_dma_residue(adc);
1599 
1600 		while (residue >= indio_dev->scan_bytes) {
1601 			u16 *buffer = (u16 *)&adc->rx_buf[adc->bufi];
1602 
1603 			iio_push_to_buffers_with_timestamp(indio_dev, buffer,
1604 							   pf->timestamp);
1605 			residue -= indio_dev->scan_bytes;
1606 			adc->bufi += indio_dev->scan_bytes;
1607 			if (adc->bufi >= adc->rx_buf_sz)
1608 				adc->bufi = 0;
1609 		}
1610 	}
1611 
1612 	iio_trigger_notify_done(indio_dev->trig);
1613 
1614 	/* re-enable eoc irq */
1615 	if (!adc->dma_chan)
1616 		stm32_adc_conv_irq_enable(adc);
1617 
1618 	return IRQ_HANDLED;
1619 }
1620 
1621 static const struct iio_chan_spec_ext_info stm32_adc_ext_info[] = {
1622 	IIO_ENUM("trigger_polarity", IIO_SHARED_BY_ALL, &stm32_adc_trig_pol),
1623 	{
1624 		.name = "trigger_polarity_available",
1625 		.shared = IIO_SHARED_BY_ALL,
1626 		.read = iio_enum_available_read,
1627 		.private = (uintptr_t)&stm32_adc_trig_pol,
1628 	},
1629 	{},
1630 };
1631 
1632 static int stm32_adc_of_get_resolution(struct iio_dev *indio_dev)
1633 {
1634 	struct device_node *node = indio_dev->dev.of_node;
1635 	struct stm32_adc *adc = iio_priv(indio_dev);
1636 	unsigned int i;
1637 	u32 res;
1638 
1639 	if (of_property_read_u32(node, "assigned-resolution-bits", &res))
1640 		res = adc->cfg->adc_info->resolutions[0];
1641 
1642 	for (i = 0; i < adc->cfg->adc_info->num_res; i++)
1643 		if (res == adc->cfg->adc_info->resolutions[i])
1644 			break;
1645 	if (i >= adc->cfg->adc_info->num_res) {
1646 		dev_err(&indio_dev->dev, "Bad resolution: %u bits\n", res);
1647 		return -EINVAL;
1648 	}
1649 
1650 	dev_dbg(&indio_dev->dev, "Using %u bits resolution\n", res);
1651 	adc->res = i;
1652 
1653 	return 0;
1654 }
1655 
1656 static void stm32_adc_smpr_init(struct stm32_adc *adc, int channel, u32 smp_ns)
1657 {
1658 	const struct stm32_adc_regs *smpr = &adc->cfg->regs->smp_bits[channel];
1659 	u32 period_ns, shift = smpr->shift, mask = smpr->mask;
1660 	unsigned int smp, r = smpr->reg;
1661 
1662 	/* Determine sampling time (ADC clock cycles) */
1663 	period_ns = NSEC_PER_SEC / adc->common->rate;
1664 	for (smp = 0; smp <= STM32_ADC_MAX_SMP; smp++)
1665 		if ((period_ns * adc->cfg->smp_cycles[smp]) >= smp_ns)
1666 			break;
1667 	if (smp > STM32_ADC_MAX_SMP)
1668 		smp = STM32_ADC_MAX_SMP;
1669 
1670 	/* pre-build sampling time registers (e.g. smpr1, smpr2) */
1671 	adc->smpr_val[r] = (adc->smpr_val[r] & ~mask) | (smp << shift);
1672 }
1673 
1674 static void stm32_adc_chan_init_one(struct iio_dev *indio_dev,
1675 				    struct iio_chan_spec *chan, u32 vinp,
1676 				    u32 vinn, int scan_index, bool differential)
1677 {
1678 	struct stm32_adc *adc = iio_priv(indio_dev);
1679 	char *name = adc->chan_name[vinp];
1680 
1681 	chan->type = IIO_VOLTAGE;
1682 	chan->channel = vinp;
1683 	if (differential) {
1684 		chan->differential = 1;
1685 		chan->channel2 = vinn;
1686 		snprintf(name, STM32_ADC_CH_SZ, "in%d-in%d", vinp, vinn);
1687 	} else {
1688 		snprintf(name, STM32_ADC_CH_SZ, "in%d", vinp);
1689 	}
1690 	chan->datasheet_name = name;
1691 	chan->scan_index = scan_index;
1692 	chan->indexed = 1;
1693 	chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
1694 	chan->info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |
1695 					 BIT(IIO_CHAN_INFO_OFFSET);
1696 	chan->scan_type.sign = 'u';
1697 	chan->scan_type.realbits = adc->cfg->adc_info->resolutions[adc->res];
1698 	chan->scan_type.storagebits = 16;
1699 	chan->ext_info = stm32_adc_ext_info;
1700 
1701 	/* pre-build selected channels mask */
1702 	adc->pcsel |= BIT(chan->channel);
1703 	if (differential) {
1704 		/* pre-build diff channels mask */
1705 		adc->difsel |= BIT(chan->channel);
1706 		/* Also add negative input to pre-selected channels */
1707 		adc->pcsel |= BIT(chan->channel2);
1708 	}
1709 }
1710 
1711 static int stm32_adc_chan_of_init(struct iio_dev *indio_dev)
1712 {
1713 	struct device_node *node = indio_dev->dev.of_node;
1714 	struct stm32_adc *adc = iio_priv(indio_dev);
1715 	const struct stm32_adc_info *adc_info = adc->cfg->adc_info;
1716 	struct stm32_adc_diff_channel diff[STM32_ADC_CH_MAX];
1717 	struct property *prop;
1718 	const __be32 *cur;
1719 	struct iio_chan_spec *channels;
1720 	int scan_index = 0, num_channels = 0, num_diff = 0, ret, i;
1721 	u32 val, smp = 0;
1722 
1723 	ret = of_property_count_u32_elems(node, "st,adc-channels");
1724 	if (ret > adc_info->max_channels) {
1725 		dev_err(&indio_dev->dev, "Bad st,adc-channels?\n");
1726 		return -EINVAL;
1727 	} else if (ret > 0) {
1728 		num_channels += ret;
1729 	}
1730 
1731 	ret = of_property_count_elems_of_size(node, "st,adc-diff-channels",
1732 					      sizeof(*diff));
1733 	if (ret > adc_info->max_channels) {
1734 		dev_err(&indio_dev->dev, "Bad st,adc-diff-channels?\n");
1735 		return -EINVAL;
1736 	} else if (ret > 0) {
1737 		int size = ret * sizeof(*diff) / sizeof(u32);
1738 
1739 		num_diff = ret;
1740 		num_channels += ret;
1741 		ret = of_property_read_u32_array(node, "st,adc-diff-channels",
1742 						 (u32 *)diff, size);
1743 		if (ret)
1744 			return ret;
1745 	}
1746 
1747 	if (!num_channels) {
1748 		dev_err(&indio_dev->dev, "No channels configured\n");
1749 		return -ENODATA;
1750 	}
1751 
1752 	/* Optional sample time is provided either for each, or all channels */
1753 	ret = of_property_count_u32_elems(node, "st,min-sample-time-nsecs");
1754 	if (ret > 1 && ret != num_channels) {
1755 		dev_err(&indio_dev->dev, "Invalid st,min-sample-time-nsecs\n");
1756 		return -EINVAL;
1757 	}
1758 
1759 	channels = devm_kcalloc(&indio_dev->dev, num_channels,
1760 				sizeof(struct iio_chan_spec), GFP_KERNEL);
1761 	if (!channels)
1762 		return -ENOMEM;
1763 
1764 	of_property_for_each_u32(node, "st,adc-channels", prop, cur, val) {
1765 		if (val >= adc_info->max_channels) {
1766 			dev_err(&indio_dev->dev, "Invalid channel %d\n", val);
1767 			return -EINVAL;
1768 		}
1769 
1770 		/* Channel can't be configured both as single-ended & diff */
1771 		for (i = 0; i < num_diff; i++) {
1772 			if (val == diff[i].vinp) {
1773 				dev_err(&indio_dev->dev,
1774 					"channel %d miss-configured\n",	val);
1775 				return -EINVAL;
1776 			}
1777 		}
1778 		stm32_adc_chan_init_one(indio_dev, &channels[scan_index], val,
1779 					0, scan_index, false);
1780 		scan_index++;
1781 	}
1782 
1783 	for (i = 0; i < num_diff; i++) {
1784 		if (diff[i].vinp >= adc_info->max_channels ||
1785 		    diff[i].vinn >= adc_info->max_channels) {
1786 			dev_err(&indio_dev->dev, "Invalid channel in%d-in%d\n",
1787 				diff[i].vinp, diff[i].vinn);
1788 			return -EINVAL;
1789 		}
1790 		stm32_adc_chan_init_one(indio_dev, &channels[scan_index],
1791 					diff[i].vinp, diff[i].vinn, scan_index,
1792 					true);
1793 		scan_index++;
1794 	}
1795 
1796 	for (i = 0; i < scan_index; i++) {
1797 		/*
1798 		 * Using of_property_read_u32_index(), smp value will only be
1799 		 * modified if valid u32 value can be decoded. This allows to
1800 		 * get either no value, 1 shared value for all indexes, or one
1801 		 * value per channel.
1802 		 */
1803 		of_property_read_u32_index(node, "st,min-sample-time-nsecs",
1804 					   i, &smp);
1805 		/* Prepare sampling time settings */
1806 		stm32_adc_smpr_init(adc, channels[i].channel, smp);
1807 	}
1808 
1809 	indio_dev->num_channels = scan_index;
1810 	indio_dev->channels = channels;
1811 
1812 	return 0;
1813 }
1814 
1815 static int stm32_adc_dma_request(struct device *dev, struct iio_dev *indio_dev)
1816 {
1817 	struct stm32_adc *adc = iio_priv(indio_dev);
1818 	struct dma_slave_config config;
1819 	int ret;
1820 
1821 	adc->dma_chan = dma_request_chan(dev, "rx");
1822 	if (IS_ERR(adc->dma_chan)) {
1823 		ret = PTR_ERR(adc->dma_chan);
1824 		if (ret != -ENODEV) {
1825 			if (ret != -EPROBE_DEFER)
1826 				dev_err(dev,
1827 					"DMA channel request failed with %d\n",
1828 					ret);
1829 			return ret;
1830 		}
1831 
1832 		/* DMA is optional: fall back to IRQ mode */
1833 		adc->dma_chan = NULL;
1834 		return 0;
1835 	}
1836 
1837 	adc->rx_buf = dma_alloc_coherent(adc->dma_chan->device->dev,
1838 					 STM32_DMA_BUFFER_SIZE,
1839 					 &adc->rx_dma_buf, GFP_KERNEL);
1840 	if (!adc->rx_buf) {
1841 		ret = -ENOMEM;
1842 		goto err_release;
1843 	}
1844 
1845 	/* Configure DMA channel to read data register */
1846 	memset(&config, 0, sizeof(config));
1847 	config.src_addr = (dma_addr_t)adc->common->phys_base;
1848 	config.src_addr += adc->offset + adc->cfg->regs->dr;
1849 	config.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
1850 
1851 	ret = dmaengine_slave_config(adc->dma_chan, &config);
1852 	if (ret)
1853 		goto err_free;
1854 
1855 	return 0;
1856 
1857 err_free:
1858 	dma_free_coherent(adc->dma_chan->device->dev, STM32_DMA_BUFFER_SIZE,
1859 			  adc->rx_buf, adc->rx_dma_buf);
1860 err_release:
1861 	dma_release_channel(adc->dma_chan);
1862 
1863 	return ret;
1864 }
1865 
1866 static int stm32_adc_probe(struct platform_device *pdev)
1867 {
1868 	struct iio_dev *indio_dev;
1869 	struct device *dev = &pdev->dev;
1870 	irqreturn_t (*handler)(int irq, void *p) = NULL;
1871 	struct stm32_adc *adc;
1872 	int ret;
1873 
1874 	if (!pdev->dev.of_node)
1875 		return -ENODEV;
1876 
1877 	indio_dev = devm_iio_device_alloc(&pdev->dev, sizeof(*adc));
1878 	if (!indio_dev)
1879 		return -ENOMEM;
1880 
1881 	adc = iio_priv(indio_dev);
1882 	adc->common = dev_get_drvdata(pdev->dev.parent);
1883 	spin_lock_init(&adc->lock);
1884 	init_completion(&adc->completion);
1885 	adc->cfg = (const struct stm32_adc_cfg *)
1886 		of_match_device(dev->driver->of_match_table, dev)->data;
1887 
1888 	indio_dev->name = dev_name(&pdev->dev);
1889 	indio_dev->dev.parent = &pdev->dev;
1890 	indio_dev->dev.of_node = pdev->dev.of_node;
1891 	indio_dev->info = &stm32_adc_iio_info;
1892 	indio_dev->modes = INDIO_DIRECT_MODE | INDIO_HARDWARE_TRIGGERED;
1893 
1894 	platform_set_drvdata(pdev, adc);
1895 
1896 	ret = of_property_read_u32(pdev->dev.of_node, "reg", &adc->offset);
1897 	if (ret != 0) {
1898 		dev_err(&pdev->dev, "missing reg property\n");
1899 		return -EINVAL;
1900 	}
1901 
1902 	adc->irq = platform_get_irq(pdev, 0);
1903 	if (adc->irq < 0)
1904 		return adc->irq;
1905 
1906 	ret = devm_request_threaded_irq(&pdev->dev, adc->irq, stm32_adc_isr,
1907 					stm32_adc_threaded_isr,
1908 					0, pdev->name, adc);
1909 	if (ret) {
1910 		dev_err(&pdev->dev, "failed to request IRQ\n");
1911 		return ret;
1912 	}
1913 
1914 	adc->clk = devm_clk_get(&pdev->dev, NULL);
1915 	if (IS_ERR(adc->clk)) {
1916 		ret = PTR_ERR(adc->clk);
1917 		if (ret == -ENOENT && !adc->cfg->clk_required) {
1918 			adc->clk = NULL;
1919 		} else {
1920 			dev_err(&pdev->dev, "Can't get clock\n");
1921 			return ret;
1922 		}
1923 	}
1924 
1925 	ret = stm32_adc_of_get_resolution(indio_dev);
1926 	if (ret < 0)
1927 		return ret;
1928 
1929 	ret = stm32_adc_chan_of_init(indio_dev);
1930 	if (ret < 0)
1931 		return ret;
1932 
1933 	ret = stm32_adc_dma_request(dev, indio_dev);
1934 	if (ret < 0)
1935 		return ret;
1936 
1937 	if (!adc->dma_chan)
1938 		handler = &stm32_adc_trigger_handler;
1939 
1940 	ret = iio_triggered_buffer_setup(indio_dev,
1941 					 &iio_pollfunc_store_time, handler,
1942 					 &stm32_adc_buffer_setup_ops);
1943 	if (ret) {
1944 		dev_err(&pdev->dev, "buffer setup failed\n");
1945 		goto err_dma_disable;
1946 	}
1947 
1948 	/* Get stm32-adc-core PM online */
1949 	pm_runtime_get_noresume(dev);
1950 	pm_runtime_set_active(dev);
1951 	pm_runtime_set_autosuspend_delay(dev, STM32_ADC_HW_STOP_DELAY_MS);
1952 	pm_runtime_use_autosuspend(dev);
1953 	pm_runtime_enable(dev);
1954 
1955 	ret = stm32_adc_hw_start(dev);
1956 	if (ret)
1957 		goto err_buffer_cleanup;
1958 
1959 	ret = iio_device_register(indio_dev);
1960 	if (ret) {
1961 		dev_err(&pdev->dev, "iio dev register failed\n");
1962 		goto err_hw_stop;
1963 	}
1964 
1965 	pm_runtime_mark_last_busy(dev);
1966 	pm_runtime_put_autosuspend(dev);
1967 
1968 	return 0;
1969 
1970 err_hw_stop:
1971 	stm32_adc_hw_stop(dev);
1972 
1973 err_buffer_cleanup:
1974 	pm_runtime_disable(dev);
1975 	pm_runtime_set_suspended(dev);
1976 	pm_runtime_put_noidle(dev);
1977 	iio_triggered_buffer_cleanup(indio_dev);
1978 
1979 err_dma_disable:
1980 	if (adc->dma_chan) {
1981 		dma_free_coherent(adc->dma_chan->device->dev,
1982 				  STM32_DMA_BUFFER_SIZE,
1983 				  adc->rx_buf, adc->rx_dma_buf);
1984 		dma_release_channel(adc->dma_chan);
1985 	}
1986 
1987 	return ret;
1988 }
1989 
1990 static int stm32_adc_remove(struct platform_device *pdev)
1991 {
1992 	struct stm32_adc *adc = platform_get_drvdata(pdev);
1993 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
1994 
1995 	pm_runtime_get_sync(&pdev->dev);
1996 	iio_device_unregister(indio_dev);
1997 	stm32_adc_hw_stop(&pdev->dev);
1998 	pm_runtime_disable(&pdev->dev);
1999 	pm_runtime_set_suspended(&pdev->dev);
2000 	pm_runtime_put_noidle(&pdev->dev);
2001 	iio_triggered_buffer_cleanup(indio_dev);
2002 	if (adc->dma_chan) {
2003 		dma_free_coherent(adc->dma_chan->device->dev,
2004 				  STM32_DMA_BUFFER_SIZE,
2005 				  adc->rx_buf, adc->rx_dma_buf);
2006 		dma_release_channel(adc->dma_chan);
2007 	}
2008 
2009 	return 0;
2010 }
2011 
2012 #if defined(CONFIG_PM_SLEEP)
2013 static int stm32_adc_suspend(struct device *dev)
2014 {
2015 	struct stm32_adc *adc = dev_get_drvdata(dev);
2016 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
2017 
2018 	if (iio_buffer_enabled(indio_dev))
2019 		__stm32_adc_buffer_predisable(indio_dev);
2020 
2021 	return pm_runtime_force_suspend(dev);
2022 }
2023 
2024 static int stm32_adc_resume(struct device *dev)
2025 {
2026 	struct stm32_adc *adc = dev_get_drvdata(dev);
2027 	struct iio_dev *indio_dev = iio_priv_to_dev(adc);
2028 	int ret;
2029 
2030 	ret = pm_runtime_force_resume(dev);
2031 	if (ret < 0)
2032 		return ret;
2033 
2034 	if (!iio_buffer_enabled(indio_dev))
2035 		return 0;
2036 
2037 	ret = stm32_adc_update_scan_mode(indio_dev,
2038 					 indio_dev->active_scan_mask);
2039 	if (ret < 0)
2040 		return ret;
2041 
2042 	return __stm32_adc_buffer_postenable(indio_dev);
2043 }
2044 #endif
2045 
2046 #if defined(CONFIG_PM)
2047 static int stm32_adc_runtime_suspend(struct device *dev)
2048 {
2049 	return stm32_adc_hw_stop(dev);
2050 }
2051 
2052 static int stm32_adc_runtime_resume(struct device *dev)
2053 {
2054 	return stm32_adc_hw_start(dev);
2055 }
2056 #endif
2057 
2058 static const struct dev_pm_ops stm32_adc_pm_ops = {
2059 	SET_SYSTEM_SLEEP_PM_OPS(stm32_adc_suspend, stm32_adc_resume)
2060 	SET_RUNTIME_PM_OPS(stm32_adc_runtime_suspend, stm32_adc_runtime_resume,
2061 			   NULL)
2062 };
2063 
2064 static const struct stm32_adc_cfg stm32f4_adc_cfg = {
2065 	.regs = &stm32f4_adc_regspec,
2066 	.adc_info = &stm32f4_adc_info,
2067 	.trigs = stm32f4_adc_trigs,
2068 	.clk_required = true,
2069 	.start_conv = stm32f4_adc_start_conv,
2070 	.stop_conv = stm32f4_adc_stop_conv,
2071 	.smp_cycles = stm32f4_adc_smp_cycles,
2072 };
2073 
2074 static const struct stm32_adc_cfg stm32h7_adc_cfg = {
2075 	.regs = &stm32h7_adc_regspec,
2076 	.adc_info = &stm32h7_adc_info,
2077 	.trigs = stm32h7_adc_trigs,
2078 	.start_conv = stm32h7_adc_start_conv,
2079 	.stop_conv = stm32h7_adc_stop_conv,
2080 	.prepare = stm32h7_adc_prepare,
2081 	.unprepare = stm32h7_adc_unprepare,
2082 	.smp_cycles = stm32h7_adc_smp_cycles,
2083 };
2084 
2085 static const struct stm32_adc_cfg stm32mp1_adc_cfg = {
2086 	.regs = &stm32h7_adc_regspec,
2087 	.adc_info = &stm32h7_adc_info,
2088 	.trigs = stm32h7_adc_trigs,
2089 	.has_vregready = true,
2090 	.start_conv = stm32h7_adc_start_conv,
2091 	.stop_conv = stm32h7_adc_stop_conv,
2092 	.prepare = stm32h7_adc_prepare,
2093 	.unprepare = stm32h7_adc_unprepare,
2094 	.smp_cycles = stm32h7_adc_smp_cycles,
2095 };
2096 
2097 static const struct of_device_id stm32_adc_of_match[] = {
2098 	{ .compatible = "st,stm32f4-adc", .data = (void *)&stm32f4_adc_cfg },
2099 	{ .compatible = "st,stm32h7-adc", .data = (void *)&stm32h7_adc_cfg },
2100 	{ .compatible = "st,stm32mp1-adc", .data = (void *)&stm32mp1_adc_cfg },
2101 	{},
2102 };
2103 MODULE_DEVICE_TABLE(of, stm32_adc_of_match);
2104 
2105 static struct platform_driver stm32_adc_driver = {
2106 	.probe = stm32_adc_probe,
2107 	.remove = stm32_adc_remove,
2108 	.driver = {
2109 		.name = "stm32-adc",
2110 		.of_match_table = stm32_adc_of_match,
2111 		.pm = &stm32_adc_pm_ops,
2112 	},
2113 };
2114 module_platform_driver(stm32_adc_driver);
2115 
2116 MODULE_AUTHOR("Fabrice Gasnier <fabrice.gasnier@st.com>");
2117 MODULE_DESCRIPTION("STMicroelectronics STM32 ADC IIO driver");
2118 MODULE_LICENSE("GPL v2");
2119 MODULE_ALIAS("platform:stm32-adc");
2120