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