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