xref: /linux/drivers/iio/adc/stm32-adc.c (revision d2c9a99135da931377240942d44f3dea104cedb8)
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/array_size.h>
10 #include <linux/clk.h>
11 #include <linux/debugfs.h>
12 #include <linux/delay.h>
13 #include <linux/dma-mapping.h>
14 #include <linux/dmaengine.h>
15 #include <linux/iio/iio.h>
16 #include <linux/iio/buffer.h>
17 #include <linux/iio/timer/stm32-lptim-trigger.h>
18 #include <linux/iio/timer/stm32-timer-trigger.h>
19 #include <linux/iio/trigger.h>
20 #include <linux/iio/trigger_consumer.h>
21 #include <linux/iio/triggered_buffer.h>
22 #include <linux/interrupt.h>
23 #include <linux/io.h>
24 #include <linux/iopoll.h>
25 #include <linux/module.h>
26 #include <linux/nvmem-consumer.h>
27 #include <linux/platform_device.h>
28 #include <linux/pm_runtime.h>
29 #include <linux/property.h>
30 
31 #include "stm32-adc-core.h"
32 
33 /* Number of linear calibration shadow registers / LINCALRDYW control bits */
34 #define STM32H7_LINCALFACT_NUM		6
35 
36 /* BOOST bit must be set on STM32H7 when ADC clock is above 20MHz */
37 #define STM32H7_BOOST_CLKRATE		20000000UL
38 
39 #define STM32_ADC_CH_MAX		20	/* max number of channels */
40 #define STM32_ADC_CH_SZ			16	/* max channel name size */
41 #define STM32_ADC_MAX_SQ		16	/* SQ1..SQ16 */
42 #define STM32_ADC_MAX_SMP		7	/* SMPx range is [0..7] */
43 #define STM32_ADC_TIMEOUT_US		100000
44 #define STM32_ADC_TIMEOUT	(msecs_to_jiffies(STM32_ADC_TIMEOUT_US / 1000))
45 #define STM32_ADC_HW_STOP_DELAY_MS	100
46 #define STM32_ADC_VREFINT_VOLTAGE	3300
47 
48 #define STM32_DMA_BUFFER_SIZE		PAGE_SIZE
49 
50 /* External trigger enable */
51 enum stm32_adc_exten {
52 	STM32_EXTEN_SWTRIG,
53 	STM32_EXTEN_HWTRIG_RISING_EDGE,
54 	STM32_EXTEN_HWTRIG_FALLING_EDGE,
55 	STM32_EXTEN_HWTRIG_BOTH_EDGES,
56 };
57 
58 /* extsel - trigger mux selection value */
59 enum stm32_adc_extsel {
60 	STM32_EXT0,
61 	STM32_EXT1,
62 	STM32_EXT2,
63 	STM32_EXT3,
64 	STM32_EXT4,
65 	STM32_EXT5,
66 	STM32_EXT6,
67 	STM32_EXT7,
68 	STM32_EXT8,
69 	STM32_EXT9,
70 	STM32_EXT10,
71 	STM32_EXT11,
72 	STM32_EXT12,
73 	STM32_EXT13,
74 	STM32_EXT14,
75 	STM32_EXT15,
76 	STM32_EXT16,
77 	STM32_EXT17,
78 	STM32_EXT18,
79 	STM32_EXT19,
80 	STM32_EXT20,
81 };
82 
83 enum stm32_adc_int_ch {
84 	STM32_ADC_INT_CH_NONE = -1,
85 	STM32_ADC_INT_CH_VDDCORE,
86 	STM32_ADC_INT_CH_VDDCPU,
87 	STM32_ADC_INT_CH_VDDQ_DDR,
88 	STM32_ADC_INT_CH_VREFINT,
89 	STM32_ADC_INT_CH_VBAT,
90 	STM32_ADC_INT_CH_NB,
91 };
92 
93 /**
94  * struct stm32_adc_ic - ADC internal channels
95  * @name:	name of the internal channel
96  * @idx:	internal channel enum index
97  */
98 struct stm32_adc_ic {
99 	const char *name;
100 	u32 idx;
101 };
102 
103 static const struct stm32_adc_ic stm32_adc_ic[STM32_ADC_INT_CH_NB] = {
104 	{ "vddcore", STM32_ADC_INT_CH_VDDCORE },
105 	{ "vddcpu", STM32_ADC_INT_CH_VDDCPU },
106 	{ "vddq_ddr", STM32_ADC_INT_CH_VDDQ_DDR },
107 	{ "vrefint", STM32_ADC_INT_CH_VREFINT },
108 	{ "vbat", STM32_ADC_INT_CH_VBAT },
109 };
110 
111 /**
112  * struct stm32_adc_trig_info - ADC trigger info
113  * @name:		name of the trigger, corresponding to its source
114  * @extsel:		trigger selection
115  */
116 struct stm32_adc_trig_info {
117 	const char *name;
118 	enum stm32_adc_extsel extsel;
119 };
120 
121 /**
122  * struct stm32_adc_calib - optional adc calibration data
123  * @lincalfact: Linearity calibration factor
124  * @lincal_saved: Indicates that linear calibration factors are saved
125  */
126 struct stm32_adc_calib {
127 	u32			lincalfact[STM32H7_LINCALFACT_NUM];
128 	bool			lincal_saved;
129 };
130 
131 /**
132  * struct stm32_adc_regs - stm32 ADC misc registers & bitfield desc
133  * @reg:		register offset
134  * @mask:		bitfield mask
135  * @shift:		left shift
136  */
137 struct stm32_adc_regs {
138 	int reg;
139 	int mask;
140 	int shift;
141 };
142 
143 /**
144  * struct stm32_adc_vrefint - stm32 ADC internal reference voltage data
145  * @vrefint_cal:	vrefint calibration value from nvmem
146  * @vrefint_data:	vrefint actual value
147  */
148 struct stm32_adc_vrefint {
149 	u32 vrefint_cal;
150 	u32 vrefint_data;
151 };
152 
153 /**
154  * struct stm32_adc_regspec - stm32 registers definition
155  * @dr:			data register offset
156  * @ier_eoc:		interrupt enable register & eocie bitfield
157  * @ier_ovr:		interrupt enable register & overrun bitfield
158  * @isr_eoc:		interrupt status register & eoc bitfield
159  * @isr_ovr:		interrupt status register & overrun bitfield
160  * @sqr:		reference to sequence registers array
161  * @exten:		trigger control register & bitfield
162  * @extsel:		trigger selection register & bitfield
163  * @res:		resolution selection register & bitfield
164  * @difsel:		differential mode selection register & bitfield
165  * @smpr:		smpr1 & smpr2 registers offset array
166  * @smp_bits:		smpr1 & smpr2 index and bitfields
167  * @or_vddcore:		option register & vddcore bitfield
168  * @or_vddcpu:		option register & vddcpu bitfield
169  * @or_vddq_ddr:	option register & vddq_ddr bitfield
170  * @ccr_vbat:		common register & vbat bitfield
171  * @ccr_vref:		common register & vrefint bitfield
172  */
173 struct stm32_adc_regspec {
174 	const u32 dr;
175 	const struct stm32_adc_regs ier_eoc;
176 	const struct stm32_adc_regs ier_ovr;
177 	const struct stm32_adc_regs isr_eoc;
178 	const struct stm32_adc_regs isr_ovr;
179 	const struct stm32_adc_regs *sqr;
180 	const struct stm32_adc_regs exten;
181 	const struct stm32_adc_regs extsel;
182 	const struct stm32_adc_regs res;
183 	const struct stm32_adc_regs difsel;
184 	const u32 smpr[2];
185 	const struct stm32_adc_regs *smp_bits;
186 	const struct stm32_adc_regs or_vddcore;
187 	const struct stm32_adc_regs or_vddcpu;
188 	const struct stm32_adc_regs or_vddq_ddr;
189 	const struct stm32_adc_regs ccr_vbat;
190 	const struct stm32_adc_regs ccr_vref;
191 };
192 
193 struct stm32_adc;
194 
195 /**
196  * struct stm32_adc_cfg - stm32 compatible configuration data
197  * @regs:		registers descriptions
198  * @adc_info:		per instance input channels definitions
199  * @trigs:		external trigger sources
200  * @clk_required:	clock is required
201  * @has_vregready:	vregready status flag presence
202  * @has_boostmode:	boost mode support flag
203  * @has_linearcal:	linear calibration support flag
204  * @has_presel:		channel preselection support flag
205  * @has_oversampling:	oversampling support flag
206  * @prepare:		optional prepare routine (power-up, enable)
207  * @start_conv:		routine to start conversions
208  * @stop_conv:		routine to stop conversions
209  * @unprepare:		optional unprepare routine (disable, power-down)
210  * @irq_clear:		routine to clear irqs
211  * @set_ovs:		routine to set oversampling configuration
212  * @smp_cycles:		programmable sampling time (ADC clock cycles)
213  * @ts_int_ch:		pointer to array of internal channels minimum sampling time in ns
214  */
215 struct stm32_adc_cfg {
216 	const struct stm32_adc_regspec	*regs;
217 	const struct stm32_adc_info	*adc_info;
218 	const struct stm32_adc_trig_info *trigs;
219 	bool clk_required;
220 	bool has_vregready;
221 	bool has_boostmode;
222 	bool has_linearcal;
223 	bool has_presel;
224 	bool has_oversampling;
225 	int (*prepare)(struct iio_dev *);
226 	void (*start_conv)(struct iio_dev *, bool dma);
227 	void (*stop_conv)(struct iio_dev *);
228 	void (*unprepare)(struct iio_dev *);
229 	void (*irq_clear)(struct iio_dev *indio_dev, u32 msk);
230 	void (*set_ovs)(struct iio_dev *indio_dev, u32 ovs_idx);
231 	const unsigned int *smp_cycles;
232 	const unsigned int *ts_int_ch;
233 };
234 
235 /**
236  * struct stm32_adc - private data of each ADC IIO instance
237  * @common:		reference to ADC block common data
238  * @offset:		ADC instance register offset in ADC block
239  * @cfg:		compatible configuration data
240  * @completion:		end of single conversion completion
241  * @buffer:		data buffer + 8 bytes for timestamp if enabled
242  * @clk:		clock for this adc instance
243  * @irq:		interrupt for this adc instance
244  * @lock:		spinlock
245  * @bufi:		data buffer index
246  * @num_conv:		expected number of scan conversions
247  * @res:		data resolution (e.g. RES bitfield value)
248  * @trigger_polarity:	external trigger polarity (e.g. exten)
249  * @dma_chan:		dma channel
250  * @rx_buf:		dma rx buffer cpu address
251  * @rx_dma_buf:		dma rx buffer bus address
252  * @rx_buf_sz:		dma rx buffer size
253  * @difsel:		bitmask to set single-ended/differential channel
254  * @pcsel:		bitmask to preselect channels on some devices
255  * @smpr_val:		sampling time settings (e.g. smpr1 / smpr2)
256  * @cal:		optional calibration data on some devices
257  * @vrefint:		internal reference voltage data
258  * @chan_name:		channel name array
259  * @num_diff:		number of differential channels
260  * @int_ch:		internal channel indexes array
261  * @nsmps:		number of channels with optional sample time
262  * @ovs_idx:		current oversampling ratio index (in oversampling array)
263  */
264 struct stm32_adc {
265 	struct stm32_adc_common	*common;
266 	u32			offset;
267 	const struct stm32_adc_cfg	*cfg;
268 	struct completion	completion;
269 	u16			buffer[STM32_ADC_MAX_SQ + 4] __aligned(8);
270 	struct clk		*clk;
271 	int			irq;
272 	spinlock_t		lock;		/* interrupt lock */
273 	unsigned int		bufi;
274 	unsigned int		num_conv;
275 	u32			res;
276 	u32			trigger_polarity;
277 	struct dma_chan		*dma_chan;
278 	u8			*rx_buf;
279 	dma_addr_t		rx_dma_buf;
280 	unsigned int		rx_buf_sz;
281 	u32			difsel;
282 	u32			pcsel;
283 	u32			smpr_val[2];
284 	struct stm32_adc_calib	cal;
285 	struct stm32_adc_vrefint vrefint;
286 	char			chan_name[STM32_ADC_CH_MAX][STM32_ADC_CH_SZ];
287 	u32			num_diff;
288 	int			int_ch[STM32_ADC_INT_CH_NB];
289 	int			nsmps;
290 	int			ovs_idx;
291 };
292 
293 struct stm32_adc_diff_channel {
294 	u32 vinp;
295 	u32 vinn;
296 };
297 
298 /**
299  * struct stm32_adc_info - stm32 ADC, per instance config data
300  * @max_channels:	Number of channels
301  * @resolutions:	available resolutions
302  * @oversampling:	available oversampling ratios
303  * @num_res:		number of available resolutions
304  * @num_ovs:		number of available oversampling ratios
305  */
306 struct stm32_adc_info {
307 	int max_channels;
308 	const unsigned int *resolutions;
309 	const unsigned int *oversampling;
310 	const unsigned int num_res;
311 	const unsigned int num_ovs;
312 };
313 
314 static const unsigned int stm32h7_adc_oversampling_avail[] = {
315 	1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024,
316 };
317 
318 static const unsigned int stm32mp13_adc_oversampling_avail[] = {
319 	1, 2, 4, 8, 16, 32, 64, 128, 256,
320 };
321 
322 static const unsigned int stm32f4_adc_resolutions[] = {
323 	/* sorted values so the index matches RES[1:0] in STM32F4_ADC_CR1 */
324 	12, 10, 8, 6,
325 };
326 
327 /* stm32f4 can have up to 16 channels */
328 static const struct stm32_adc_info stm32f4_adc_info = {
329 	.max_channels = 16,
330 	.resolutions = stm32f4_adc_resolutions,
331 	.num_res = ARRAY_SIZE(stm32f4_adc_resolutions),
332 };
333 
334 static const unsigned int stm32h7_adc_resolutions[] = {
335 	/* sorted values so the index matches RES[2:0] in STM32H7_ADC_CFGR */
336 	16, 14, 12, 10, 8,
337 };
338 
339 /* stm32h7 can have up to 20 channels */
340 static const struct stm32_adc_info stm32h7_adc_info = {
341 	.max_channels = STM32_ADC_CH_MAX,
342 	.resolutions = stm32h7_adc_resolutions,
343 	.oversampling = stm32h7_adc_oversampling_avail,
344 	.num_res = ARRAY_SIZE(stm32h7_adc_resolutions),
345 	.num_ovs = ARRAY_SIZE(stm32h7_adc_oversampling_avail),
346 };
347 
348 /* stm32mp13 can have up to 19 channels */
349 static const struct stm32_adc_info stm32mp13_adc_info = {
350 	.max_channels = 19,
351 	.resolutions = stm32f4_adc_resolutions,
352 	.oversampling = stm32mp13_adc_oversampling_avail,
353 	.num_res = ARRAY_SIZE(stm32f4_adc_resolutions),
354 	.num_ovs = ARRAY_SIZE(stm32mp13_adc_oversampling_avail),
355 };
356 
357 /*
358  * stm32f4_sq - describe regular sequence registers
359  * - L: sequence len (register & bit field)
360  * - SQ1..SQ16: sequence entries (register & bit field)
361  */
362 static const struct stm32_adc_regs stm32f4_sq[STM32_ADC_MAX_SQ + 1] = {
363 	/* L: len bit field description to be kept as first element */
364 	{ STM32F4_ADC_SQR1, GENMASK(23, 20), 20 },
365 	/* SQ1..SQ16 registers & bit fields (reg, mask, shift) */
366 	{ STM32F4_ADC_SQR3, GENMASK(4, 0), 0 },
367 	{ STM32F4_ADC_SQR3, GENMASK(9, 5), 5 },
368 	{ STM32F4_ADC_SQR3, GENMASK(14, 10), 10 },
369 	{ STM32F4_ADC_SQR3, GENMASK(19, 15), 15 },
370 	{ STM32F4_ADC_SQR3, GENMASK(24, 20), 20 },
371 	{ STM32F4_ADC_SQR3, GENMASK(29, 25), 25 },
372 	{ STM32F4_ADC_SQR2, GENMASK(4, 0), 0 },
373 	{ STM32F4_ADC_SQR2, GENMASK(9, 5), 5 },
374 	{ STM32F4_ADC_SQR2, GENMASK(14, 10), 10 },
375 	{ STM32F4_ADC_SQR2, GENMASK(19, 15), 15 },
376 	{ STM32F4_ADC_SQR2, GENMASK(24, 20), 20 },
377 	{ STM32F4_ADC_SQR2, GENMASK(29, 25), 25 },
378 	{ STM32F4_ADC_SQR1, GENMASK(4, 0), 0 },
379 	{ STM32F4_ADC_SQR1, GENMASK(9, 5), 5 },
380 	{ STM32F4_ADC_SQR1, GENMASK(14, 10), 10 },
381 	{ STM32F4_ADC_SQR1, GENMASK(19, 15), 15 },
382 };
383 
384 /* STM32F4 external trigger sources for all instances */
385 static const struct stm32_adc_trig_info stm32f4_adc_trigs[] = {
386 	{ TIM1_CH1, STM32_EXT0 },
387 	{ TIM1_CH2, STM32_EXT1 },
388 	{ TIM1_CH3, STM32_EXT2 },
389 	{ TIM2_CH2, STM32_EXT3 },
390 	{ TIM2_CH3, STM32_EXT4 },
391 	{ TIM2_CH4, STM32_EXT5 },
392 	{ TIM2_TRGO, STM32_EXT6 },
393 	{ TIM3_CH1, STM32_EXT7 },
394 	{ TIM3_TRGO, STM32_EXT8 },
395 	{ TIM4_CH4, STM32_EXT9 },
396 	{ TIM5_CH1, STM32_EXT10 },
397 	{ TIM5_CH2, STM32_EXT11 },
398 	{ TIM5_CH3, STM32_EXT12 },
399 	{ TIM8_CH1, STM32_EXT13 },
400 	{ TIM8_TRGO, STM32_EXT14 },
401 	{}, /* sentinel */
402 };
403 
404 /*
405  * stm32f4_smp_bits[] - describe sampling time register index & bit fields
406  * Sorted so it can be indexed by channel number.
407  */
408 static const struct stm32_adc_regs stm32f4_smp_bits[] = {
409 	/* STM32F4_ADC_SMPR2: smpr[] index, mask, shift for SMP0 to SMP9 */
410 	{ 1, GENMASK(2, 0), 0 },
411 	{ 1, GENMASK(5, 3), 3 },
412 	{ 1, GENMASK(8, 6), 6 },
413 	{ 1, GENMASK(11, 9), 9 },
414 	{ 1, GENMASK(14, 12), 12 },
415 	{ 1, GENMASK(17, 15), 15 },
416 	{ 1, GENMASK(20, 18), 18 },
417 	{ 1, GENMASK(23, 21), 21 },
418 	{ 1, GENMASK(26, 24), 24 },
419 	{ 1, GENMASK(29, 27), 27 },
420 	/* STM32F4_ADC_SMPR1, smpr[] index, mask, shift for SMP10 to SMP18 */
421 	{ 0, GENMASK(2, 0), 0 },
422 	{ 0, GENMASK(5, 3), 3 },
423 	{ 0, GENMASK(8, 6), 6 },
424 	{ 0, GENMASK(11, 9), 9 },
425 	{ 0, GENMASK(14, 12), 12 },
426 	{ 0, GENMASK(17, 15), 15 },
427 	{ 0, GENMASK(20, 18), 18 },
428 	{ 0, GENMASK(23, 21), 21 },
429 	{ 0, GENMASK(26, 24), 24 },
430 };
431 
432 /* STM32F4 programmable sampling time (ADC clock cycles) */
433 static const unsigned int stm32f4_adc_smp_cycles[STM32_ADC_MAX_SMP + 1] = {
434 	3, 15, 28, 56, 84, 112, 144, 480,
435 };
436 
437 static const struct stm32_adc_regspec stm32f4_adc_regspec = {
438 	.dr = STM32F4_ADC_DR,
439 	.ier_eoc = { STM32F4_ADC_CR1, STM32F4_EOCIE },
440 	.ier_ovr = { STM32F4_ADC_CR1, STM32F4_OVRIE },
441 	.isr_eoc = { STM32F4_ADC_SR, STM32F4_EOC },
442 	.isr_ovr = { STM32F4_ADC_SR, STM32F4_OVR },
443 	.sqr = stm32f4_sq,
444 	.exten = { STM32F4_ADC_CR2, STM32F4_EXTEN_MASK, STM32F4_EXTEN_SHIFT },
445 	.extsel = { STM32F4_ADC_CR2, STM32F4_EXTSEL_MASK,
446 		    STM32F4_EXTSEL_SHIFT },
447 	.res = { STM32F4_ADC_CR1, STM32F4_RES_MASK, STM32F4_RES_SHIFT },
448 	.smpr = { STM32F4_ADC_SMPR1, STM32F4_ADC_SMPR2 },
449 	.smp_bits = stm32f4_smp_bits,
450 };
451 
452 static const struct stm32_adc_regs stm32h7_sq[STM32_ADC_MAX_SQ + 1] = {
453 	/* L: len bit field description to be kept as first element */
454 	{ STM32H7_ADC_SQR1, GENMASK(3, 0), 0 },
455 	/* SQ1..SQ16 registers & bit fields (reg, mask, shift) */
456 	{ STM32H7_ADC_SQR1, GENMASK(10, 6), 6 },
457 	{ STM32H7_ADC_SQR1, GENMASK(16, 12), 12 },
458 	{ STM32H7_ADC_SQR1, GENMASK(22, 18), 18 },
459 	{ STM32H7_ADC_SQR1, GENMASK(28, 24), 24 },
460 	{ STM32H7_ADC_SQR2, GENMASK(4, 0), 0 },
461 	{ STM32H7_ADC_SQR2, GENMASK(10, 6), 6 },
462 	{ STM32H7_ADC_SQR2, GENMASK(16, 12), 12 },
463 	{ STM32H7_ADC_SQR2, GENMASK(22, 18), 18 },
464 	{ STM32H7_ADC_SQR2, GENMASK(28, 24), 24 },
465 	{ STM32H7_ADC_SQR3, GENMASK(4, 0), 0 },
466 	{ STM32H7_ADC_SQR3, GENMASK(10, 6), 6 },
467 	{ STM32H7_ADC_SQR3, GENMASK(16, 12), 12 },
468 	{ STM32H7_ADC_SQR3, GENMASK(22, 18), 18 },
469 	{ STM32H7_ADC_SQR3, GENMASK(28, 24), 24 },
470 	{ STM32H7_ADC_SQR4, GENMASK(4, 0), 0 },
471 	{ STM32H7_ADC_SQR4, GENMASK(10, 6), 6 },
472 };
473 
474 /* STM32H7 external trigger sources for all instances */
475 static const struct stm32_adc_trig_info stm32h7_adc_trigs[] = {
476 	{ TIM1_CH1, STM32_EXT0 },
477 	{ TIM1_CH2, STM32_EXT1 },
478 	{ TIM1_CH3, STM32_EXT2 },
479 	{ TIM2_CH2, STM32_EXT3 },
480 	{ TIM3_TRGO, STM32_EXT4 },
481 	{ TIM4_CH4, STM32_EXT5 },
482 	{ TIM8_TRGO, STM32_EXT7 },
483 	{ TIM8_TRGO2, STM32_EXT8 },
484 	{ TIM1_TRGO, STM32_EXT9 },
485 	{ TIM1_TRGO2, STM32_EXT10 },
486 	{ TIM2_TRGO, STM32_EXT11 },
487 	{ TIM4_TRGO, STM32_EXT12 },
488 	{ TIM6_TRGO, STM32_EXT13 },
489 	{ TIM15_TRGO, STM32_EXT14 },
490 	{ TIM3_CH4, STM32_EXT15 },
491 	{ LPTIM1_OUT, STM32_EXT18 },
492 	{ LPTIM2_OUT, STM32_EXT19 },
493 	{ LPTIM3_OUT, STM32_EXT20 },
494 	{ }
495 };
496 
497 /*
498  * stm32h7_smp_bits - describe sampling time register index & bit fields
499  * Sorted so it can be indexed by channel number.
500  */
501 static const struct stm32_adc_regs stm32h7_smp_bits[] = {
502 	/* STM32H7_ADC_SMPR1, smpr[] index, mask, shift for SMP0 to SMP9 */
503 	{ 0, GENMASK(2, 0), 0 },
504 	{ 0, GENMASK(5, 3), 3 },
505 	{ 0, GENMASK(8, 6), 6 },
506 	{ 0, GENMASK(11, 9), 9 },
507 	{ 0, GENMASK(14, 12), 12 },
508 	{ 0, GENMASK(17, 15), 15 },
509 	{ 0, GENMASK(20, 18), 18 },
510 	{ 0, GENMASK(23, 21), 21 },
511 	{ 0, GENMASK(26, 24), 24 },
512 	{ 0, GENMASK(29, 27), 27 },
513 	/* STM32H7_ADC_SMPR2, smpr[] index, mask, shift for SMP10 to SMP19 */
514 	{ 1, GENMASK(2, 0), 0 },
515 	{ 1, GENMASK(5, 3), 3 },
516 	{ 1, GENMASK(8, 6), 6 },
517 	{ 1, GENMASK(11, 9), 9 },
518 	{ 1, GENMASK(14, 12), 12 },
519 	{ 1, GENMASK(17, 15), 15 },
520 	{ 1, GENMASK(20, 18), 18 },
521 	{ 1, GENMASK(23, 21), 21 },
522 	{ 1, GENMASK(26, 24), 24 },
523 	{ 1, GENMASK(29, 27), 27 },
524 };
525 
526 /* STM32H7 programmable sampling time (ADC clock cycles, rounded down) */
527 static const unsigned int stm32h7_adc_smp_cycles[STM32_ADC_MAX_SMP + 1] = {
528 	1, 2, 8, 16, 32, 64, 387, 810,
529 };
530 
531 static const struct stm32_adc_regspec stm32h7_adc_regspec = {
532 	.dr = STM32H7_ADC_DR,
533 	.ier_eoc = { STM32H7_ADC_IER, STM32H7_EOCIE },
534 	.ier_ovr = { STM32H7_ADC_IER, STM32H7_OVRIE },
535 	.isr_eoc = { STM32H7_ADC_ISR, STM32H7_EOC },
536 	.isr_ovr = { STM32H7_ADC_ISR, STM32H7_OVR },
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 	.difsel = { STM32H7_ADC_DIFSEL, STM32H7_DIFSEL_MASK},
543 	.smpr = { STM32H7_ADC_SMPR1, STM32H7_ADC_SMPR2 },
544 	.smp_bits = stm32h7_smp_bits,
545 };
546 
547 /* STM32MP13 programmable sampling time (ADC clock cycles, rounded down) */
548 static const unsigned int stm32mp13_adc_smp_cycles[STM32_ADC_MAX_SMP + 1] = {
549 	2, 6, 12, 24, 47, 92, 247, 640,
550 };
551 
552 static const struct stm32_adc_regspec stm32mp13_adc_regspec = {
553 	.dr = STM32H7_ADC_DR,
554 	.ier_eoc = { STM32H7_ADC_IER, STM32H7_EOCIE },
555 	.ier_ovr = { STM32H7_ADC_IER, STM32H7_OVRIE },
556 	.isr_eoc = { STM32H7_ADC_ISR, STM32H7_EOC },
557 	.isr_ovr = { STM32H7_ADC_ISR, STM32H7_OVR },
558 	.sqr = stm32h7_sq,
559 	.exten = { STM32H7_ADC_CFGR, STM32H7_EXTEN_MASK, STM32H7_EXTEN_SHIFT },
560 	.extsel = { STM32H7_ADC_CFGR, STM32H7_EXTSEL_MASK,
561 		    STM32H7_EXTSEL_SHIFT },
562 	.res = { STM32H7_ADC_CFGR, STM32MP13_RES_MASK, STM32MP13_RES_SHIFT },
563 	.difsel = { STM32MP13_ADC_DIFSEL, STM32MP13_DIFSEL_MASK},
564 	.smpr = { STM32H7_ADC_SMPR1, STM32H7_ADC_SMPR2 },
565 	.smp_bits = stm32h7_smp_bits,
566 	.or_vddcore = { STM32MP13_ADC2_OR, STM32MP13_OP0 },
567 	.or_vddcpu = { STM32MP13_ADC2_OR, STM32MP13_OP1 },
568 	.or_vddq_ddr = { STM32MP13_ADC2_OR, STM32MP13_OP2 },
569 	.ccr_vbat = { STM32H7_ADC_CCR, STM32H7_VBATEN },
570 	.ccr_vref = { STM32H7_ADC_CCR, STM32H7_VREFEN },
571 };
572 
573 static const struct stm32_adc_regspec stm32mp1_adc_regspec = {
574 	.dr = STM32H7_ADC_DR,
575 	.ier_eoc = { STM32H7_ADC_IER, STM32H7_EOCIE },
576 	.ier_ovr = { STM32H7_ADC_IER, STM32H7_OVRIE },
577 	.isr_eoc = { STM32H7_ADC_ISR, STM32H7_EOC },
578 	.isr_ovr = { STM32H7_ADC_ISR, STM32H7_OVR },
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 	.difsel = { STM32H7_ADC_DIFSEL, STM32H7_DIFSEL_MASK},
585 	.smpr = { STM32H7_ADC_SMPR1, STM32H7_ADC_SMPR2 },
586 	.smp_bits = stm32h7_smp_bits,
587 	.or_vddcore = { STM32MP1_ADC2_OR, STM32MP1_VDDCOREEN },
588 	.ccr_vbat = { STM32H7_ADC_CCR, STM32H7_VBATEN },
589 	.ccr_vref = { STM32H7_ADC_CCR, STM32H7_VREFEN },
590 };
591 
592 /*
593  * STM32 ADC registers access routines
594  * @adc: stm32 adc instance
595  * @reg: reg offset in adc instance
596  *
597  * Note: All instances share same base, with 0x0, 0x100 or 0x200 offset resp.
598  * for adc1, adc2 and adc3.
599  */
stm32_adc_readl(struct stm32_adc * adc,u32 reg)600 static u32 stm32_adc_readl(struct stm32_adc *adc, u32 reg)
601 {
602 	return readl_relaxed(adc->common->base + adc->offset + reg);
603 }
604 
605 #define stm32_adc_readl_addr(addr)	stm32_adc_readl(adc, addr)
606 
607 #define stm32_adc_readl_poll_timeout(reg, val, cond, sleep_us, timeout_us) \
608 	readx_poll_timeout(stm32_adc_readl_addr, reg, val, \
609 			   cond, sleep_us, timeout_us)
610 
stm32_adc_readw(struct stm32_adc * adc,u32 reg)611 static u16 stm32_adc_readw(struct stm32_adc *adc, u32 reg)
612 {
613 	return readw_relaxed(adc->common->base + adc->offset + reg);
614 }
615 
stm32_adc_writel(struct stm32_adc * adc,u32 reg,u32 val)616 static void stm32_adc_writel(struct stm32_adc *adc, u32 reg, u32 val)
617 {
618 	writel_relaxed(val, adc->common->base + adc->offset + reg);
619 }
620 
stm32_adc_set_bits(struct stm32_adc * adc,u32 reg,u32 bits)621 static void stm32_adc_set_bits(struct stm32_adc *adc, u32 reg, u32 bits)
622 {
623 	unsigned long flags;
624 
625 	spin_lock_irqsave(&adc->lock, flags);
626 	stm32_adc_writel(adc, reg, stm32_adc_readl(adc, reg) | bits);
627 	spin_unlock_irqrestore(&adc->lock, flags);
628 }
629 
stm32_adc_set_bits_common(struct stm32_adc * adc,u32 reg,u32 bits)630 static void stm32_adc_set_bits_common(struct stm32_adc *adc, u32 reg, u32 bits)
631 {
632 	spin_lock(&adc->common->lock);
633 	writel_relaxed(readl_relaxed(adc->common->base + reg) | bits,
634 		       adc->common->base + reg);
635 	spin_unlock(&adc->common->lock);
636 }
637 
stm32_adc_clr_bits(struct stm32_adc * adc,u32 reg,u32 bits)638 static void stm32_adc_clr_bits(struct stm32_adc *adc, u32 reg, u32 bits)
639 {
640 	unsigned long flags;
641 
642 	spin_lock_irqsave(&adc->lock, flags);
643 	stm32_adc_writel(adc, reg, stm32_adc_readl(adc, reg) & ~bits);
644 	spin_unlock_irqrestore(&adc->lock, flags);
645 }
646 
stm32_adc_clr_bits_common(struct stm32_adc * adc,u32 reg,u32 bits)647 static void stm32_adc_clr_bits_common(struct stm32_adc *adc, u32 reg, u32 bits)
648 {
649 	spin_lock(&adc->common->lock);
650 	writel_relaxed(readl_relaxed(adc->common->base + reg) & ~bits,
651 		       adc->common->base + reg);
652 	spin_unlock(&adc->common->lock);
653 }
654 
655 /**
656  * stm32_adc_conv_irq_enable() - Enable end of conversion interrupt
657  * @adc: stm32 adc instance
658  */
stm32_adc_conv_irq_enable(struct stm32_adc * adc)659 static void stm32_adc_conv_irq_enable(struct stm32_adc *adc)
660 {
661 	stm32_adc_set_bits(adc, adc->cfg->regs->ier_eoc.reg,
662 			   adc->cfg->regs->ier_eoc.mask);
663 };
664 
665 /**
666  * stm32_adc_conv_irq_disable() - Disable end of conversion interrupt
667  * @adc: stm32 adc instance
668  */
stm32_adc_conv_irq_disable(struct stm32_adc * adc)669 static void stm32_adc_conv_irq_disable(struct stm32_adc *adc)
670 {
671 	stm32_adc_clr_bits(adc, adc->cfg->regs->ier_eoc.reg,
672 			   adc->cfg->regs->ier_eoc.mask);
673 }
674 
stm32_adc_ovr_irq_enable(struct stm32_adc * adc)675 static void stm32_adc_ovr_irq_enable(struct stm32_adc *adc)
676 {
677 	stm32_adc_set_bits(adc, adc->cfg->regs->ier_ovr.reg,
678 			   adc->cfg->regs->ier_ovr.mask);
679 }
680 
stm32_adc_ovr_irq_disable(struct stm32_adc * adc)681 static void stm32_adc_ovr_irq_disable(struct stm32_adc *adc)
682 {
683 	stm32_adc_clr_bits(adc, adc->cfg->regs->ier_ovr.reg,
684 			   adc->cfg->regs->ier_ovr.mask);
685 }
686 
stm32_adc_set_res(struct stm32_adc * adc)687 static void stm32_adc_set_res(struct stm32_adc *adc)
688 {
689 	const struct stm32_adc_regs *res = &adc->cfg->regs->res;
690 	u32 val;
691 
692 	val = stm32_adc_readl(adc, res->reg);
693 	val = (val & ~res->mask) | (adc->res << res->shift);
694 	stm32_adc_writel(adc, res->reg, val);
695 }
696 
stm32_adc_hw_stop(struct device * dev)697 static int stm32_adc_hw_stop(struct device *dev)
698 {
699 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
700 	struct stm32_adc *adc = iio_priv(indio_dev);
701 
702 	if (adc->cfg->unprepare)
703 		adc->cfg->unprepare(indio_dev);
704 
705 	clk_disable_unprepare(adc->clk);
706 
707 	return 0;
708 }
709 
stm32_adc_hw_start(struct device * dev)710 static int stm32_adc_hw_start(struct device *dev)
711 {
712 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
713 	struct stm32_adc *adc = iio_priv(indio_dev);
714 	int ret;
715 
716 	ret = clk_prepare_enable(adc->clk);
717 	if (ret)
718 		return ret;
719 
720 	stm32_adc_set_res(adc);
721 
722 	if (adc->cfg->prepare) {
723 		ret = adc->cfg->prepare(indio_dev);
724 		if (ret)
725 			goto err_clk_dis;
726 	}
727 
728 	return 0;
729 
730 err_clk_dis:
731 	clk_disable_unprepare(adc->clk);
732 
733 	return ret;
734 }
735 
stm32_adc_int_ch_enable(struct iio_dev * indio_dev)736 static void stm32_adc_int_ch_enable(struct iio_dev *indio_dev)
737 {
738 	struct stm32_adc *adc = iio_priv(indio_dev);
739 	u32 i;
740 
741 	for (i = 0; i < STM32_ADC_INT_CH_NB; i++) {
742 		if (adc->int_ch[i] == STM32_ADC_INT_CH_NONE)
743 			continue;
744 
745 		switch (i) {
746 		case STM32_ADC_INT_CH_VDDCORE:
747 			dev_dbg(&indio_dev->dev, "Enable VDDCore\n");
748 			stm32_adc_set_bits(adc, adc->cfg->regs->or_vddcore.reg,
749 					   adc->cfg->regs->or_vddcore.mask);
750 			break;
751 		case STM32_ADC_INT_CH_VDDCPU:
752 			dev_dbg(&indio_dev->dev, "Enable VDDCPU\n");
753 			stm32_adc_set_bits(adc, adc->cfg->regs->or_vddcpu.reg,
754 					   adc->cfg->regs->or_vddcpu.mask);
755 			break;
756 		case STM32_ADC_INT_CH_VDDQ_DDR:
757 			dev_dbg(&indio_dev->dev, "Enable VDDQ_DDR\n");
758 			stm32_adc_set_bits(adc, adc->cfg->regs->or_vddq_ddr.reg,
759 					   adc->cfg->regs->or_vddq_ddr.mask);
760 			break;
761 		case STM32_ADC_INT_CH_VREFINT:
762 			dev_dbg(&indio_dev->dev, "Enable VREFInt\n");
763 			stm32_adc_set_bits_common(adc, adc->cfg->regs->ccr_vref.reg,
764 						  adc->cfg->regs->ccr_vref.mask);
765 			break;
766 		case STM32_ADC_INT_CH_VBAT:
767 			dev_dbg(&indio_dev->dev, "Enable VBAT\n");
768 			stm32_adc_set_bits_common(adc, adc->cfg->regs->ccr_vbat.reg,
769 						  adc->cfg->regs->ccr_vbat.mask);
770 			break;
771 		}
772 	}
773 }
774 
stm32_adc_int_ch_disable(struct stm32_adc * adc)775 static void stm32_adc_int_ch_disable(struct stm32_adc *adc)
776 {
777 	u32 i;
778 
779 	for (i = 0; i < STM32_ADC_INT_CH_NB; i++) {
780 		if (adc->int_ch[i] == STM32_ADC_INT_CH_NONE)
781 			continue;
782 
783 		switch (i) {
784 		case STM32_ADC_INT_CH_VDDCORE:
785 			stm32_adc_clr_bits(adc, adc->cfg->regs->or_vddcore.reg,
786 					   adc->cfg->regs->or_vddcore.mask);
787 			break;
788 		case STM32_ADC_INT_CH_VDDCPU:
789 			stm32_adc_clr_bits(adc, adc->cfg->regs->or_vddcpu.reg,
790 					   adc->cfg->regs->or_vddcpu.mask);
791 			break;
792 		case STM32_ADC_INT_CH_VDDQ_DDR:
793 			stm32_adc_clr_bits(adc, adc->cfg->regs->or_vddq_ddr.reg,
794 					   adc->cfg->regs->or_vddq_ddr.mask);
795 			break;
796 		case STM32_ADC_INT_CH_VREFINT:
797 			stm32_adc_clr_bits_common(adc, adc->cfg->regs->ccr_vref.reg,
798 						  adc->cfg->regs->ccr_vref.mask);
799 			break;
800 		case STM32_ADC_INT_CH_VBAT:
801 			stm32_adc_clr_bits_common(adc, adc->cfg->regs->ccr_vbat.reg,
802 						  adc->cfg->regs->ccr_vbat.mask);
803 			break;
804 		}
805 	}
806 }
807 
808 /**
809  * stm32f4_adc_start_conv() - Start conversions for regular channels.
810  * @indio_dev: IIO device instance
811  * @dma: use dma to transfer conversion result
812  *
813  * Start conversions for regular channels.
814  * Also take care of normal or DMA mode. Circular DMA may be used for regular
815  * conversions, in IIO buffer modes. Otherwise, use ADC interrupt with direct
816  * DR read instead (e.g. read_raw, or triggered buffer mode without DMA).
817  */
stm32f4_adc_start_conv(struct iio_dev * indio_dev,bool dma)818 static void stm32f4_adc_start_conv(struct iio_dev *indio_dev, bool dma)
819 {
820 	struct stm32_adc *adc = iio_priv(indio_dev);
821 
822 	stm32_adc_set_bits(adc, STM32F4_ADC_CR1, STM32F4_SCAN);
823 
824 	if (dma)
825 		stm32_adc_set_bits(adc, STM32F4_ADC_CR2,
826 				   STM32F4_DMA | STM32F4_DDS);
827 
828 	stm32_adc_set_bits(adc, STM32F4_ADC_CR2, STM32F4_EOCS | STM32F4_ADON);
829 
830 	/* Wait for Power-up time (tSTAB from datasheet) */
831 	usleep_range(2, 3);
832 
833 	/* Software start ? (e.g. trigger detection disabled ?) */
834 	if (!(stm32_adc_readl(adc, STM32F4_ADC_CR2) & STM32F4_EXTEN_MASK))
835 		stm32_adc_set_bits(adc, STM32F4_ADC_CR2, STM32F4_SWSTART);
836 }
837 
stm32f4_adc_stop_conv(struct iio_dev * indio_dev)838 static void stm32f4_adc_stop_conv(struct iio_dev *indio_dev)
839 {
840 	struct stm32_adc *adc = iio_priv(indio_dev);
841 
842 	stm32_adc_clr_bits(adc, STM32F4_ADC_CR2, STM32F4_EXTEN_MASK);
843 	stm32_adc_clr_bits(adc, STM32F4_ADC_SR, STM32F4_STRT);
844 
845 	stm32_adc_clr_bits(adc, STM32F4_ADC_CR1, STM32F4_SCAN);
846 	stm32_adc_clr_bits(adc, STM32F4_ADC_CR2,
847 			   STM32F4_ADON | STM32F4_DMA | STM32F4_DDS);
848 }
849 
stm32f4_adc_irq_clear(struct iio_dev * indio_dev,u32 msk)850 static void stm32f4_adc_irq_clear(struct iio_dev *indio_dev, u32 msk)
851 {
852 	struct stm32_adc *adc = iio_priv(indio_dev);
853 
854 	stm32_adc_clr_bits(adc, adc->cfg->regs->isr_eoc.reg, msk);
855 }
856 
stm32h7_adc_start_conv(struct iio_dev * indio_dev,bool dma)857 static void stm32h7_adc_start_conv(struct iio_dev *indio_dev, bool dma)
858 {
859 	struct stm32_adc *adc = iio_priv(indio_dev);
860 	enum stm32h7_adc_dmngt dmngt;
861 	unsigned long flags;
862 	u32 val;
863 
864 	if (dma)
865 		dmngt = STM32H7_DMNGT_DMA_CIRC;
866 	else
867 		dmngt = STM32H7_DMNGT_DR_ONLY;
868 
869 	spin_lock_irqsave(&adc->lock, flags);
870 	val = stm32_adc_readl(adc, STM32H7_ADC_CFGR);
871 	val = (val & ~STM32H7_DMNGT_MASK) | (dmngt << STM32H7_DMNGT_SHIFT);
872 	stm32_adc_writel(adc, STM32H7_ADC_CFGR, val);
873 	spin_unlock_irqrestore(&adc->lock, flags);
874 
875 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADSTART);
876 }
877 
stm32h7_adc_stop_conv(struct iio_dev * indio_dev)878 static void stm32h7_adc_stop_conv(struct iio_dev *indio_dev)
879 {
880 	struct stm32_adc *adc = iio_priv(indio_dev);
881 	int ret;
882 	u32 val;
883 
884 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADSTP);
885 
886 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
887 					   !(val & (STM32H7_ADSTART)),
888 					   100, STM32_ADC_TIMEOUT_US);
889 	if (ret)
890 		dev_warn(&indio_dev->dev, "stop failed\n");
891 
892 	/* STM32H7_DMNGT_MASK covers STM32MP13_DMAEN & STM32MP13_DMACFG */
893 	stm32_adc_clr_bits(adc, STM32H7_ADC_CFGR, STM32H7_DMNGT_MASK);
894 }
895 
stm32h7_adc_irq_clear(struct iio_dev * indio_dev,u32 msk)896 static void stm32h7_adc_irq_clear(struct iio_dev *indio_dev, u32 msk)
897 {
898 	struct stm32_adc *adc = iio_priv(indio_dev);
899 	/* On STM32H7 IRQs are cleared by writing 1 into ISR register */
900 	stm32_adc_set_bits(adc, adc->cfg->regs->isr_eoc.reg, msk);
901 }
902 
stm32mp13_adc_start_conv(struct iio_dev * indio_dev,bool dma)903 static void stm32mp13_adc_start_conv(struct iio_dev *indio_dev, bool dma)
904 {
905 	struct stm32_adc *adc = iio_priv(indio_dev);
906 
907 	if (dma)
908 		stm32_adc_set_bits(adc, STM32H7_ADC_CFGR,
909 				   STM32MP13_DMAEN | STM32MP13_DMACFG);
910 
911 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADSTART);
912 }
913 
stm32h7_adc_set_ovs(struct iio_dev * indio_dev,u32 ovs_idx)914 static void stm32h7_adc_set_ovs(struct iio_dev *indio_dev, u32 ovs_idx)
915 {
916 	struct stm32_adc *adc = iio_priv(indio_dev);
917 	u32 ovsr_bits, bits, msk;
918 
919 	msk = STM32H7_ROVSE | STM32H7_OVSR_MASK | STM32H7_OVSS_MASK;
920 	stm32_adc_clr_bits(adc, STM32H7_ADC_CFGR2, msk);
921 
922 	if (!ovs_idx)
923 		return;
924 
925 	/*
926 	 * Only the oversampling ratios corresponding to 2^ovs_idx are exposed in sysfs.
927 	 * Oversampling ratios [2,3,...,1024] are mapped on OVSR register values [1,2,...,1023].
928 	 * OVSR = 2^ovs_idx - 1
929 	 * These ratio increase the resolution by ovs_idx bits. Apply a right shift to keep initial
930 	 * resolution given by "assigned-resolution-bits" property.
931 	 * OVSS = ovs_idx
932 	 */
933 	ovsr_bits = GENMASK(ovs_idx - 1, 0);
934 	bits = STM32H7_ROVSE | STM32H7_OVSS(ovs_idx) | STM32H7_OVSR(ovsr_bits);
935 
936 	stm32_adc_set_bits(adc, STM32H7_ADC_CFGR2, bits & msk);
937 }
938 
stm32mp13_adc_set_ovs(struct iio_dev * indio_dev,u32 ovs_idx)939 static void stm32mp13_adc_set_ovs(struct iio_dev *indio_dev, u32 ovs_idx)
940 {
941 	struct stm32_adc *adc = iio_priv(indio_dev);
942 	u32 bits, msk;
943 
944 	msk = STM32H7_ROVSE | STM32MP13_OVSR_MASK | STM32MP13_OVSS_MASK;
945 	stm32_adc_clr_bits(adc, STM32H7_ADC_CFGR2, msk);
946 
947 	if (!ovs_idx)
948 		return;
949 
950 	/*
951 	 * The oversampling ratios [2,4,8,..,256] are mapped on OVSR register values [0,1,...,7].
952 	 * OVSR = ovs_idx - 1
953 	 * These ratio increase the resolution by ovs_idx bits. Apply a right shift to keep initial
954 	 * resolution given by "assigned-resolution-bits" property.
955 	 * OVSS = ovs_idx
956 	 */
957 	bits = STM32H7_ROVSE | STM32MP13_OVSS(ovs_idx);
958 	if (ovs_idx - 1)
959 		bits |= STM32MP13_OVSR(ovs_idx - 1);
960 
961 	stm32_adc_set_bits(adc, STM32H7_ADC_CFGR2, bits & msk);
962 }
963 
stm32h7_adc_exit_pwr_down(struct iio_dev * indio_dev)964 static int stm32h7_adc_exit_pwr_down(struct iio_dev *indio_dev)
965 {
966 	struct stm32_adc *adc = iio_priv(indio_dev);
967 	int ret;
968 	u32 val;
969 
970 	/* Exit deep power down, then enable ADC voltage regulator */
971 	stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_DEEPPWD);
972 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADVREGEN);
973 
974 	if (adc->cfg->has_boostmode &&
975 	    adc->common->rate > STM32H7_BOOST_CLKRATE)
976 		stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_BOOST);
977 
978 	/* Wait for startup time */
979 	if (!adc->cfg->has_vregready) {
980 		usleep_range(10, 20);
981 		return 0;
982 	}
983 
984 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_ISR, val,
985 					   val & STM32MP1_VREGREADY, 100,
986 					   STM32_ADC_TIMEOUT_US);
987 	if (ret) {
988 		stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_DEEPPWD);
989 		dev_err(&indio_dev->dev, "Failed to exit power down\n");
990 	}
991 
992 	return ret;
993 }
994 
stm32h7_adc_enter_pwr_down(struct stm32_adc * adc)995 static void stm32h7_adc_enter_pwr_down(struct stm32_adc *adc)
996 {
997 	if (adc->cfg->has_boostmode)
998 		stm32_adc_clr_bits(adc, STM32H7_ADC_CR, STM32H7_BOOST);
999 
1000 	/* Setting DEEPPWD disables ADC vreg and clears ADVREGEN */
1001 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_DEEPPWD);
1002 }
1003 
stm32h7_adc_enable(struct iio_dev * indio_dev)1004 static int stm32h7_adc_enable(struct iio_dev *indio_dev)
1005 {
1006 	struct stm32_adc *adc = iio_priv(indio_dev);
1007 	int ret;
1008 	u32 val;
1009 
1010 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADEN);
1011 
1012 	/* Poll for ADRDY to be set (after adc startup time) */
1013 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_ISR, val,
1014 					   val & STM32H7_ADRDY,
1015 					   100, STM32_ADC_TIMEOUT_US);
1016 	if (ret) {
1017 		stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADDIS);
1018 		dev_err(&indio_dev->dev, "Failed to enable ADC\n");
1019 	} else {
1020 		/* Clear ADRDY by writing one */
1021 		stm32_adc_set_bits(adc, STM32H7_ADC_ISR, STM32H7_ADRDY);
1022 	}
1023 
1024 	return ret;
1025 }
1026 
stm32h7_adc_disable(struct iio_dev * indio_dev)1027 static void stm32h7_adc_disable(struct iio_dev *indio_dev)
1028 {
1029 	struct stm32_adc *adc = iio_priv(indio_dev);
1030 	int ret;
1031 	u32 val;
1032 
1033 	if (!(stm32_adc_readl(adc, STM32H7_ADC_CR) & STM32H7_ADEN))
1034 		return;
1035 
1036 	/* Disable ADC and wait until it's effectively disabled */
1037 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADDIS);
1038 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
1039 					   !(val & STM32H7_ADEN), 100,
1040 					   STM32_ADC_TIMEOUT_US);
1041 	if (ret)
1042 		dev_warn(&indio_dev->dev, "Failed to disable\n");
1043 }
1044 
1045 /**
1046  * stm32h7_adc_read_selfcalib() - read calibration shadow regs, save result
1047  * @indio_dev: IIO device instance
1048  * Note: Must be called once ADC is enabled, so LINCALRDYW[1..6] are writable
1049  */
stm32h7_adc_read_selfcalib(struct iio_dev * indio_dev)1050 static int stm32h7_adc_read_selfcalib(struct iio_dev *indio_dev)
1051 {
1052 	struct stm32_adc *adc = iio_priv(indio_dev);
1053 	int i, ret;
1054 	u32 lincalrdyw_mask, val;
1055 
1056 	/* Read linearity calibration */
1057 	lincalrdyw_mask = STM32H7_LINCALRDYW6;
1058 	for (i = STM32H7_LINCALFACT_NUM - 1; i >= 0; i--) {
1059 		/* Clear STM32H7_LINCALRDYW[6..1]: transfer calib to CALFACT2 */
1060 		stm32_adc_clr_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
1061 
1062 		/* Poll: wait calib data to be ready in CALFACT2 register */
1063 		ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
1064 						   !(val & lincalrdyw_mask),
1065 						   100, STM32_ADC_TIMEOUT_US);
1066 		if (ret) {
1067 			dev_err(&indio_dev->dev, "Failed to read calfact\n");
1068 			return ret;
1069 		}
1070 
1071 		val = stm32_adc_readl(adc, STM32H7_ADC_CALFACT2);
1072 		adc->cal.lincalfact[i] = (val & STM32H7_LINCALFACT_MASK);
1073 		adc->cal.lincalfact[i] >>= STM32H7_LINCALFACT_SHIFT;
1074 
1075 		lincalrdyw_mask >>= 1;
1076 	}
1077 	adc->cal.lincal_saved = true;
1078 
1079 	return 0;
1080 }
1081 
1082 /**
1083  * stm32h7_adc_restore_selfcalib() - Restore saved self-calibration result
1084  * @indio_dev: IIO device instance
1085  * Note: ADC must be enabled, with no on-going conversions.
1086  */
stm32h7_adc_restore_selfcalib(struct iio_dev * indio_dev)1087 static int stm32h7_adc_restore_selfcalib(struct iio_dev *indio_dev)
1088 {
1089 	struct stm32_adc *adc = iio_priv(indio_dev);
1090 	int i, ret;
1091 	u32 lincalrdyw_mask, val;
1092 
1093 	lincalrdyw_mask = STM32H7_LINCALRDYW6;
1094 	for (i = STM32H7_LINCALFACT_NUM - 1; i >= 0; i--) {
1095 		/*
1096 		 * Write saved calibration data to shadow registers:
1097 		 * Write CALFACT2, and set LINCALRDYW[6..1] bit to trigger
1098 		 * data write. Then poll to wait for complete transfer.
1099 		 */
1100 		val = adc->cal.lincalfact[i] << STM32H7_LINCALFACT_SHIFT;
1101 		stm32_adc_writel(adc, STM32H7_ADC_CALFACT2, val);
1102 		stm32_adc_set_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
1103 		ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
1104 						   val & lincalrdyw_mask,
1105 						   100, STM32_ADC_TIMEOUT_US);
1106 		if (ret) {
1107 			dev_err(&indio_dev->dev, "Failed to write calfact\n");
1108 			return ret;
1109 		}
1110 
1111 		/*
1112 		 * Read back calibration data, has two effects:
1113 		 * - It ensures bits LINCALRDYW[6..1] are kept cleared
1114 		 *   for next time calibration needs to be restored.
1115 		 * - BTW, bit clear triggers a read, then check data has been
1116 		 *   correctly written.
1117 		 */
1118 		stm32_adc_clr_bits(adc, STM32H7_ADC_CR, lincalrdyw_mask);
1119 		ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
1120 						   !(val & lincalrdyw_mask),
1121 						   100, STM32_ADC_TIMEOUT_US);
1122 		if (ret) {
1123 			dev_err(&indio_dev->dev, "Failed to read calfact\n");
1124 			return ret;
1125 		}
1126 		val = stm32_adc_readl(adc, STM32H7_ADC_CALFACT2);
1127 		if (val != adc->cal.lincalfact[i] << STM32H7_LINCALFACT_SHIFT) {
1128 			dev_err(&indio_dev->dev, "calfact not consistent\n");
1129 			return -EIO;
1130 		}
1131 
1132 		lincalrdyw_mask >>= 1;
1133 	}
1134 
1135 	return 0;
1136 }
1137 
1138 /*
1139  * Fixed timeout value for ADC calibration.
1140  * worst cases:
1141  * - low clock frequency
1142  * - maximum prescalers
1143  * Calibration requires:
1144  * - 131,072 ADC clock cycle for the linear calibration
1145  * - 20 ADC clock cycle for the offset calibration
1146  *
1147  * Set to 100ms for now
1148  */
1149 #define STM32H7_ADC_CALIB_TIMEOUT_US		100000
1150 
1151 /**
1152  * stm32h7_adc_selfcalib() - Procedure to calibrate ADC
1153  * @indio_dev: IIO device instance
1154  * @do_lincal: linear calibration request flag
1155  * Note: Must be called once ADC is out of power down.
1156  *
1157  * Run offset calibration unconditionally.
1158  * Run linear calibration if requested & supported.
1159  */
stm32h7_adc_selfcalib(struct iio_dev * indio_dev,int do_lincal)1160 static int stm32h7_adc_selfcalib(struct iio_dev *indio_dev, int do_lincal)
1161 {
1162 	struct stm32_adc *adc = iio_priv(indio_dev);
1163 	int ret;
1164 	u32 msk = STM32H7_ADCALDIF;
1165 	u32 val;
1166 
1167 	if (adc->cfg->has_linearcal && do_lincal)
1168 		msk |= STM32H7_ADCALLIN;
1169 	/* ADC must be disabled for calibration */
1170 	stm32h7_adc_disable(indio_dev);
1171 
1172 	/*
1173 	 * Select calibration mode:
1174 	 * - Offset calibration for single ended inputs
1175 	 * - No linearity calibration (do it later, before reading it)
1176 	 */
1177 	stm32_adc_clr_bits(adc, STM32H7_ADC_CR, msk);
1178 
1179 	/* Start calibration, then wait for completion */
1180 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADCAL);
1181 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
1182 					   !(val & STM32H7_ADCAL), 100,
1183 					   STM32H7_ADC_CALIB_TIMEOUT_US);
1184 	if (ret) {
1185 		dev_err(&indio_dev->dev, "calibration (single-ended) error %d\n", ret);
1186 		goto out;
1187 	}
1188 
1189 	/*
1190 	 * Select calibration mode, then start calibration:
1191 	 * - Offset calibration for differential input
1192 	 * - Linearity calibration (needs to be done only once for single/diff)
1193 	 *   will run simultaneously with offset calibration.
1194 	 */
1195 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, msk);
1196 	stm32_adc_set_bits(adc, STM32H7_ADC_CR, STM32H7_ADCAL);
1197 	ret = stm32_adc_readl_poll_timeout(STM32H7_ADC_CR, val,
1198 					   !(val & STM32H7_ADCAL), 100,
1199 					   STM32H7_ADC_CALIB_TIMEOUT_US);
1200 	if (ret) {
1201 		dev_err(&indio_dev->dev, "calibration (diff%s) error %d\n",
1202 			(msk & STM32H7_ADCALLIN) ? "+linear" : "", ret);
1203 		goto out;
1204 	}
1205 
1206 out:
1207 	stm32_adc_clr_bits(adc, STM32H7_ADC_CR, msk);
1208 
1209 	return ret;
1210 }
1211 
1212 /**
1213  * stm32h7_adc_check_selfcalib() - Check linear calibration status
1214  * @indio_dev: IIO device instance
1215  *
1216  * Used to check if linear calibration has been done.
1217  * Return true if linear calibration factors are already saved in private data
1218  * or if a linear calibration has been done at boot stage.
1219  */
stm32h7_adc_check_selfcalib(struct iio_dev * indio_dev)1220 static int stm32h7_adc_check_selfcalib(struct iio_dev *indio_dev)
1221 {
1222 	struct stm32_adc *adc = iio_priv(indio_dev);
1223 	u32 val;
1224 
1225 	if (adc->cal.lincal_saved)
1226 		return true;
1227 
1228 	/*
1229 	 * Check if linear calibration factors are available in ADC registers,
1230 	 * by checking that all LINCALRDYWx bits are set.
1231 	 */
1232 	val = stm32_adc_readl(adc, STM32H7_ADC_CR) & STM32H7_LINCALRDYW_MASK;
1233 	if (val == STM32H7_LINCALRDYW_MASK)
1234 		return true;
1235 
1236 	return false;
1237 }
1238 
1239 /**
1240  * stm32h7_adc_prepare() - Leave power down mode to enable ADC.
1241  * @indio_dev: IIO device instance
1242  * Leave power down mode.
1243  * Configure channels as single ended or differential before enabling ADC.
1244  * Enable ADC.
1245  * Restore calibration data.
1246  * Pre-select channels that may be used in PCSEL (required by input MUX / IO):
1247  * - Only one input is selected for single ended (e.g. 'vinp')
1248  * - Two inputs are selected for differential channels (e.g. 'vinp' & 'vinn')
1249  */
stm32h7_adc_prepare(struct iio_dev * indio_dev)1250 static int stm32h7_adc_prepare(struct iio_dev *indio_dev)
1251 {
1252 	struct stm32_adc *adc = iio_priv(indio_dev);
1253 	int lincal_done = false;
1254 	int ret;
1255 
1256 	ret = stm32h7_adc_exit_pwr_down(indio_dev);
1257 	if (ret)
1258 		return ret;
1259 
1260 	if (adc->cfg->has_linearcal)
1261 		lincal_done = stm32h7_adc_check_selfcalib(indio_dev);
1262 
1263 	/* Always run offset calibration. Run linear calibration only once */
1264 	ret = stm32h7_adc_selfcalib(indio_dev, !lincal_done);
1265 	if (ret < 0)
1266 		goto pwr_dwn;
1267 
1268 	stm32_adc_int_ch_enable(indio_dev);
1269 
1270 	stm32_adc_writel(adc, adc->cfg->regs->difsel.reg, adc->difsel);
1271 
1272 	ret = stm32h7_adc_enable(indio_dev);
1273 	if (ret)
1274 		goto ch_disable;
1275 
1276 	if (adc->cfg->has_linearcal) {
1277 		if (!adc->cal.lincal_saved)
1278 			ret = stm32h7_adc_read_selfcalib(indio_dev);
1279 		else
1280 			ret = stm32h7_adc_restore_selfcalib(indio_dev);
1281 
1282 		if (ret)
1283 			goto disable;
1284 	}
1285 
1286 	if (adc->cfg->has_presel)
1287 		stm32_adc_writel(adc, STM32H7_ADC_PCSEL, adc->pcsel);
1288 
1289 	return 0;
1290 
1291 disable:
1292 	stm32h7_adc_disable(indio_dev);
1293 ch_disable:
1294 	stm32_adc_int_ch_disable(adc);
1295 pwr_dwn:
1296 	stm32h7_adc_enter_pwr_down(adc);
1297 
1298 	return ret;
1299 }
1300 
stm32h7_adc_unprepare(struct iio_dev * indio_dev)1301 static void stm32h7_adc_unprepare(struct iio_dev *indio_dev)
1302 {
1303 	struct stm32_adc *adc = iio_priv(indio_dev);
1304 
1305 	if (adc->cfg->has_presel)
1306 		stm32_adc_writel(adc, STM32H7_ADC_PCSEL, 0);
1307 	stm32h7_adc_disable(indio_dev);
1308 	stm32_adc_int_ch_disable(adc);
1309 	stm32h7_adc_enter_pwr_down(adc);
1310 }
1311 
1312 /**
1313  * stm32_adc_conf_scan_seq() - Build regular channels scan sequence
1314  * @indio_dev: IIO device
1315  * @scan_mask: channels to be converted
1316  *
1317  * Conversion sequence :
1318  * Apply sampling time settings for all channels.
1319  * Configure ADC scan sequence based on selected channels in scan_mask.
1320  * Add channels to SQR registers, from scan_mask LSB to MSB, then
1321  * program sequence len.
1322  */
stm32_adc_conf_scan_seq(struct iio_dev * indio_dev,const unsigned long * scan_mask)1323 static int stm32_adc_conf_scan_seq(struct iio_dev *indio_dev,
1324 				   const unsigned long *scan_mask)
1325 {
1326 	struct stm32_adc *adc = iio_priv(indio_dev);
1327 	const struct stm32_adc_regs *sqr = adc->cfg->regs->sqr;
1328 	const struct iio_chan_spec *chan;
1329 	u32 val, bit;
1330 	int i = 0;
1331 
1332 	/* Apply sampling time settings */
1333 	stm32_adc_writel(adc, adc->cfg->regs->smpr[0], adc->smpr_val[0]);
1334 	stm32_adc_writel(adc, adc->cfg->regs->smpr[1], adc->smpr_val[1]);
1335 
1336 	for_each_set_bit(bit, scan_mask, iio_get_masklength(indio_dev)) {
1337 		chan = indio_dev->channels + bit;
1338 		/*
1339 		 * Assign one channel per SQ entry in regular
1340 		 * sequence, starting with SQ1.
1341 		 */
1342 		i++;
1343 		if (i > STM32_ADC_MAX_SQ)
1344 			return -EINVAL;
1345 
1346 		dev_dbg(&indio_dev->dev, "%s chan %d to SQ%d\n",
1347 			__func__, chan->channel, i);
1348 
1349 		val = stm32_adc_readl(adc, sqr[i].reg);
1350 		val &= ~sqr[i].mask;
1351 		val |= chan->channel << sqr[i].shift;
1352 		stm32_adc_writel(adc, sqr[i].reg, val);
1353 	}
1354 
1355 	if (!i)
1356 		return -EINVAL;
1357 
1358 	/* Sequence len */
1359 	val = stm32_adc_readl(adc, sqr[0].reg);
1360 	val &= ~sqr[0].mask;
1361 	val |= ((i - 1) << sqr[0].shift);
1362 	stm32_adc_writel(adc, sqr[0].reg, val);
1363 
1364 	return 0;
1365 }
1366 
1367 /**
1368  * stm32_adc_get_trig_extsel() - Get external trigger selection
1369  * @indio_dev: IIO device structure
1370  * @trig: trigger
1371  *
1372  * Returns trigger extsel value, if trig matches, -EINVAL otherwise.
1373  */
stm32_adc_get_trig_extsel(struct iio_dev * indio_dev,struct iio_trigger * trig)1374 static int stm32_adc_get_trig_extsel(struct iio_dev *indio_dev,
1375 				     struct iio_trigger *trig)
1376 {
1377 	struct stm32_adc *adc = iio_priv(indio_dev);
1378 	int i;
1379 
1380 	/* lookup triggers registered by stm32 timer trigger driver */
1381 	for (i = 0; adc->cfg->trigs[i].name; i++) {
1382 		/**
1383 		 * Checking both stm32 timer trigger type and trig name
1384 		 * should be safe against arbitrary trigger names.
1385 		 */
1386 		if ((is_stm32_timer_trigger(trig) ||
1387 		     is_stm32_lptim_trigger(trig)) &&
1388 		    !strcmp(adc->cfg->trigs[i].name, trig->name)) {
1389 			return adc->cfg->trigs[i].extsel;
1390 		}
1391 	}
1392 
1393 	return -EINVAL;
1394 }
1395 
1396 /**
1397  * stm32_adc_set_trig() - Set a regular trigger
1398  * @indio_dev: IIO device
1399  * @trig: IIO trigger
1400  *
1401  * Set trigger source/polarity (e.g. SW, or HW with polarity) :
1402  * - if HW trigger disabled (e.g. trig == NULL, conversion launched by sw)
1403  * - if HW trigger enabled, set source & polarity
1404  */
stm32_adc_set_trig(struct iio_dev * indio_dev,struct iio_trigger * trig)1405 static int stm32_adc_set_trig(struct iio_dev *indio_dev,
1406 			      struct iio_trigger *trig)
1407 {
1408 	struct stm32_adc *adc = iio_priv(indio_dev);
1409 	u32 val, extsel = 0, exten = STM32_EXTEN_SWTRIG;
1410 	unsigned long flags;
1411 	int ret;
1412 
1413 	if (trig) {
1414 		ret = stm32_adc_get_trig_extsel(indio_dev, trig);
1415 		if (ret < 0)
1416 			return ret;
1417 
1418 		/* set trigger source and polarity (default to rising edge) */
1419 		extsel = ret;
1420 		exten = adc->trigger_polarity + STM32_EXTEN_HWTRIG_RISING_EDGE;
1421 	}
1422 
1423 	spin_lock_irqsave(&adc->lock, flags);
1424 	val = stm32_adc_readl(adc, adc->cfg->regs->exten.reg);
1425 	val &= ~(adc->cfg->regs->exten.mask | adc->cfg->regs->extsel.mask);
1426 	val |= exten << adc->cfg->regs->exten.shift;
1427 	val |= extsel << adc->cfg->regs->extsel.shift;
1428 	stm32_adc_writel(adc,  adc->cfg->regs->exten.reg, val);
1429 	spin_unlock_irqrestore(&adc->lock, flags);
1430 
1431 	return 0;
1432 }
1433 
stm32_adc_set_trig_pol(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,unsigned int type)1434 static int stm32_adc_set_trig_pol(struct iio_dev *indio_dev,
1435 				  const struct iio_chan_spec *chan,
1436 				  unsigned int type)
1437 {
1438 	struct stm32_adc *adc = iio_priv(indio_dev);
1439 
1440 	adc->trigger_polarity = type;
1441 
1442 	return 0;
1443 }
1444 
stm32_adc_get_trig_pol(struct iio_dev * indio_dev,const struct iio_chan_spec * chan)1445 static int stm32_adc_get_trig_pol(struct iio_dev *indio_dev,
1446 				  const struct iio_chan_spec *chan)
1447 {
1448 	struct stm32_adc *adc = iio_priv(indio_dev);
1449 
1450 	return adc->trigger_polarity;
1451 }
1452 
1453 static const char * const stm32_trig_pol_items[] = {
1454 	"rising-edge", "falling-edge", "both-edges",
1455 };
1456 
1457 static const struct iio_enum stm32_adc_trig_pol = {
1458 	.items = stm32_trig_pol_items,
1459 	.num_items = ARRAY_SIZE(stm32_trig_pol_items),
1460 	.get = stm32_adc_get_trig_pol,
1461 	.set = stm32_adc_set_trig_pol,
1462 };
1463 
1464 /**
1465  * stm32_adc_single_conv() - Performs a single conversion
1466  * @indio_dev: IIO device
1467  * @chan: IIO channel
1468  * @res: conversion result
1469  *
1470  * The function performs a single conversion on a given channel:
1471  * - Apply sampling time settings
1472  * - Program sequencer with one channel (e.g. in SQ1 with len = 1)
1473  * - Use SW trigger
1474  * - Start conversion, then wait for interrupt completion.
1475  */
stm32_adc_single_conv(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,int * res)1476 static int stm32_adc_single_conv(struct iio_dev *indio_dev,
1477 				 const struct iio_chan_spec *chan,
1478 				 int *res)
1479 {
1480 	struct stm32_adc *adc = iio_priv(indio_dev);
1481 	struct device *dev = indio_dev->dev.parent;
1482 	const struct stm32_adc_regspec *regs = adc->cfg->regs;
1483 	long time_left;
1484 	u32 val;
1485 	int ret;
1486 
1487 	reinit_completion(&adc->completion);
1488 
1489 	adc->bufi = 0;
1490 
1491 	ret = pm_runtime_resume_and_get(dev);
1492 	if (ret < 0)
1493 		return ret;
1494 
1495 	/* Apply sampling time settings */
1496 	stm32_adc_writel(adc, regs->smpr[0], adc->smpr_val[0]);
1497 	stm32_adc_writel(adc, regs->smpr[1], adc->smpr_val[1]);
1498 
1499 	/* Program chan number in regular sequence (SQ1) */
1500 	val = stm32_adc_readl(adc, regs->sqr[1].reg);
1501 	val &= ~regs->sqr[1].mask;
1502 	val |= chan->channel << regs->sqr[1].shift;
1503 	stm32_adc_writel(adc, regs->sqr[1].reg, val);
1504 
1505 	/* Set regular sequence len (0 for 1 conversion) */
1506 	stm32_adc_clr_bits(adc, regs->sqr[0].reg, regs->sqr[0].mask);
1507 
1508 	/* Trigger detection disabled (conversion can be launched in SW) */
1509 	stm32_adc_clr_bits(adc, regs->exten.reg, regs->exten.mask);
1510 
1511 	stm32_adc_conv_irq_enable(adc);
1512 
1513 	adc->cfg->start_conv(indio_dev, false);
1514 
1515 	time_left = wait_for_completion_interruptible_timeout(
1516 					&adc->completion, STM32_ADC_TIMEOUT);
1517 	if (time_left == 0) {
1518 		ret = -ETIMEDOUT;
1519 	} else if (time_left < 0) {
1520 		ret = time_left;
1521 	} else {
1522 		*res = adc->buffer[0];
1523 		ret = IIO_VAL_INT;
1524 	}
1525 
1526 	adc->cfg->stop_conv(indio_dev);
1527 
1528 	stm32_adc_conv_irq_disable(adc);
1529 
1530 	pm_runtime_put_autosuspend(dev);
1531 
1532 	return ret;
1533 }
1534 
stm32_adc_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)1535 static int stm32_adc_write_raw(struct iio_dev *indio_dev,
1536 			       struct iio_chan_spec const *chan,
1537 			       int val, int val2, long mask)
1538 {
1539 	struct stm32_adc *adc = iio_priv(indio_dev);
1540 	struct device *dev = indio_dev->dev.parent;
1541 	int nb = adc->cfg->adc_info->num_ovs;
1542 	unsigned int idx;
1543 	int ret;
1544 
1545 	switch (mask) {
1546 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1547 		if (val2)
1548 			return -EINVAL;
1549 
1550 		for (idx = 0; idx < nb; idx++)
1551 			if (adc->cfg->adc_info->oversampling[idx] == val)
1552 				break;
1553 		if (idx >= nb)
1554 			return -EINVAL;
1555 
1556 		if (!iio_device_claim_direct(indio_dev))
1557 			return -EBUSY;
1558 
1559 		ret = pm_runtime_resume_and_get(dev);
1560 		if (ret < 0)
1561 			goto err;
1562 
1563 		adc->cfg->set_ovs(indio_dev, idx);
1564 
1565 		pm_runtime_put_autosuspend(dev);
1566 
1567 		adc->ovs_idx = idx;
1568 
1569 err:
1570 		iio_device_release_direct(indio_dev);
1571 
1572 		return ret;
1573 	default:
1574 		return -EINVAL;
1575 	}
1576 }
1577 
stm32_adc_read_avail(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,const int ** vals,int * type,int * length,long m)1578 static int stm32_adc_read_avail(struct iio_dev *indio_dev,
1579 				struct iio_chan_spec const *chan,
1580 				const int **vals, int *type, int *length, long m)
1581 {
1582 	struct stm32_adc *adc = iio_priv(indio_dev);
1583 
1584 	switch (m) {
1585 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1586 		*type = IIO_VAL_INT;
1587 		*length = adc->cfg->adc_info->num_ovs;
1588 		*vals = adc->cfg->adc_info->oversampling;
1589 		return IIO_AVAIL_LIST;
1590 	default:
1591 		return -EINVAL;
1592 	}
1593 }
1594 
stm32_adc_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)1595 static int stm32_adc_read_raw(struct iio_dev *indio_dev,
1596 			      struct iio_chan_spec const *chan,
1597 			      int *val, int *val2, long mask)
1598 {
1599 	struct stm32_adc *adc = iio_priv(indio_dev);
1600 	int ret;
1601 
1602 	switch (mask) {
1603 	case IIO_CHAN_INFO_RAW:
1604 	case IIO_CHAN_INFO_PROCESSED:
1605 		if (!iio_device_claim_direct(indio_dev))
1606 			return -EBUSY;
1607 		if (chan->type == IIO_VOLTAGE)
1608 			ret = stm32_adc_single_conv(indio_dev, chan, val);
1609 		else
1610 			ret = -EINVAL;
1611 
1612 		if (mask == IIO_CHAN_INFO_PROCESSED)
1613 			*val = STM32_ADC_VREFINT_VOLTAGE * adc->vrefint.vrefint_cal / *val;
1614 
1615 		iio_device_release_direct(indio_dev);
1616 		return ret;
1617 
1618 	case IIO_CHAN_INFO_SCALE:
1619 		if (chan->differential) {
1620 			*val = adc->common->vref_mv * 2;
1621 			*val2 = chan->scan_type.realbits;
1622 		} else {
1623 			*val = adc->common->vref_mv;
1624 			*val2 = chan->scan_type.realbits;
1625 		}
1626 		return IIO_VAL_FRACTIONAL_LOG2;
1627 
1628 	case IIO_CHAN_INFO_OFFSET:
1629 		if (chan->differential)
1630 			/* ADC_full_scale / 2 */
1631 			*val = -((1 << chan->scan_type.realbits) / 2);
1632 		else
1633 			*val = 0;
1634 		return IIO_VAL_INT;
1635 
1636 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1637 		*val = adc->cfg->adc_info->oversampling[adc->ovs_idx];
1638 		return IIO_VAL_INT;
1639 
1640 	default:
1641 		return -EINVAL;
1642 	}
1643 }
1644 
stm32_adc_irq_clear(struct iio_dev * indio_dev,u32 msk)1645 static void stm32_adc_irq_clear(struct iio_dev *indio_dev, u32 msk)
1646 {
1647 	struct stm32_adc *adc = iio_priv(indio_dev);
1648 
1649 	adc->cfg->irq_clear(indio_dev, msk);
1650 }
1651 
stm32_adc_threaded_isr(int irq,void * data)1652 static irqreturn_t stm32_adc_threaded_isr(int irq, void *data)
1653 {
1654 	struct iio_dev *indio_dev = data;
1655 	struct stm32_adc *adc = iio_priv(indio_dev);
1656 	const struct stm32_adc_regspec *regs = adc->cfg->regs;
1657 	u32 status = stm32_adc_readl(adc, regs->isr_eoc.reg);
1658 
1659 	/* Check ovr status right now, as ovr mask should be already disabled */
1660 	if (status & regs->isr_ovr.mask) {
1661 		/*
1662 		 * Clear ovr bit to avoid subsequent calls to IRQ handler.
1663 		 * This requires to stop ADC first. OVR bit state in ISR,
1664 		 * is propagated to CSR register by hardware.
1665 		 */
1666 		adc->cfg->stop_conv(indio_dev);
1667 		stm32_adc_irq_clear(indio_dev, regs->isr_ovr.mask);
1668 		dev_err(&indio_dev->dev, "Overrun, stopping: restart needed\n");
1669 		return IRQ_HANDLED;
1670 	}
1671 
1672 	return IRQ_NONE;
1673 }
1674 
stm32_adc_isr(int irq,void * data)1675 static irqreturn_t stm32_adc_isr(int irq, void *data)
1676 {
1677 	struct iio_dev *indio_dev = data;
1678 	struct stm32_adc *adc = iio_priv(indio_dev);
1679 	const struct stm32_adc_regspec *regs = adc->cfg->regs;
1680 	u32 status = stm32_adc_readl(adc, regs->isr_eoc.reg);
1681 
1682 	if (status & regs->isr_ovr.mask) {
1683 		/*
1684 		 * Overrun occurred on regular conversions: data for wrong
1685 		 * channel may be read. Unconditionally disable interrupts
1686 		 * to stop processing data and print error message.
1687 		 * Restarting the capture can be done by disabling, then
1688 		 * re-enabling it (e.g. write 0, then 1 to buffer/enable).
1689 		 */
1690 		stm32_adc_ovr_irq_disable(adc);
1691 		stm32_adc_conv_irq_disable(adc);
1692 		return IRQ_WAKE_THREAD;
1693 	}
1694 
1695 	if (status & regs->isr_eoc.mask) {
1696 		/* Reading DR also clears EOC status flag */
1697 		adc->buffer[adc->bufi] = stm32_adc_readw(adc, regs->dr);
1698 		if (iio_buffer_enabled(indio_dev)) {
1699 			adc->bufi++;
1700 			if (adc->bufi >= adc->num_conv) {
1701 				stm32_adc_conv_irq_disable(adc);
1702 				iio_trigger_poll(indio_dev->trig);
1703 			}
1704 		} else {
1705 			complete(&adc->completion);
1706 		}
1707 		return IRQ_HANDLED;
1708 	}
1709 
1710 	return IRQ_NONE;
1711 }
1712 
1713 /**
1714  * stm32_adc_validate_trigger() - validate trigger for stm32 adc
1715  * @indio_dev: IIO device
1716  * @trig: new trigger
1717  *
1718  * Returns: 0 if trig matches one of the triggers registered by stm32 adc
1719  * driver, -EINVAL otherwise.
1720  */
stm32_adc_validate_trigger(struct iio_dev * indio_dev,struct iio_trigger * trig)1721 static int stm32_adc_validate_trigger(struct iio_dev *indio_dev,
1722 				      struct iio_trigger *trig)
1723 {
1724 	return stm32_adc_get_trig_extsel(indio_dev, trig) < 0 ? -EINVAL : 0;
1725 }
1726 
stm32_adc_set_watermark(struct iio_dev * indio_dev,unsigned int val)1727 static int stm32_adc_set_watermark(struct iio_dev *indio_dev, unsigned int val)
1728 {
1729 	struct stm32_adc *adc = iio_priv(indio_dev);
1730 	unsigned int watermark = STM32_DMA_BUFFER_SIZE / 2;
1731 	unsigned int rx_buf_sz = STM32_DMA_BUFFER_SIZE;
1732 
1733 	/*
1734 	 * dma cyclic transfers are used, buffer is split into two periods.
1735 	 * There should be :
1736 	 * - always one buffer (period) dma is working on
1737 	 * - one buffer (period) driver can push data.
1738 	 */
1739 	watermark = min(watermark, val * (unsigned)(sizeof(u16)));
1740 	adc->rx_buf_sz = min(rx_buf_sz, watermark * 2 * adc->num_conv);
1741 
1742 	return 0;
1743 }
1744 
stm32_adc_update_scan_mode(struct iio_dev * indio_dev,const unsigned long * scan_mask)1745 static int stm32_adc_update_scan_mode(struct iio_dev *indio_dev,
1746 				      const unsigned long *scan_mask)
1747 {
1748 	struct stm32_adc *adc = iio_priv(indio_dev);
1749 	struct device *dev = indio_dev->dev.parent;
1750 	int ret;
1751 
1752 	ret = pm_runtime_resume_and_get(dev);
1753 	if (ret < 0)
1754 		return ret;
1755 
1756 	adc->num_conv = bitmap_weight(scan_mask, iio_get_masklength(indio_dev));
1757 
1758 	ret = stm32_adc_conf_scan_seq(indio_dev, scan_mask);
1759 	pm_runtime_put_autosuspend(dev);
1760 
1761 	return ret;
1762 }
1763 
stm32_adc_fwnode_xlate(struct iio_dev * indio_dev,const struct fwnode_reference_args * iiospec)1764 static int stm32_adc_fwnode_xlate(struct iio_dev *indio_dev,
1765 				  const struct fwnode_reference_args *iiospec)
1766 {
1767 	int i;
1768 
1769 	for (i = 0; i < indio_dev->num_channels; i++)
1770 		if (indio_dev->channels[i].channel == iiospec->args[0])
1771 			return i;
1772 
1773 	return -EINVAL;
1774 }
1775 
1776 /**
1777  * stm32_adc_debugfs_reg_access - read or write register value
1778  * @indio_dev: IIO device structure
1779  * @reg: register offset
1780  * @writeval: value to write
1781  * @readval: value to read
1782  *
1783  * To read a value from an ADC register:
1784  *   echo [ADC reg offset] > direct_reg_access
1785  *   cat direct_reg_access
1786  *
1787  * To write a value in a ADC register:
1788  *   echo [ADC_reg_offset] [value] > direct_reg_access
1789  */
stm32_adc_debugfs_reg_access(struct iio_dev * indio_dev,unsigned reg,unsigned writeval,unsigned * readval)1790 static int stm32_adc_debugfs_reg_access(struct iio_dev *indio_dev,
1791 					unsigned reg, unsigned writeval,
1792 					unsigned *readval)
1793 {
1794 	struct stm32_adc *adc = iio_priv(indio_dev);
1795 	struct device *dev = indio_dev->dev.parent;
1796 	int ret;
1797 
1798 	ret = pm_runtime_resume_and_get(dev);
1799 	if (ret < 0)
1800 		return ret;
1801 
1802 	if (!readval)
1803 		stm32_adc_writel(adc, reg, writeval);
1804 	else
1805 		*readval = stm32_adc_readl(adc, reg);
1806 
1807 	pm_runtime_put_autosuspend(dev);
1808 
1809 	return 0;
1810 }
1811 
1812 static const struct iio_info stm32_adc_iio_info = {
1813 	.read_raw = stm32_adc_read_raw,
1814 	.write_raw = stm32_adc_write_raw,
1815 	.read_avail = stm32_adc_read_avail,
1816 	.validate_trigger = stm32_adc_validate_trigger,
1817 	.hwfifo_set_watermark = stm32_adc_set_watermark,
1818 	.update_scan_mode = stm32_adc_update_scan_mode,
1819 	.debugfs_reg_access = stm32_adc_debugfs_reg_access,
1820 	.fwnode_xlate = stm32_adc_fwnode_xlate,
1821 };
1822 
stm32_adc_dma_residue(struct stm32_adc * adc)1823 static unsigned int stm32_adc_dma_residue(struct stm32_adc *adc)
1824 {
1825 	struct dma_tx_state state;
1826 	enum dma_status status;
1827 
1828 	status = dmaengine_tx_status(adc->dma_chan,
1829 				     adc->dma_chan->cookie,
1830 				     &state);
1831 	if (status == DMA_IN_PROGRESS) {
1832 		/* Residue is size in bytes from end of buffer */
1833 		unsigned int i = adc->rx_buf_sz - state.residue;
1834 		unsigned int size;
1835 
1836 		/* Return available bytes */
1837 		if (i >= adc->bufi)
1838 			size = i - adc->bufi;
1839 		else
1840 			size = adc->rx_buf_sz + i - adc->bufi;
1841 
1842 		return size;
1843 	}
1844 
1845 	return 0;
1846 }
1847 
stm32_adc_dma_buffer_done(void * data)1848 static void stm32_adc_dma_buffer_done(void *data)
1849 {
1850 	struct iio_dev *indio_dev = data;
1851 	struct stm32_adc *adc = iio_priv(indio_dev);
1852 	int residue = stm32_adc_dma_residue(adc);
1853 
1854 	/*
1855 	 * In DMA mode the trigger services of IIO are not used
1856 	 * (e.g. no call to iio_trigger_poll).
1857 	 * Calling irq handler associated to the hardware trigger is not
1858 	 * relevant as the conversions have already been done. Data
1859 	 * transfers are performed directly in DMA callback instead.
1860 	 * This implementation avoids to call trigger irq handler that
1861 	 * may sleep, in an atomic context (DMA irq handler context).
1862 	 */
1863 	dev_dbg(&indio_dev->dev, "%s bufi=%d\n", __func__, adc->bufi);
1864 
1865 	while (residue >= indio_dev->scan_bytes) {
1866 		u16 *buffer = (u16 *)&adc->rx_buf[adc->bufi];
1867 
1868 		iio_push_to_buffers(indio_dev, buffer);
1869 
1870 		residue -= indio_dev->scan_bytes;
1871 		adc->bufi += indio_dev->scan_bytes;
1872 		if (adc->bufi >= adc->rx_buf_sz)
1873 			adc->bufi = 0;
1874 	}
1875 }
1876 
stm32_adc_dma_start(struct iio_dev * indio_dev)1877 static int stm32_adc_dma_start(struct iio_dev *indio_dev)
1878 {
1879 	struct stm32_adc *adc = iio_priv(indio_dev);
1880 	struct dma_async_tx_descriptor *desc;
1881 	dma_cookie_t cookie;
1882 	int ret;
1883 
1884 	if (!adc->dma_chan)
1885 		return 0;
1886 
1887 	dev_dbg(&indio_dev->dev, "%s size=%d watermark=%d\n", __func__,
1888 		adc->rx_buf_sz, adc->rx_buf_sz / 2);
1889 
1890 	/* Prepare a DMA cyclic transaction */
1891 	desc = dmaengine_prep_dma_cyclic(adc->dma_chan,
1892 					 adc->rx_dma_buf,
1893 					 adc->rx_buf_sz, adc->rx_buf_sz / 2,
1894 					 DMA_DEV_TO_MEM,
1895 					 DMA_PREP_INTERRUPT);
1896 	if (!desc)
1897 		return -EBUSY;
1898 
1899 	desc->callback = stm32_adc_dma_buffer_done;
1900 	desc->callback_param = indio_dev;
1901 
1902 	cookie = dmaengine_submit(desc);
1903 	ret = dma_submit_error(cookie);
1904 	if (ret) {
1905 		dmaengine_terminate_sync(adc->dma_chan);
1906 		return ret;
1907 	}
1908 
1909 	/* Issue pending DMA requests */
1910 	dma_async_issue_pending(adc->dma_chan);
1911 
1912 	return 0;
1913 }
1914 
stm32_adc_buffer_postenable(struct iio_dev * indio_dev)1915 static int stm32_adc_buffer_postenable(struct iio_dev *indio_dev)
1916 {
1917 	struct stm32_adc *adc = iio_priv(indio_dev);
1918 	struct device *dev = indio_dev->dev.parent;
1919 	int ret;
1920 
1921 	ret = pm_runtime_resume_and_get(dev);
1922 	if (ret < 0)
1923 		return ret;
1924 
1925 	ret = stm32_adc_set_trig(indio_dev, indio_dev->trig);
1926 	if (ret) {
1927 		dev_err(&indio_dev->dev, "Can't set trigger\n");
1928 		goto err_pm_put;
1929 	}
1930 
1931 	ret = stm32_adc_dma_start(indio_dev);
1932 	if (ret) {
1933 		dev_err(&indio_dev->dev, "Can't start dma\n");
1934 		goto err_clr_trig;
1935 	}
1936 
1937 	/* Reset adc buffer index */
1938 	adc->bufi = 0;
1939 
1940 	stm32_adc_ovr_irq_enable(adc);
1941 
1942 	if (!adc->dma_chan)
1943 		stm32_adc_conv_irq_enable(adc);
1944 
1945 	adc->cfg->start_conv(indio_dev, !!adc->dma_chan);
1946 
1947 	return 0;
1948 
1949 err_clr_trig:
1950 	stm32_adc_set_trig(indio_dev, NULL);
1951 err_pm_put:
1952 	pm_runtime_put_autosuspend(dev);
1953 
1954 	return ret;
1955 }
1956 
stm32_adc_buffer_predisable(struct iio_dev * indio_dev)1957 static int stm32_adc_buffer_predisable(struct iio_dev *indio_dev)
1958 {
1959 	struct stm32_adc *adc = iio_priv(indio_dev);
1960 	struct device *dev = indio_dev->dev.parent;
1961 
1962 	adc->cfg->stop_conv(indio_dev);
1963 	if (!adc->dma_chan)
1964 		stm32_adc_conv_irq_disable(adc);
1965 
1966 	stm32_adc_ovr_irq_disable(adc);
1967 
1968 	if (adc->dma_chan)
1969 		dmaengine_terminate_sync(adc->dma_chan);
1970 
1971 	if (stm32_adc_set_trig(indio_dev, NULL))
1972 		dev_err(&indio_dev->dev, "Can't clear trigger\n");
1973 
1974 	pm_runtime_put_autosuspend(dev);
1975 
1976 	return 0;
1977 }
1978 
1979 static const struct iio_buffer_setup_ops stm32_adc_buffer_setup_ops = {
1980 	.postenable = &stm32_adc_buffer_postenable,
1981 	.predisable = &stm32_adc_buffer_predisable,
1982 };
1983 
stm32_adc_trigger_handler(int irq,void * p)1984 static irqreturn_t stm32_adc_trigger_handler(int irq, void *p)
1985 {
1986 	struct iio_poll_func *pf = p;
1987 	struct iio_dev *indio_dev = pf->indio_dev;
1988 	struct stm32_adc *adc = iio_priv(indio_dev);
1989 
1990 	dev_dbg(&indio_dev->dev, "%s bufi=%d\n", __func__, adc->bufi);
1991 
1992 	/* reset buffer index */
1993 	adc->bufi = 0;
1994 	iio_push_to_buffers_with_ts(indio_dev, adc->buffer, sizeof(adc->buffer),
1995 				    pf->timestamp);
1996 	iio_trigger_notify_done(indio_dev->trig);
1997 
1998 	/* re-enable eoc irq */
1999 	stm32_adc_conv_irq_enable(adc);
2000 
2001 	return IRQ_HANDLED;
2002 }
2003 
2004 static const struct iio_chan_spec_ext_info stm32_adc_ext_info[] = {
2005 	IIO_ENUM("trigger_polarity", IIO_SHARED_BY_ALL, &stm32_adc_trig_pol),
2006 	{
2007 		.name = "trigger_polarity_available",
2008 		.shared = IIO_SHARED_BY_ALL,
2009 		.read = iio_enum_available_read,
2010 		.private = (uintptr_t)&stm32_adc_trig_pol,
2011 	},
2012 	{ }
2013 };
2014 
stm32_adc_debugfs_init(struct iio_dev * indio_dev)2015 static void stm32_adc_debugfs_init(struct iio_dev *indio_dev)
2016 {
2017 	struct stm32_adc *adc = iio_priv(indio_dev);
2018 	struct dentry *d = iio_get_debugfs_dentry(indio_dev);
2019 	struct stm32_adc_calib *cal = &adc->cal;
2020 	char buf[16];
2021 	unsigned int i;
2022 
2023 	if (!adc->cfg->has_linearcal)
2024 		return;
2025 
2026 	for (i = 0; i < STM32H7_LINCALFACT_NUM; i++) {
2027 		snprintf(buf, sizeof(buf), "lincalfact%d", i + 1);
2028 		debugfs_create_u32(buf, 0444, d, &cal->lincalfact[i]);
2029 	}
2030 }
2031 
stm32_adc_fw_get_resolution(struct iio_dev * indio_dev)2032 static int stm32_adc_fw_get_resolution(struct iio_dev *indio_dev)
2033 {
2034 	struct device *dev = &indio_dev->dev;
2035 	struct stm32_adc *adc = iio_priv(indio_dev);
2036 	unsigned int i;
2037 	u32 res;
2038 
2039 	if (device_property_read_u32(dev, "assigned-resolution-bits", &res))
2040 		res = adc->cfg->adc_info->resolutions[0];
2041 
2042 	for (i = 0; i < adc->cfg->adc_info->num_res; i++)
2043 		if (res == adc->cfg->adc_info->resolutions[i])
2044 			break;
2045 	if (i >= adc->cfg->adc_info->num_res) {
2046 		dev_err(&indio_dev->dev, "Bad resolution: %u bits\n", res);
2047 		return -EINVAL;
2048 	}
2049 
2050 	dev_dbg(&indio_dev->dev, "Using %u bits resolution\n", res);
2051 	adc->res = i;
2052 
2053 	return 0;
2054 }
2055 
stm32_adc_smpr_init(struct stm32_adc * adc,int channel,u32 smp_ns)2056 static void stm32_adc_smpr_init(struct stm32_adc *adc, int channel, u32 smp_ns)
2057 {
2058 	const struct stm32_adc_regs *smpr = &adc->cfg->regs->smp_bits[channel];
2059 	u32 period_ns, shift = smpr->shift, mask = smpr->mask;
2060 	unsigned int i, smp, r = smpr->reg;
2061 
2062 	/*
2063 	 * For internal channels, ensure that the sampling time cannot
2064 	 * be lower than the one specified in the datasheet
2065 	 */
2066 	for (i = 0; i < STM32_ADC_INT_CH_NB; i++)
2067 		if (channel == adc->int_ch[i] && adc->int_ch[i] != STM32_ADC_INT_CH_NONE)
2068 			smp_ns = max(smp_ns, adc->cfg->ts_int_ch[i]);
2069 
2070 	/* Determine sampling time (ADC clock cycles) */
2071 	period_ns = NSEC_PER_SEC / adc->common->rate;
2072 	for (smp = 0; smp <= STM32_ADC_MAX_SMP; smp++)
2073 		if ((period_ns * adc->cfg->smp_cycles[smp]) >= smp_ns)
2074 			break;
2075 	if (smp > STM32_ADC_MAX_SMP)
2076 		smp = STM32_ADC_MAX_SMP;
2077 
2078 	/* pre-build sampling time registers (e.g. smpr1, smpr2) */
2079 	adc->smpr_val[r] = (adc->smpr_val[r] & ~mask) | (smp << shift);
2080 }
2081 
stm32_adc_chan_init_one(struct iio_dev * indio_dev,struct iio_chan_spec * chan,u32 vinp,u32 vinn,int scan_index,bool differential)2082 static void stm32_adc_chan_init_one(struct iio_dev *indio_dev,
2083 				    struct iio_chan_spec *chan, u32 vinp,
2084 				    u32 vinn, int scan_index, bool differential)
2085 {
2086 	struct stm32_adc *adc = iio_priv(indio_dev);
2087 	char *name = adc->chan_name[vinp];
2088 
2089 	chan->type = IIO_VOLTAGE;
2090 	chan->channel = vinp;
2091 	if (differential) {
2092 		chan->differential = 1;
2093 		chan->channel2 = vinn;
2094 		snprintf(name, STM32_ADC_CH_SZ, "in%d-in%d", vinp, vinn);
2095 	} else {
2096 		snprintf(name, STM32_ADC_CH_SZ, "in%d", vinp);
2097 	}
2098 	chan->datasheet_name = name;
2099 	chan->scan_index = scan_index;
2100 	chan->indexed = 1;
2101 	if (chan->channel == adc->int_ch[STM32_ADC_INT_CH_VREFINT])
2102 		chan->info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED);
2103 	else
2104 		chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
2105 	chan->info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |
2106 					 BIT(IIO_CHAN_INFO_OFFSET);
2107 	if (adc->cfg->has_oversampling) {
2108 		chan->info_mask_shared_by_all |= BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO);
2109 		chan->info_mask_shared_by_all_available = BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO);
2110 	}
2111 	chan->scan_type.sign = 'u';
2112 	chan->scan_type.realbits = adc->cfg->adc_info->resolutions[adc->res];
2113 	chan->scan_type.storagebits = 16;
2114 	chan->ext_info = stm32_adc_ext_info;
2115 
2116 	/* pre-build selected channels mask */
2117 	adc->pcsel |= BIT(chan->channel);
2118 	if (differential) {
2119 		/* pre-build diff channels mask */
2120 		adc->difsel |= BIT(chan->channel) & adc->cfg->regs->difsel.mask;
2121 		/* Also add negative input to pre-selected channels */
2122 		adc->pcsel |= BIT(chan->channel2);
2123 	}
2124 }
2125 
stm32_adc_get_legacy_chan_count(struct iio_dev * indio_dev,struct stm32_adc * adc)2126 static int stm32_adc_get_legacy_chan_count(struct iio_dev *indio_dev, struct stm32_adc *adc)
2127 {
2128 	struct device *dev = &indio_dev->dev;
2129 	const struct stm32_adc_info *adc_info = adc->cfg->adc_info;
2130 	int num_channels = 0, ret;
2131 
2132 	dev_dbg(&indio_dev->dev, "using legacy channel config\n");
2133 
2134 	ret = device_property_count_u32(dev, "st,adc-channels");
2135 	if (ret > adc_info->max_channels) {
2136 		dev_err(&indio_dev->dev, "Bad st,adc-channels?\n");
2137 		return -EINVAL;
2138 	} else if (ret > 0) {
2139 		num_channels += ret;
2140 	}
2141 
2142 	/*
2143 	 * each st,adc-diff-channels is a group of 2 u32 so we divide @ret
2144 	 * to get the *real* number of channels.
2145 	 */
2146 	ret = device_property_count_u32(dev, "st,adc-diff-channels");
2147 	if (ret > 0) {
2148 		ret /= (int)(sizeof(struct stm32_adc_diff_channel) / sizeof(u32));
2149 		if (ret > adc_info->max_channels) {
2150 			dev_err(&indio_dev->dev, "Bad st,adc-diff-channels?\n");
2151 			return -EINVAL;
2152 		} else if (ret > 0) {
2153 			adc->num_diff = ret;
2154 			num_channels += ret;
2155 		}
2156 	}
2157 
2158 	/* Optional sample time is provided either for each, or all channels */
2159 	adc->nsmps = device_property_count_u32(dev, "st,min-sample-time-nsecs");
2160 	if (adc->nsmps > 1 && adc->nsmps != num_channels) {
2161 		dev_err(&indio_dev->dev, "Invalid st,min-sample-time-nsecs\n");
2162 		return -EINVAL;
2163 	}
2164 
2165 	return num_channels;
2166 }
2167 
stm32_adc_legacy_chan_init(struct iio_dev * indio_dev,struct stm32_adc * adc,struct iio_chan_spec * channels,int nchans)2168 static int stm32_adc_legacy_chan_init(struct iio_dev *indio_dev,
2169 				      struct stm32_adc *adc,
2170 				      struct iio_chan_spec *channels,
2171 				      int nchans)
2172 {
2173 	const struct stm32_adc_info *adc_info = adc->cfg->adc_info;
2174 	struct stm32_adc_diff_channel diff[STM32_ADC_CH_MAX];
2175 	struct device *dev = &indio_dev->dev;
2176 	u32 num_diff = adc->num_diff;
2177 	int num_se = nchans - num_diff;
2178 	int size = num_diff * sizeof(*diff) / sizeof(u32);
2179 	int scan_index = 0, ret, i, c;
2180 	u32 smp = 0, smps[STM32_ADC_CH_MAX], chans[STM32_ADC_CH_MAX];
2181 
2182 	if (num_diff) {
2183 		ret = device_property_read_u32_array(dev, "st,adc-diff-channels",
2184 						     (u32 *)diff, size);
2185 		if (ret) {
2186 			dev_err(&indio_dev->dev, "Failed to get diff channels %d\n", ret);
2187 			return ret;
2188 		}
2189 
2190 		for (i = 0; i < num_diff; i++) {
2191 			if (diff[i].vinp >= adc_info->max_channels ||
2192 			    diff[i].vinn >= adc_info->max_channels) {
2193 				dev_err(&indio_dev->dev, "Invalid channel in%d-in%d\n",
2194 					diff[i].vinp, diff[i].vinn);
2195 				return -EINVAL;
2196 			}
2197 
2198 			stm32_adc_chan_init_one(indio_dev, &channels[scan_index],
2199 						diff[i].vinp, diff[i].vinn,
2200 						scan_index, true);
2201 			scan_index++;
2202 		}
2203 	}
2204 	if (num_se > 0) {
2205 		ret = device_property_read_u32_array(dev, "st,adc-channels", chans, num_se);
2206 		if (ret) {
2207 			dev_err(&indio_dev->dev, "Failed to get st,adc-channels %d\n", ret);
2208 			return ret;
2209 		}
2210 
2211 		for (c = 0; c < num_se; c++) {
2212 			if (chans[c] >= adc_info->max_channels) {
2213 				dev_err(&indio_dev->dev, "Invalid channel %d\n",
2214 					chans[c]);
2215 				return -EINVAL;
2216 			}
2217 
2218 			/* Channel can't be configured both as single-ended & diff */
2219 			for (i = 0; i < num_diff; i++) {
2220 				if (chans[c] == diff[i].vinp) {
2221 					dev_err(&indio_dev->dev, "channel %d misconfigured\n",
2222 						chans[c]);
2223 					return -EINVAL;
2224 				}
2225 			}
2226 			stm32_adc_chan_init_one(indio_dev, &channels[scan_index],
2227 						chans[c], 0, scan_index, false);
2228 			scan_index++;
2229 		}
2230 	}
2231 
2232 	if (adc->nsmps > 0) {
2233 		ret = device_property_read_u32_array(dev, "st,min-sample-time-nsecs",
2234 						     smps, adc->nsmps);
2235 		if (ret)
2236 			return ret;
2237 	}
2238 
2239 	for (i = 0; i < scan_index; i++) {
2240 		/*
2241 		 * This check is used with the above logic so that smp value
2242 		 * will only be modified if valid u32 value can be decoded. This
2243 		 * allows to get either no value, 1 shared value for all indexes,
2244 		 * or one value per channel. The point is to have the same
2245 		 * behavior as 'of_property_read_u32_index()'.
2246 		 */
2247 		if (i < adc->nsmps)
2248 			smp = smps[i];
2249 
2250 		/* Prepare sampling time settings */
2251 		stm32_adc_smpr_init(adc, channels[i].channel, smp);
2252 	}
2253 
2254 	return scan_index;
2255 }
2256 
stm32_adc_populate_int_ch(struct iio_dev * indio_dev,const char * ch_name,int chan)2257 static int stm32_adc_populate_int_ch(struct iio_dev *indio_dev, const char *ch_name,
2258 				     int chan)
2259 {
2260 	struct stm32_adc *adc = iio_priv(indio_dev);
2261 	u16 vrefint;
2262 	int i, ret;
2263 
2264 	for (i = 0; i < STM32_ADC_INT_CH_NB; i++) {
2265 		if (!strncmp(stm32_adc_ic[i].name, ch_name, STM32_ADC_CH_SZ)) {
2266 			/* Check internal channel availability */
2267 			switch (i) {
2268 			case STM32_ADC_INT_CH_VDDCORE:
2269 				if (!adc->cfg->regs->or_vddcore.reg)
2270 					dev_warn(&indio_dev->dev,
2271 						 "%s channel not available\n", ch_name);
2272 				break;
2273 			case STM32_ADC_INT_CH_VDDCPU:
2274 				if (!adc->cfg->regs->or_vddcpu.reg)
2275 					dev_warn(&indio_dev->dev,
2276 						 "%s channel not available\n", ch_name);
2277 				break;
2278 			case STM32_ADC_INT_CH_VDDQ_DDR:
2279 				if (!adc->cfg->regs->or_vddq_ddr.reg)
2280 					dev_warn(&indio_dev->dev,
2281 						 "%s channel not available\n", ch_name);
2282 				break;
2283 			case STM32_ADC_INT_CH_VREFINT:
2284 				if (!adc->cfg->regs->ccr_vref.reg)
2285 					dev_warn(&indio_dev->dev,
2286 						 "%s channel not available\n", ch_name);
2287 				break;
2288 			case STM32_ADC_INT_CH_VBAT:
2289 				if (!adc->cfg->regs->ccr_vbat.reg)
2290 					dev_warn(&indio_dev->dev,
2291 						 "%s channel not available\n", ch_name);
2292 				break;
2293 			}
2294 
2295 			if (stm32_adc_ic[i].idx != STM32_ADC_INT_CH_VREFINT) {
2296 				adc->int_ch[i] = chan;
2297 				break;
2298 			}
2299 
2300 			/* Get calibration data for vrefint channel */
2301 			ret = nvmem_cell_read_u16(&indio_dev->dev, "vrefint", &vrefint);
2302 			if (ret && ret != -ENOENT) {
2303 				return dev_err_probe(indio_dev->dev.parent, ret,
2304 						     "nvmem access error\n");
2305 			}
2306 			if (ret == -ENOENT) {
2307 				dev_dbg(&indio_dev->dev, "vrefint calibration not found. Skip vrefint channel\n");
2308 				return ret;
2309 			} else if (!vrefint) {
2310 				dev_dbg(&indio_dev->dev, "Null vrefint calibration value. Skip vrefint channel\n");
2311 				return -ENOENT;
2312 			}
2313 			adc->int_ch[i] = chan;
2314 			adc->vrefint.vrefint_cal = vrefint;
2315 		}
2316 	}
2317 
2318 	return 0;
2319 }
2320 
stm32_adc_generic_chan_init(struct iio_dev * indio_dev,struct stm32_adc * adc,struct iio_chan_spec * channels)2321 static int stm32_adc_generic_chan_init(struct iio_dev *indio_dev,
2322 				       struct stm32_adc *adc,
2323 				       struct iio_chan_spec *channels)
2324 {
2325 	const struct stm32_adc_info *adc_info = adc->cfg->adc_info;
2326 	struct device *dev = &indio_dev->dev;
2327 	const char *name;
2328 	int val, scan_index = 0, ret;
2329 	bool differential;
2330 	u32 vin[2];
2331 
2332 	device_for_each_child_node_scoped(dev, child) {
2333 		ret = fwnode_property_read_u32(child, "reg", &val);
2334 		if (ret)
2335 			return dev_err_probe(dev, ret,
2336 					     "Missing channel index\n");
2337 
2338 		ret = fwnode_property_read_string(child, "label", &name);
2339 		/* label is optional */
2340 		if (!ret) {
2341 			if (strlen(name) >= STM32_ADC_CH_SZ)
2342 				return dev_err_probe(dev, -EINVAL,
2343 						     "Label %s exceeds %d characters\n",
2344 						     name, STM32_ADC_CH_SZ);
2345 
2346 			strscpy(adc->chan_name[val], name, STM32_ADC_CH_SZ);
2347 			ret = stm32_adc_populate_int_ch(indio_dev, name, val);
2348 			if (ret == -ENOENT)
2349 				continue;
2350 			else if (ret)
2351 				return ret;
2352 		} else if (ret != -EINVAL) {
2353 			return dev_err_probe(dev, ret, "Invalid label\n");
2354 		}
2355 
2356 		if (val >= adc_info->max_channels)
2357 			return dev_err_probe(dev, -EINVAL,
2358 					     "Invalid channel %d\n", val);
2359 
2360 		differential = false;
2361 		ret = fwnode_property_read_u32_array(child, "diff-channels", vin, 2);
2362 		/* diff-channels is optional */
2363 		if (!ret) {
2364 			differential = true;
2365 			if (vin[0] != val || vin[1] >= adc_info->max_channels)
2366 				return dev_err_probe(dev, -EINVAL,
2367 						     "Invalid channel in%d-in%d\n",
2368 						     vin[0], vin[1]);
2369 		} else if (ret != -EINVAL) {
2370 			return dev_err_probe(dev, ret,
2371 					     "Invalid diff-channels property\n");
2372 		}
2373 
2374 		stm32_adc_chan_init_one(indio_dev, &channels[scan_index], val,
2375 					vin[1], scan_index, differential);
2376 
2377 		val = 0;
2378 		ret = fwnode_property_read_u32(child, "st,min-sample-time-ns", &val);
2379 		/* st,min-sample-time-ns is optional */
2380 		if (ret && ret != -EINVAL)
2381 			return dev_err_probe(dev, ret,
2382 					     "Invalid st,min-sample-time-ns property\n");
2383 
2384 		stm32_adc_smpr_init(adc, channels[scan_index].channel, val);
2385 		if (differential)
2386 			stm32_adc_smpr_init(adc, vin[1], val);
2387 
2388 		scan_index++;
2389 	}
2390 
2391 	return scan_index;
2392 }
2393 
stm32_adc_chan_fw_init(struct iio_dev * indio_dev,bool timestamping)2394 static int stm32_adc_chan_fw_init(struct iio_dev *indio_dev, bool timestamping)
2395 {
2396 	struct stm32_adc *adc = iio_priv(indio_dev);
2397 	const struct stm32_adc_info *adc_info = adc->cfg->adc_info;
2398 	struct iio_chan_spec *channels;
2399 	int scan_index = 0, num_channels = 0, ret, i;
2400 	bool legacy = false;
2401 
2402 	for (i = 0; i < STM32_ADC_INT_CH_NB; i++)
2403 		adc->int_ch[i] = STM32_ADC_INT_CH_NONE;
2404 
2405 	num_channels = device_get_child_node_count(&indio_dev->dev);
2406 	/* If no channels have been found, fallback to channels legacy properties. */
2407 	if (!num_channels) {
2408 		legacy = true;
2409 
2410 		ret = stm32_adc_get_legacy_chan_count(indio_dev, adc);
2411 		if (!ret) {
2412 			dev_err(indio_dev->dev.parent, "No channel found\n");
2413 			return -ENODATA;
2414 		} else if (ret < 0) {
2415 			return ret;
2416 		}
2417 
2418 		num_channels = ret;
2419 	}
2420 
2421 	if (num_channels > adc_info->max_channels) {
2422 		dev_err(&indio_dev->dev, "Channel number [%d] exceeds %d\n",
2423 			num_channels, adc_info->max_channels);
2424 		return -EINVAL;
2425 	}
2426 
2427 	if (timestamping)
2428 		num_channels++;
2429 
2430 	channels = devm_kcalloc(&indio_dev->dev, num_channels,
2431 				sizeof(struct iio_chan_spec), GFP_KERNEL);
2432 	if (!channels)
2433 		return -ENOMEM;
2434 
2435 	if (legacy)
2436 		ret = stm32_adc_legacy_chan_init(indio_dev, adc, channels,
2437 						 timestamping ? num_channels - 1 : num_channels);
2438 	else
2439 		ret = stm32_adc_generic_chan_init(indio_dev, adc, channels);
2440 	if (ret < 0)
2441 		return ret;
2442 	scan_index = ret;
2443 
2444 	if (timestamping) {
2445 		channels[scan_index] = IIO_CHAN_SOFT_TIMESTAMP(scan_index);
2446 		scan_index++;
2447 	}
2448 
2449 	indio_dev->num_channels = scan_index;
2450 	indio_dev->channels = channels;
2451 
2452 	return 0;
2453 }
2454 
stm32_adc_dma_request(struct device * dev,struct iio_dev * indio_dev)2455 static int stm32_adc_dma_request(struct device *dev, struct iio_dev *indio_dev)
2456 {
2457 	struct stm32_adc *adc = iio_priv(indio_dev);
2458 	struct dma_slave_config config = { };
2459 	int ret;
2460 
2461 	adc->dma_chan = dma_request_chan(dev, "rx");
2462 	if (IS_ERR(adc->dma_chan)) {
2463 		ret = PTR_ERR(adc->dma_chan);
2464 		if (ret != -ENODEV)
2465 			return dev_err_probe(dev, ret,
2466 					     "DMA channel request failed with\n");
2467 
2468 		/* DMA is optional: fall back to IRQ mode */
2469 		adc->dma_chan = NULL;
2470 		return 0;
2471 	}
2472 
2473 	adc->rx_buf = dma_alloc_coherent(adc->dma_chan->device->dev,
2474 					 STM32_DMA_BUFFER_SIZE,
2475 					 &adc->rx_dma_buf, GFP_KERNEL);
2476 	if (!adc->rx_buf) {
2477 		ret = -ENOMEM;
2478 		goto err_release;
2479 	}
2480 
2481 	/* Configure DMA channel to read data register */
2482 	config.src_addr = (dma_addr_t)adc->common->phys_base;
2483 	config.src_addr += adc->offset + adc->cfg->regs->dr;
2484 	config.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
2485 
2486 	ret = dmaengine_slave_config(adc->dma_chan, &config);
2487 	if (ret)
2488 		goto err_free;
2489 
2490 	return 0;
2491 
2492 err_free:
2493 	dma_free_coherent(adc->dma_chan->device->dev, STM32_DMA_BUFFER_SIZE,
2494 			  adc->rx_buf, adc->rx_dma_buf);
2495 err_release:
2496 	dma_release_channel(adc->dma_chan);
2497 
2498 	return ret;
2499 }
2500 
stm32_adc_probe(struct platform_device * pdev)2501 static int stm32_adc_probe(struct platform_device *pdev)
2502 {
2503 	struct iio_dev *indio_dev;
2504 	struct device *dev = &pdev->dev;
2505 	irqreturn_t (*handler)(int irq, void *p) = NULL;
2506 	struct stm32_adc *adc;
2507 	bool timestamping = false;
2508 	int ret;
2509 
2510 	indio_dev = devm_iio_device_alloc(&pdev->dev, sizeof(*adc));
2511 	if (!indio_dev)
2512 		return -ENOMEM;
2513 
2514 	adc = iio_priv(indio_dev);
2515 	adc->common = dev_get_drvdata(pdev->dev.parent);
2516 	spin_lock_init(&adc->lock);
2517 	init_completion(&adc->completion);
2518 	adc->cfg = device_get_match_data(dev);
2519 
2520 	indio_dev->name = dev_name(&pdev->dev);
2521 	device_set_node(&indio_dev->dev, dev_fwnode(&pdev->dev));
2522 	indio_dev->info = &stm32_adc_iio_info;
2523 	indio_dev->modes = INDIO_DIRECT_MODE | INDIO_HARDWARE_TRIGGERED;
2524 
2525 	platform_set_drvdata(pdev, indio_dev);
2526 
2527 	ret = device_property_read_u32(dev, "reg", &adc->offset);
2528 	if (ret != 0) {
2529 		dev_err(&pdev->dev, "missing reg property\n");
2530 		return -EINVAL;
2531 	}
2532 
2533 	adc->irq = platform_get_irq(pdev, 0);
2534 	if (adc->irq < 0)
2535 		return adc->irq;
2536 
2537 	ret = devm_request_threaded_irq(&pdev->dev, adc->irq, stm32_adc_isr,
2538 					stm32_adc_threaded_isr,
2539 					0, pdev->name, indio_dev);
2540 	if (ret) {
2541 		dev_err(&pdev->dev, "failed to request IRQ\n");
2542 		return ret;
2543 	}
2544 
2545 	adc->clk = devm_clk_get(&pdev->dev, NULL);
2546 	if (IS_ERR(adc->clk)) {
2547 		ret = PTR_ERR(adc->clk);
2548 		if (ret == -ENOENT && !adc->cfg->clk_required) {
2549 			adc->clk = NULL;
2550 		} else {
2551 			dev_err(&pdev->dev, "Can't get clock\n");
2552 			return ret;
2553 		}
2554 	}
2555 
2556 	ret = stm32_adc_fw_get_resolution(indio_dev);
2557 	if (ret < 0)
2558 		return ret;
2559 
2560 	ret = stm32_adc_dma_request(dev, indio_dev);
2561 	if (ret < 0)
2562 		return ret;
2563 
2564 	if (!adc->dma_chan) {
2565 		/* For PIO mode only, iio_pollfunc_store_time stores a timestamp
2566 		 * in the primary trigger IRQ handler and stm32_adc_trigger_handler
2567 		 * runs in the IRQ thread to push out buffer along with timestamp.
2568 		 */
2569 		handler = &stm32_adc_trigger_handler;
2570 		timestamping = true;
2571 	}
2572 
2573 	ret = stm32_adc_chan_fw_init(indio_dev, timestamping);
2574 	if (ret < 0)
2575 		goto err_dma_disable;
2576 
2577 	ret = iio_triggered_buffer_setup(indio_dev,
2578 					 &iio_pollfunc_store_time, handler,
2579 					 &stm32_adc_buffer_setup_ops);
2580 	if (ret) {
2581 		dev_err(&pdev->dev, "buffer setup failed\n");
2582 		goto err_dma_disable;
2583 	}
2584 
2585 	/* Get stm32-adc-core PM online */
2586 	pm_runtime_get_noresume(dev);
2587 	pm_runtime_set_active(dev);
2588 	pm_runtime_set_autosuspend_delay(dev, STM32_ADC_HW_STOP_DELAY_MS);
2589 	pm_runtime_use_autosuspend(dev);
2590 	pm_runtime_enable(dev);
2591 
2592 	ret = stm32_adc_hw_start(dev);
2593 	if (ret)
2594 		goto err_buffer_cleanup;
2595 
2596 	ret = iio_device_register(indio_dev);
2597 	if (ret) {
2598 		dev_err(&pdev->dev, "iio dev register failed\n");
2599 		goto err_hw_stop;
2600 	}
2601 
2602 	pm_runtime_put_autosuspend(dev);
2603 
2604 	if (IS_ENABLED(CONFIG_DEBUG_FS))
2605 		stm32_adc_debugfs_init(indio_dev);
2606 
2607 	return 0;
2608 
2609 err_hw_stop:
2610 	stm32_adc_hw_stop(dev);
2611 
2612 err_buffer_cleanup:
2613 	pm_runtime_disable(dev);
2614 	pm_runtime_set_suspended(dev);
2615 	pm_runtime_put_noidle(dev);
2616 	iio_triggered_buffer_cleanup(indio_dev);
2617 
2618 err_dma_disable:
2619 	if (adc->dma_chan) {
2620 		dma_free_coherent(adc->dma_chan->device->dev,
2621 				  STM32_DMA_BUFFER_SIZE,
2622 				  adc->rx_buf, adc->rx_dma_buf);
2623 		dma_release_channel(adc->dma_chan);
2624 	}
2625 
2626 	return ret;
2627 }
2628 
stm32_adc_remove(struct platform_device * pdev)2629 static void stm32_adc_remove(struct platform_device *pdev)
2630 {
2631 	struct iio_dev *indio_dev = platform_get_drvdata(pdev);
2632 	struct stm32_adc *adc = iio_priv(indio_dev);
2633 
2634 	pm_runtime_get_sync(&pdev->dev);
2635 	/* iio_device_unregister() also removes debugfs entries */
2636 	iio_device_unregister(indio_dev);
2637 	stm32_adc_hw_stop(&pdev->dev);
2638 	pm_runtime_disable(&pdev->dev);
2639 	pm_runtime_set_suspended(&pdev->dev);
2640 	pm_runtime_put_noidle(&pdev->dev);
2641 	iio_triggered_buffer_cleanup(indio_dev);
2642 	if (adc->dma_chan) {
2643 		dma_free_coherent(adc->dma_chan->device->dev,
2644 				  STM32_DMA_BUFFER_SIZE,
2645 				  adc->rx_buf, adc->rx_dma_buf);
2646 		dma_release_channel(adc->dma_chan);
2647 	}
2648 }
2649 
stm32_adc_suspend(struct device * dev)2650 static int stm32_adc_suspend(struct device *dev)
2651 {
2652 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2653 
2654 	if (iio_buffer_enabled(indio_dev))
2655 		stm32_adc_buffer_predisable(indio_dev);
2656 
2657 	return pm_runtime_force_suspend(dev);
2658 }
2659 
stm32_adc_resume(struct device * dev)2660 static int stm32_adc_resume(struct device *dev)
2661 {
2662 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2663 	int ret;
2664 
2665 	ret = pm_runtime_force_resume(dev);
2666 	if (ret < 0)
2667 		return ret;
2668 
2669 	if (!iio_buffer_enabled(indio_dev))
2670 		return 0;
2671 
2672 	ret = stm32_adc_update_scan_mode(indio_dev,
2673 					 indio_dev->active_scan_mask);
2674 	if (ret < 0)
2675 		return ret;
2676 
2677 	return stm32_adc_buffer_postenable(indio_dev);
2678 }
2679 
stm32_adc_runtime_suspend(struct device * dev)2680 static int stm32_adc_runtime_suspend(struct device *dev)
2681 {
2682 	return stm32_adc_hw_stop(dev);
2683 }
2684 
stm32_adc_runtime_resume(struct device * dev)2685 static int stm32_adc_runtime_resume(struct device *dev)
2686 {
2687 	return stm32_adc_hw_start(dev);
2688 }
2689 
2690 static const struct dev_pm_ops stm32_adc_pm_ops = {
2691 	SYSTEM_SLEEP_PM_OPS(stm32_adc_suspend, stm32_adc_resume)
2692 	RUNTIME_PM_OPS(stm32_adc_runtime_suspend, stm32_adc_runtime_resume,
2693 		       NULL)
2694 };
2695 
2696 static const struct stm32_adc_cfg stm32f4_adc_cfg = {
2697 	.regs = &stm32f4_adc_regspec,
2698 	.adc_info = &stm32f4_adc_info,
2699 	.trigs = stm32f4_adc_trigs,
2700 	.clk_required = true,
2701 	.start_conv = stm32f4_adc_start_conv,
2702 	.stop_conv = stm32f4_adc_stop_conv,
2703 	.smp_cycles = stm32f4_adc_smp_cycles,
2704 	.irq_clear = stm32f4_adc_irq_clear,
2705 };
2706 
2707 static const unsigned int stm32_adc_min_ts_h7[] = { 0, 0, 0, 4300, 9000 };
2708 static_assert(ARRAY_SIZE(stm32_adc_min_ts_h7) == STM32_ADC_INT_CH_NB);
2709 
2710 static const struct stm32_adc_cfg stm32h7_adc_cfg = {
2711 	.regs = &stm32h7_adc_regspec,
2712 	.adc_info = &stm32h7_adc_info,
2713 	.trigs = stm32h7_adc_trigs,
2714 	.has_boostmode = true,
2715 	.has_linearcal = true,
2716 	.has_presel = true,
2717 	.has_oversampling = true,
2718 	.start_conv = stm32h7_adc_start_conv,
2719 	.stop_conv = stm32h7_adc_stop_conv,
2720 	.prepare = stm32h7_adc_prepare,
2721 	.unprepare = stm32h7_adc_unprepare,
2722 	.smp_cycles = stm32h7_adc_smp_cycles,
2723 	.irq_clear = stm32h7_adc_irq_clear,
2724 	.ts_int_ch = stm32_adc_min_ts_h7,
2725 	.set_ovs = stm32h7_adc_set_ovs,
2726 };
2727 
2728 static const unsigned int stm32_adc_min_ts_mp1[] = { 100, 100, 100, 4300, 9800 };
2729 static_assert(ARRAY_SIZE(stm32_adc_min_ts_mp1) == STM32_ADC_INT_CH_NB);
2730 
2731 static const struct stm32_adc_cfg stm32mp1_adc_cfg = {
2732 	.regs = &stm32mp1_adc_regspec,
2733 	.adc_info = &stm32h7_adc_info,
2734 	.trigs = stm32h7_adc_trigs,
2735 	.has_vregready = true,
2736 	.has_boostmode = true,
2737 	.has_linearcal = true,
2738 	.has_presel = true,
2739 	.has_oversampling = true,
2740 	.start_conv = stm32h7_adc_start_conv,
2741 	.stop_conv = stm32h7_adc_stop_conv,
2742 	.prepare = stm32h7_adc_prepare,
2743 	.unprepare = stm32h7_adc_unprepare,
2744 	.smp_cycles = stm32h7_adc_smp_cycles,
2745 	.irq_clear = stm32h7_adc_irq_clear,
2746 	.ts_int_ch = stm32_adc_min_ts_mp1,
2747 	.set_ovs = stm32h7_adc_set_ovs,
2748 };
2749 
2750 static const unsigned int stm32_adc_min_ts_mp13[] = { 100, 0, 0, 4300, 9800 };
2751 static_assert(ARRAY_SIZE(stm32_adc_min_ts_mp13) == STM32_ADC_INT_CH_NB);
2752 
2753 static const struct stm32_adc_cfg stm32mp13_adc_cfg = {
2754 	.regs = &stm32mp13_adc_regspec,
2755 	.adc_info = &stm32mp13_adc_info,
2756 	.trigs = stm32h7_adc_trigs,
2757 	.has_oversampling = true,
2758 	.start_conv = stm32mp13_adc_start_conv,
2759 	.stop_conv = stm32h7_adc_stop_conv,
2760 	.prepare = stm32h7_adc_prepare,
2761 	.unprepare = stm32h7_adc_unprepare,
2762 	.smp_cycles = stm32mp13_adc_smp_cycles,
2763 	.irq_clear = stm32h7_adc_irq_clear,
2764 	.ts_int_ch = stm32_adc_min_ts_mp13,
2765 	.set_ovs = stm32mp13_adc_set_ovs,
2766 };
2767 
2768 static const struct of_device_id stm32_adc_of_match[] = {
2769 	{ .compatible = "st,stm32f4-adc", .data = (void *)&stm32f4_adc_cfg },
2770 	{ .compatible = "st,stm32h7-adc", .data = (void *)&stm32h7_adc_cfg },
2771 	{ .compatible = "st,stm32mp1-adc", .data = (void *)&stm32mp1_adc_cfg },
2772 	{ .compatible = "st,stm32mp13-adc", .data = (void *)&stm32mp13_adc_cfg },
2773 	{ }
2774 };
2775 MODULE_DEVICE_TABLE(of, stm32_adc_of_match);
2776 
2777 static struct platform_driver stm32_adc_driver = {
2778 	.probe = stm32_adc_probe,
2779 	.remove = stm32_adc_remove,
2780 	.driver = {
2781 		.name = "stm32-adc",
2782 		.of_match_table = stm32_adc_of_match,
2783 		.pm = pm_ptr(&stm32_adc_pm_ops),
2784 	},
2785 };
2786 module_platform_driver(stm32_adc_driver);
2787 
2788 MODULE_AUTHOR("Fabrice Gasnier <fabrice.gasnier@st.com>");
2789 MODULE_DESCRIPTION("STMicroelectronics STM32 ADC IIO driver");
2790 MODULE_LICENSE("GPL v2");
2791 MODULE_ALIAS("platform:stm32-adc");
2792