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