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