1 /*
2  * Copyright (c) 2018 Kokoon Technology Limited
3  * Copyright (c) 2019 Song Qiang <songqiang1304521@gmail.com>
4  * Copyright (c) 2019 Endre Karlson
5  * Copyright (c) 2020 Teslabs Engineering S.L.
6  * Copyright (c) 2021 Marius Scholtz, RIC Electronics
7  * Copyright (c) 2023 Hein Wessels, Nobleo Technology
8  *
9  * SPDX-License-Identifier: Apache-2.0
10  */
11 
12 #define DT_DRV_COMPAT st_stm32_adc
13 
14 #include <errno.h>
15 
16 #include <zephyr/drivers/adc.h>
17 #include <zephyr/drivers/pinctrl.h>
18 #include <zephyr/device.h>
19 #include <zephyr/kernel.h>
20 #include <zephyr/init.h>
21 #include <soc.h>
22 #include <stm32_ll_adc.h>
23 #if defined(CONFIG_SOC_SERIES_STM32U5X)
24 #include <stm32_ll_pwr.h>
25 #endif /* CONFIG_SOC_SERIES_STM32U5X */
26 
27 #ifdef CONFIG_ADC_STM32_DMA
28 #include <zephyr/drivers/dma/dma_stm32.h>
29 #include <zephyr/drivers/dma.h>
30 #include <zephyr/toolchain.h>
31 #include <stm32_ll_dma.h>
32 #endif
33 
34 #define ADC_CONTEXT_USES_KERNEL_TIMER
35 #define ADC_CONTEXT_ENABLE_ON_COMPLETE
36 #include "adc_context.h"
37 
38 #define LOG_LEVEL CONFIG_ADC_LOG_LEVEL
39 #include <zephyr/logging/log.h>
40 LOG_MODULE_REGISTER(adc_stm32);
41 
42 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
43 #include <zephyr/dt-bindings/adc/stm32_adc.h>
44 #include <zephyr/irq.h>
45 #include <zephyr/mem_mgmt/mem_attr.h>
46 
47 #ifdef CONFIG_SOC_SERIES_STM32H7X
48 #include <zephyr/dt-bindings/memory-attr/memory-attr-arm.h>
49 #endif
50 
51 #ifdef CONFIG_NOCACHE_MEMORY
52 #include <zephyr/linker/linker-defs.h>
53 #elif defined(CONFIG_CACHE_MANAGEMENT)
54 #include <zephyr/arch/cache.h>
55 #endif /* CONFIG_NOCACHE_MEMORY */
56 
57 #if defined(CONFIG_SOC_SERIES_STM32F3X)
58 #if defined(ADC1_V2_5)
59 /* ADC1_V2_5 is the ADC version for STM32F37x */
60 #define STM32F3X_ADC_V2_5
61 #elif defined(ADC5_V1_1)
62 /* ADC5_V1_1 is the ADC version for other STM32F3x */
63 #define STM32F3X_ADC_V1_1
64 #endif
65 #endif
66 /*
67  * Other ADC versions:
68  * ADC_VER_V5_V90 -> STM32H72x/H73x
69  * ADC_VER_V5_X -> STM32H74x/H75x && U5
70  * ADC_VER_V5_3 -> STM32H7Ax/H7Bx
71  * compat st_stm32f1_adc -> STM32F1, F37x (ADC1_V2_5)
72  * compat st_stm32f4_adc -> STM32F2, F4, F7, L1
73  */
74 
75 #define ANY_NUM_COMMON_SAMPLING_TIME_CHANNELS_IS(value) \
76 	(DT_INST_FOREACH_STATUS_OKAY_VARGS(IS_EQ_PROP_OR, \
77 					   num_sampling_time_common_channels,\
78 					   0, value) 0)
79 
80 #define ANY_ADC_SEQUENCER_TYPE_IS(value) \
81 	(DT_INST_FOREACH_STATUS_OKAY_VARGS(IS_EQ_PROP_OR, \
82 					   st_adc_sequencer,\
83 					   0, value) 0)
84 
85 #define IS_EQ_PROP_OR(inst, prop, default_value, compare_value) \
86 	IS_EQ(DT_INST_PROP_OR(inst, prop, default_value), compare_value) ||
87 
88 /* reference voltage for the ADC */
89 #define STM32_ADC_VREF_MV DT_INST_PROP(0, vref_mv)
90 
91 #if ANY_ADC_SEQUENCER_TYPE_IS(FULLY_CONFIGURABLE)
92 #define RANK(n)		LL_ADC_REG_RANK_##n
93 static const uint32_t table_rank[] = {
94 	RANK(1),
95 	RANK(2),
96 	RANK(3),
97 	RANK(4),
98 	RANK(5),
99 	RANK(6),
100 	RANK(7),
101 	RANK(8),
102 	RANK(9),
103 	RANK(10),
104 	RANK(11),
105 	RANK(12),
106 	RANK(13),
107 	RANK(14),
108 	RANK(15),
109 	RANK(16),
110 #if defined(LL_ADC_REG_RANK_17)
111 	RANK(17),
112 	RANK(18),
113 	RANK(19),
114 	RANK(20),
115 	RANK(21),
116 	RANK(22),
117 	RANK(23),
118 	RANK(24),
119 	RANK(25),
120 	RANK(26),
121 	RANK(27),
122 #if defined(LL_ADC_REG_RANK_28)
123 	RANK(28),
124 #endif /* LL_ADC_REG_RANK_28 */
125 #endif /* LL_ADC_REG_RANK_17 */
126 };
127 
128 #define SEQ_LEN(n)	LL_ADC_REG_SEQ_SCAN_ENABLE_##n##RANKS
129 /* Length of this array signifies the maximum sequence length */
130 static const uint32_t table_seq_len[] = {
131 	LL_ADC_REG_SEQ_SCAN_DISABLE,
132 	SEQ_LEN(2),
133 	SEQ_LEN(3),
134 	SEQ_LEN(4),
135 	SEQ_LEN(5),
136 	SEQ_LEN(6),
137 	SEQ_LEN(7),
138 	SEQ_LEN(8),
139 	SEQ_LEN(9),
140 	SEQ_LEN(10),
141 	SEQ_LEN(11),
142 	SEQ_LEN(12),
143 	SEQ_LEN(13),
144 	SEQ_LEN(14),
145 	SEQ_LEN(15),
146 	SEQ_LEN(16),
147 #if defined(LL_ADC_REG_SEQ_SCAN_ENABLE_17RANKS)
148 	SEQ_LEN(17),
149 	SEQ_LEN(18),
150 	SEQ_LEN(19),
151 	SEQ_LEN(20),
152 	SEQ_LEN(21),
153 	SEQ_LEN(22),
154 	SEQ_LEN(23),
155 	SEQ_LEN(24),
156 	SEQ_LEN(25),
157 	SEQ_LEN(26),
158 	SEQ_LEN(27),
159 #if defined(LL_ADC_REG_SEQ_SCAN_ENABLE_28RANKS)
160 	SEQ_LEN(28),
161 #endif /* LL_ADC_REG_SEQ_SCAN_ENABLE_28RANKS */
162 #endif /* LL_ADC_REG_SEQ_SCAN_ENABLE_17RANKS */
163 };
164 #endif /* ANY_ADC_SEQUENCER_TYPE_IS(FULLY_CONFIGURABLE) */
165 
166 /* Number of different sampling time values */
167 #define STM32_NB_SAMPLING_TIME	8
168 
169 #ifdef CONFIG_ADC_STM32_DMA
170 struct stream {
171 	const struct device *dma_dev;
172 	uint32_t channel;
173 	struct dma_config dma_cfg;
174 	struct dma_block_config dma_blk_cfg;
175 	uint8_t priority;
176 	bool src_addr_increment;
177 	bool dst_addr_increment;
178 };
179 #endif /* CONFIG_ADC_STM32_DMA */
180 
181 struct adc_stm32_data {
182 	struct adc_context ctx;
183 	const struct device *dev;
184 	uint16_t *buffer;
185 	uint16_t *repeat_buffer;
186 
187 	uint8_t resolution;
188 	uint32_t channels;
189 	uint8_t channel_count;
190 	uint8_t samples_count;
191 	int8_t acq_time_index;
192 
193 #ifdef CONFIG_ADC_STM32_DMA
194 	volatile int dma_error;
195 	struct stream dma;
196 #endif
197 };
198 
199 struct adc_stm32_cfg {
200 	ADC_TypeDef *base;
201 	void (*irq_cfg_func)(void);
202 	const struct stm32_pclken *pclken;
203 	size_t pclk_len;
204 	uint32_t clk_prescaler;
205 	const struct pinctrl_dev_config *pcfg;
206 	const uint16_t sampling_time_table[STM32_NB_SAMPLING_TIME];
207 	int8_t num_sampling_time_common_channels;
208 	int8_t sequencer_type;
209 	int8_t res_table_size;
210 	const uint32_t res_table[];
211 };
212 
213 #ifdef CONFIG_ADC_STM32_SHARED_IRQS
214 static bool init_irq = true;
215 #endif
216 
217 #ifdef CONFIG_ADC_STM32_DMA
adc_stm32_dma_start(const struct device * dev,void * buffer,size_t channel_count)218 static int adc_stm32_dma_start(const struct device *dev,
219 			       void *buffer, size_t channel_count)
220 {
221 	const struct adc_stm32_cfg *config = dev->config;
222 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
223 	struct adc_stm32_data *data = dev->data;
224 	struct dma_block_config *blk_cfg;
225 	int ret;
226 
227 	struct stream *dma = &data->dma;
228 
229 	blk_cfg = &dma->dma_blk_cfg;
230 
231 	/* prepare the block */
232 	blk_cfg->block_size = channel_count * sizeof(int16_t);
233 
234 	/* Source and destination */
235 	blk_cfg->source_address = (uint32_t)LL_ADC_DMA_GetRegAddr(adc, LL_ADC_DMA_REG_REGULAR_DATA);
236 	blk_cfg->source_addr_adj = DMA_ADDR_ADJ_NO_CHANGE;
237 	blk_cfg->source_reload_en = 0;
238 
239 	blk_cfg->dest_address = (uint32_t)buffer;
240 	blk_cfg->dest_addr_adj = DMA_ADDR_ADJ_INCREMENT;
241 	blk_cfg->dest_reload_en = 0;
242 
243 	/* Manually set the FIFO threshold to 1/4 because the
244 	 * dmamux DTS entry does not contain fifo threshold
245 	 */
246 	blk_cfg->fifo_mode_control = 0;
247 
248 	/* direction is given by the DT */
249 	dma->dma_cfg.head_block = blk_cfg;
250 	dma->dma_cfg.user_data = data;
251 
252 	ret = dma_config(data->dma.dma_dev, data->dma.channel,
253 			 &dma->dma_cfg);
254 	if (ret != 0) {
255 		LOG_ERR("Problem setting up DMA: %d", ret);
256 		return ret;
257 	}
258 
259 	/* Allow ADC to create DMA request and set to one-shot mode,
260 	 * as implemented in HAL drivers, if applicable.
261 	 */
262 #if defined(ADC_VER_V5_V90)
263 	if (adc == ADC3) {
264 		LL_ADC_REG_SetDMATransferMode(adc,
265 			ADC3_CFGR_DMACONTREQ(LL_ADC_REG_DMA_TRANSFER_LIMITED));
266 		LL_ADC_EnableDMAReq(adc);
267 	} else {
268 		LL_ADC_REG_SetDataTransferMode(adc,
269 			ADC_CFGR_DMACONTREQ(LL_ADC_REG_DMA_TRANSFER_LIMITED));
270 	}
271 #elif defined(ADC_VER_V5_X)
272 	LL_ADC_REG_SetDataTransferMode(adc, LL_ADC_REG_DMA_TRANSFER_LIMITED);
273 #endif
274 
275 	data->dma_error = 0;
276 	ret = dma_start(data->dma.dma_dev, data->dma.channel);
277 	if (ret != 0) {
278 		LOG_ERR("Problem starting DMA: %d", ret);
279 		return ret;
280 	}
281 
282 	LOG_DBG("DMA started");
283 
284 	return ret;
285 }
286 #endif /* CONFIG_ADC_STM32_DMA */
287 
288 #if defined(CONFIG_ADC_STM32_DMA) && defined(CONFIG_SOC_SERIES_STM32H7X)
289 /* Returns true if given buffer is in a non-cacheable SRAM region.
290  * This is determined using the device tree, meaning the .nocache region won't work.
291  * The entire buffer must be in a single region.
292  * An example of how the SRAM region can be defined in the DTS:
293  *	&sram4 {
294  *		zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_RAM_NOCACHE) | ... )>;
295  *	};
296  */
buf_in_nocache(uintptr_t buf,size_t len_bytes)297 static bool buf_in_nocache(uintptr_t buf, size_t len_bytes)
298 {
299 	bool buf_within_nocache = false;
300 
301 #ifdef CONFIG_NOCACHE_MEMORY
302 	buf_within_nocache = (buf >= ((uintptr_t)_nocache_ram_start)) &&
303 		((buf + len_bytes - 1) <= ((uintptr_t)_nocache_ram_end));
304 	if (buf_within_nocache) {
305 		return true;
306 	}
307 #endif /* CONFIG_NOCACHE_MEMORY */
308 
309 	buf_within_nocache = mem_attr_check_buf(
310 		(void *)buf, len_bytes, DT_MEM_ARM(ATTR_MPU_RAM_NOCACHE)) == 0;
311 
312 	return buf_within_nocache;
313 }
314 #endif /* defined(CONFIG_ADC_STM32_DMA) && defined(CONFIG_SOC_SERIES_STM32H7X) */
315 
check_buffer(const struct adc_sequence * sequence,uint8_t active_channels)316 static int check_buffer(const struct adc_sequence *sequence,
317 			     uint8_t active_channels)
318 {
319 	size_t needed_buffer_size;
320 
321 	needed_buffer_size = active_channels * sizeof(uint16_t);
322 
323 	if (sequence->options) {
324 		needed_buffer_size *= (1 + sequence->options->extra_samplings);
325 	}
326 
327 	if (sequence->buffer_size < needed_buffer_size) {
328 		LOG_ERR("Provided buffer is too small (%u/%u)",
329 				sequence->buffer_size, needed_buffer_size);
330 		return -ENOMEM;
331 	}
332 
333 #if defined(CONFIG_ADC_STM32_DMA) && defined(CONFIG_SOC_SERIES_STM32H7X)
334 	/* Buffer is forced to be in non-cacheable SRAM region to avoid cache maintenance */
335 	if (!buf_in_nocache((uintptr_t)sequence->buffer, needed_buffer_size)) {
336 		LOG_ERR("Supplied buffer is not in a non-cacheable region according to DTS.");
337 		return -EINVAL;
338 	}
339 #endif
340 
341 	return 0;
342 }
343 
adc_stm32_start_conversion(const struct device * dev)344 static void adc_stm32_start_conversion(const struct device *dev)
345 {
346 	const struct adc_stm32_cfg *config = dev->config;
347 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
348 
349 	LOG_DBG("Starting conversion");
350 
351 #if !defined(CONFIG_SOC_SERIES_STM32F1X) && \
352 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
353 	LL_ADC_REG_StartConversion(adc);
354 #else
355 	LL_ADC_REG_StartConversionSWStart(adc);
356 #endif
357 }
358 
359 #if !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
360 
361 #define HAS_CALIBRATION
362 
363 /* Number of ADC clock cycles to wait before of after starting calibration */
364 #if defined(LL_ADC_DELAY_CALIB_ENABLE_ADC_CYCLES)
365 #define ADC_DELAY_CALIB_ADC_CYCLES	LL_ADC_DELAY_CALIB_ENABLE_ADC_CYCLES
366 #elif defined(LL_ADC_DELAY_ENABLE_CALIB_ADC_CYCLES)
367 #define ADC_DELAY_CALIB_ADC_CYCLES	LL_ADC_DELAY_ENABLE_CALIB_ADC_CYCLES
368 #elif defined(LL_ADC_DELAY_DISABLE_CALIB_ADC_CYCLES)
369 #define ADC_DELAY_CALIB_ADC_CYCLES	LL_ADC_DELAY_DISABLE_CALIB_ADC_CYCLES
370 #endif
371 
adc_stm32_calib_delay(const struct device * dev)372 static void adc_stm32_calib_delay(const struct device *dev)
373 {
374 	/*
375 	 * Calibration of F1 and F3 (ADC1_V2_5) must start two cycles after ADON
376 	 * is set.
377 	 * Other ADC modules have to wait for some cycles after calibration to
378 	 * be enabled.
379 	 */
380 	const struct adc_stm32_cfg *config = dev->config;
381 	const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
382 	uint32_t adc_rate, wait_cycles;
383 
384 	if (clock_control_get_rate(clk,
385 		(clock_control_subsys_t) &config->pclken[0], &adc_rate) < 0) {
386 		LOG_ERR("ADC clock rate get error.");
387 	}
388 
389 	if (adc_rate == 0) {
390 		LOG_ERR("ADC Clock rate null");
391 		return;
392 	}
393 	wait_cycles = SystemCoreClock / adc_rate *
394 		      ADC_DELAY_CALIB_ADC_CYCLES;
395 
396 	for (int i = wait_cycles; i >= 0; i--) {
397 	}
398 }
399 
adc_stm32_calib(const struct device * dev)400 static void adc_stm32_calib(const struct device *dev)
401 {
402 	const struct adc_stm32_cfg *config =
403 		(const struct adc_stm32_cfg *)dev->config;
404 	ADC_TypeDef *adc = config->base;
405 
406 #if defined(STM32F3X_ADC_V1_1) || \
407 	defined(CONFIG_SOC_SERIES_STM32L4X) || \
408 	defined(CONFIG_SOC_SERIES_STM32L5X) || \
409 	defined(CONFIG_SOC_SERIES_STM32H5X) || \
410 	defined(CONFIG_SOC_SERIES_STM32WBX) || \
411 	defined(CONFIG_SOC_SERIES_STM32G4X)
412 	LL_ADC_StartCalibration(adc, LL_ADC_SINGLE_ENDED);
413 #elif defined(CONFIG_SOC_SERIES_STM32C0X) || \
414 	defined(CONFIG_SOC_SERIES_STM32F0X) || \
415 	DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) || \
416 	defined(CONFIG_SOC_SERIES_STM32G0X) || \
417 	defined(CONFIG_SOC_SERIES_STM32L0X) || \
418 	defined(CONFIG_SOC_SERIES_STM32WLX) || \
419 	defined(CONFIG_SOC_SERIES_STM32WBAX)
420 	LL_ADC_StartCalibration(adc);
421 #elif defined(CONFIG_SOC_SERIES_STM32U5X)
422 	LL_ADC_StartCalibration(adc, LL_ADC_CALIB_OFFSET);
423 #elif defined(CONFIG_SOC_SERIES_STM32H7X)
424 	LL_ADC_StartCalibration(adc, LL_ADC_CALIB_OFFSET, LL_ADC_SINGLE_ENDED);
425 #endif
426 	/* Make sure ADCAL is cleared before returning for proper operations
427 	 * on the ADC control register, for enabling the peripheral for example
428 	 */
429 	while (LL_ADC_IsCalibrationOnGoing(adc)) {
430 	}
431 }
432 #endif
433 
434 /*
435  * Disable ADC peripheral, and wait until it is disabled
436  */
adc_stm32_disable(ADC_TypeDef * adc)437 static void adc_stm32_disable(ADC_TypeDef *adc)
438 {
439 	if (LL_ADC_IsEnabled(adc) != 1UL) {
440 		return;
441 	}
442 
443 	/* Stop ongoing conversion if any
444 	 * Software must poll ADSTART (or JADSTART) until the bit is reset before assuming
445 	 * the ADC is completely stopped.
446 	 */
447 
448 #if !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) && \
449 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
450 	if (LL_ADC_REG_IsConversionOngoing(adc)) {
451 		LL_ADC_REG_StopConversion(adc);
452 		while (LL_ADC_REG_IsConversionOngoing(adc)) {
453 		}
454 	}
455 #endif
456 
457 #if !defined(CONFIG_SOC_SERIES_STM32C0X) && \
458 	!defined(CONFIG_SOC_SERIES_STM32F0X) && \
459 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) && \
460 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc) && \
461 	!defined(CONFIG_SOC_SERIES_STM32G0X) && \
462 	!defined(CONFIG_SOC_SERIES_STM32L0X) && \
463 	!defined(CONFIG_SOC_SERIES_STM32WBAX) && \
464 	!defined(CONFIG_SOC_SERIES_STM32WLX)
465 	if (LL_ADC_INJ_IsConversionOngoing(adc)) {
466 		LL_ADC_INJ_StopConversion(adc);
467 		while (LL_ADC_INJ_IsConversionOngoing(adc)) {
468 		}
469 	}
470 #endif
471 
472 	LL_ADC_Disable(adc);
473 
474 	/* Wait ADC is fully disabled so that we don't leave the driver into intermediate state
475 	 * which could prevent enabling the peripheral
476 	 */
477 	while (LL_ADC_IsEnabled(adc) == 1UL) {
478 	}
479 }
480 
481 #if !defined(CONFIG_SOC_SERIES_STM32F0X) && \
482 	!defined(CONFIG_SOC_SERIES_STM32F1X) && \
483 	!defined(CONFIG_SOC_SERIES_STM32F3X) && \
484 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
485 
486 #define HAS_OVERSAMPLING
487 
488 #define OVS_SHIFT(n)		LL_ADC_OVS_SHIFT_RIGHT_##n
489 static const uint32_t table_oversampling_shift[] = {
490 	LL_ADC_OVS_SHIFT_NONE,
491 	OVS_SHIFT(1),
492 	OVS_SHIFT(2),
493 	OVS_SHIFT(3),
494 	OVS_SHIFT(4),
495 	OVS_SHIFT(5),
496 	OVS_SHIFT(6),
497 	OVS_SHIFT(7),
498 	OVS_SHIFT(8),
499 #if defined(CONFIG_SOC_SERIES_STM32H7X) || \
500 	defined(CONFIG_SOC_SERIES_STM32U5X)
501 	OVS_SHIFT(9),
502 	OVS_SHIFT(10),
503 #endif
504 };
505 
506 #ifdef LL_ADC_OVS_RATIO_2
507 #define OVS_RATIO(n)		LL_ADC_OVS_RATIO_##n
508 static const uint32_t table_oversampling_ratio[] = {
509 	0,
510 	OVS_RATIO(2),
511 	OVS_RATIO(4),
512 	OVS_RATIO(8),
513 	OVS_RATIO(16),
514 	OVS_RATIO(32),
515 	OVS_RATIO(64),
516 	OVS_RATIO(128),
517 	OVS_RATIO(256),
518 };
519 #endif
520 
521 /*
522  * Function to configure the oversampling scope. It is basically a wrapper over
523  * LL_ADC_SetOverSamplingScope() which in addition stops the ADC if needed.
524  */
adc_stm32_oversampling_scope(ADC_TypeDef * adc,uint32_t ovs_scope)525 static void adc_stm32_oversampling_scope(ADC_TypeDef *adc, uint32_t ovs_scope)
526 {
527 #if defined(CONFIG_SOC_SERIES_STM32L0X) || \
528 	defined(CONFIG_SOC_SERIES_STM32WLX)
529 	/*
530 	 * setting OVS bits is conditioned to ADC state: ADC must be disabled
531 	 * or enabled without conversion on going : disable it, it will stop
532 	 */
533 	if (LL_ADC_GetOverSamplingScope(adc) == ovs_scope) {
534 		return;
535 	}
536 	adc_stm32_disable(adc);
537 #endif
538 	LL_ADC_SetOverSamplingScope(adc, ovs_scope);
539 }
540 
541 /*
542  * Function to configure the oversampling ratio and shift. It is basically a
543  * wrapper over LL_ADC_SetOverSamplingRatioShift() which in addition stops the
544  * ADC if needed.
545  */
adc_stm32_oversampling_ratioshift(ADC_TypeDef * adc,uint32_t ratio,uint32_t shift)546 static void adc_stm32_oversampling_ratioshift(ADC_TypeDef *adc, uint32_t ratio, uint32_t shift)
547 {
548 	/*
549 	 * setting OVS bits is conditioned to ADC state: ADC must be disabled
550 	 * or enabled without conversion on going : disable it, it will stop
551 	 */
552 	if ((LL_ADC_GetOverSamplingRatio(adc) == ratio)
553 	    && (LL_ADC_GetOverSamplingShift(adc) == shift)) {
554 		return;
555 	}
556 	adc_stm32_disable(adc);
557 
558 	LL_ADC_ConfigOverSamplingRatioShift(adc, ratio, shift);
559 }
560 
561 /*
562  * Function to configure the oversampling ratio and shit using stm32 LL
563  * ratio is directly the sequence->oversampling (a 2^n value)
564  * shift is the corresponding LL_ADC_OVS_SHIFT_RIGHT_x constant
565  */
adc_stm32_oversampling(ADC_TypeDef * adc,uint8_t ratio)566 static int adc_stm32_oversampling(ADC_TypeDef *adc, uint8_t ratio)
567 {
568 	if (ratio == 0) {
569 		adc_stm32_oversampling_scope(adc, LL_ADC_OVS_DISABLE);
570 		return 0;
571 	} else if (ratio < ARRAY_SIZE(table_oversampling_shift)) {
572 		adc_stm32_oversampling_scope(adc, LL_ADC_OVS_GRP_REGULAR_CONTINUED);
573 	} else {
574 		LOG_ERR("Invalid oversampling");
575 		return -EINVAL;
576 	}
577 
578 	uint32_t shift = table_oversampling_shift[ratio];
579 
580 #if defined(CONFIG_SOC_SERIES_STM32H7X)
581 	/* Certain variants of the H7, such as STM32H72x/H73x has ADC3
582 	 * as a separate entity and require special handling.
583 	 */
584 #if defined(ADC_VER_V5_V90)
585 	if (adc != ADC3) {
586 		/* the LL function expects a value from 1 to 1024 */
587 		adc_stm32_oversampling_ratioshift(adc, 1 << ratio, shift);
588 	} else {
589 		/* the LL function expects a value LL_ADC_OVS_RATIO_x */
590 		adc_stm32_oversampling_ratioshift(adc, table_oversampling_ratio[ratio], shift);
591 	}
592 #else
593 	/* the LL function expects a value from 1 to 1024 */
594 	adc_stm32_oversampling_ratioshift(adc, 1 << ratio, shift);
595 #endif /* defined(ADC_VER_V5_V90) */
596 #elif defined(CONFIG_SOC_SERIES_STM32U5X)
597 	if (adc != ADC4) {
598 		/* the LL function expects a value from 1 to 1024 */
599 		adc_stm32_oversampling_ratioshift(adc, (1 << ratio), shift);
600 	} else {
601 		/* the LL function expects a value LL_ADC_OVS_RATIO_x */
602 		adc_stm32_oversampling_ratioshift(adc, table_oversampling_ratio[ratio], shift);
603 	}
604 #else /* CONFIG_SOC_SERIES_STM32H7X */
605 	adc_stm32_oversampling_ratioshift(adc, table_oversampling_ratio[ratio], shift);
606 #endif /* CONFIG_SOC_SERIES_STM32H7X */
607 
608 	return 0;
609 }
610 #endif /* CONFIG_SOC_SERIES_STM32xxx */
611 
612 /*
613  * Enable ADC peripheral, and wait until ready if required by SOC.
614  */
adc_stm32_enable(ADC_TypeDef * adc)615 static int adc_stm32_enable(ADC_TypeDef *adc)
616 {
617 	if (LL_ADC_IsEnabled(adc) == 1UL) {
618 		return 0;
619 	}
620 
621 #if !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) && \
622 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
623 	LL_ADC_ClearFlag_ADRDY(adc);
624 	LL_ADC_Enable(adc);
625 
626 	/*
627 	 * Enabling ADC modules in many series may fail if they are
628 	 * still not stabilized, this will wait for a short time (about 1ms)
629 	 * to ensure ADC modules are properly enabled.
630 	 */
631 	uint32_t count_timeout = 0;
632 
633 	while (LL_ADC_IsActiveFlag_ADRDY(adc) == 0) {
634 #ifdef CONFIG_SOC_SERIES_STM32F0X
635 		/* For F0, continue to write ADEN=1 until ADRDY=1 */
636 		if (LL_ADC_IsEnabled(adc) == 0UL) {
637 			LL_ADC_Enable(adc);
638 		}
639 #endif /* CONFIG_SOC_SERIES_STM32F0X */
640 		count_timeout++;
641 		k_busy_wait(100);
642 		if (count_timeout >= 10) {
643 			return -ETIMEDOUT;
644 		}
645 	}
646 #else
647 	/*
648 	 * On STM32F1, F2, F37x, F4, F7 and L1, do not re-enable the ADC.
649 	 * On F1 and F37x if ADON holds 1 (LL_ADC_IsEnabled is true) and 1 is
650 	 * written, then conversion starts. That's not what is expected.
651 	 */
652 	LL_ADC_Enable(adc);
653 #endif
654 
655 	return 0;
656 }
657 
658 #ifdef CONFIG_ADC_STM32_DMA
dma_callback(const struct device * dev,void * user_data,uint32_t channel,int status)659 static void dma_callback(const struct device *dev, void *user_data,
660 			 uint32_t channel, int status)
661 {
662 	/* user_data directly holds the adc device */
663 	struct adc_stm32_data *data = user_data;
664 	const struct adc_stm32_cfg *config = data->dev->config;
665 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
666 
667 	LOG_DBG("dma callback");
668 
669 	if (channel == data->dma.channel) {
670 #if !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
671 		if (LL_ADC_IsActiveFlag_OVR(adc) || (status >= 0)) {
672 #else
673 		if (status >= 0) {
674 #endif /* !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) */
675 			data->samples_count = data->channel_count;
676 			data->buffer += data->channel_count;
677 			/* Stop the DMA engine, only to start it again when the callback returns
678 			 * ADC_ACTION_REPEAT or ADC_ACTION_CONTINUE, or the number of samples
679 			 * haven't been reached Starting the DMA engine is done
680 			 * within adc_context_start_sampling
681 			 */
682 			dma_stop(data->dma.dma_dev, data->dma.channel);
683 #if !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
684 			LL_ADC_ClearFlag_OVR(adc);
685 #endif /* !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) */
686 			/* No need to invalidate the cache because it's assumed that
687 			 * the address is in a non-cacheable SRAM region.
688 			 */
689 			adc_context_on_sampling_done(&data->ctx, dev);
690 		} else if (status < 0) {
691 			LOG_ERR("DMA sampling complete, but DMA reported error %d", status);
692 			data->dma_error = status;
693 			LL_ADC_REG_StopConversion(adc);
694 			dma_stop(data->dma.dma_dev, data->dma.channel);
695 			adc_context_complete(&data->ctx, status);
696 		}
697 	}
698 }
699 #endif /* CONFIG_ADC_STM32_DMA */
700 
701 static uint8_t get_reg_value(const struct device *dev, uint32_t reg,
702 			     uint32_t shift, uint32_t mask)
703 {
704 	const struct adc_stm32_cfg *config = dev->config;
705 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
706 
707 	uintptr_t addr = (uintptr_t)adc + reg;
708 
709 	return ((*(volatile uint32_t *)addr >> shift) & mask);
710 }
711 
712 static void set_reg_value(const struct device *dev, uint32_t reg,
713 			  uint32_t shift, uint32_t mask, uint32_t value)
714 {
715 	const struct adc_stm32_cfg *config = dev->config;
716 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
717 
718 	uintptr_t addr = (uintptr_t)adc + reg;
719 
720 	MODIFY_REG(*(volatile uint32_t *)addr, (mask << shift), (value << shift));
721 }
722 
723 static int set_resolution(const struct device *dev,
724 			  const struct adc_sequence *sequence)
725 {
726 	const struct adc_stm32_cfg *config = dev->config;
727 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
728 	uint8_t res_reg_addr = 0xFF;
729 	uint8_t res_shift = 0;
730 	uint8_t res_mask = 0;
731 	uint8_t res_reg_val = 0;
732 	int i;
733 
734 	for (i = 0; i < config->res_table_size; i++) {
735 		if (sequence->resolution == STM32_ADC_GET_REAL_VAL(config->res_table[i])) {
736 			res_reg_addr = STM32_ADC_GET_REG(config->res_table[i]);
737 			res_shift = STM32_ADC_GET_SHIFT(config->res_table[i]);
738 			res_mask = STM32_ADC_GET_MASK(config->res_table[i]);
739 			res_reg_val = STM32_ADC_GET_REG_VAL(config->res_table[i]);
740 			break;
741 		}
742 	}
743 
744 	if (i == config->res_table_size) {
745 		LOG_ERR("Invalid resolution");
746 		return -EINVAL;
747 	}
748 
749 	/*
750 	 * Some MCUs (like STM32F1x) have no register to configure resolution.
751 	 * These MCUs have a register address value of 0xFF and should be
752 	 * ignored.
753 	 */
754 	if (res_reg_addr != 0xFF) {
755 		/*
756 		 * We don't use LL_ADC_SetResolution and LL_ADC_GetResolution
757 		 * because they don't strictly use hardware resolution values
758 		 * and makes internal conversions for some series.
759 		 * (see stm32h7xx_ll_adc.h)
760 		 * Instead we set the register ourselves if needed.
761 		 */
762 		if (get_reg_value(dev, res_reg_addr, res_shift, res_mask) != res_reg_val) {
763 			/*
764 			 * Writing ADC_CFGR1 register while ADEN bit is set
765 			 * resets RES[1:0] bitfield. We need to disable and enable adc.
766 			 */
767 			adc_stm32_disable(adc);
768 			set_reg_value(dev, res_reg_addr, res_shift, res_mask, res_reg_val);
769 		}
770 	}
771 
772 	return 0;
773 }
774 
775 static int set_sequencer(const struct device *dev)
776 {
777 	const struct adc_stm32_cfg *config = dev->config;
778 	struct adc_stm32_data *data = dev->data;
779 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
780 
781 	uint8_t channel_id;
782 	uint8_t channel_index = 0;
783 	uint32_t channels_mask = 0;
784 
785 	/* Iterate over selected channels in bitmask keeping track of:
786 	 * - channel_index: ranging from 0 -> ( data->channel_count - 1 )
787 	 * - channel_id: ordinal position of channel in data->channels bitmask
788 	 */
789 	for (uint32_t channels = data->channels; channels;
790 		      channels &= ~BIT(channel_id), channel_index++) {
791 		channel_id = find_lsb_set(channels) - 1;
792 
793 		uint32_t channel = __LL_ADC_DECIMAL_NB_TO_CHANNEL(channel_id);
794 
795 		channels_mask |= channel;
796 
797 #if ANY_ADC_SEQUENCER_TYPE_IS(FULLY_CONFIGURABLE)
798 		if (config->sequencer_type == FULLY_CONFIGURABLE) {
799 #if defined(CONFIG_SOC_SERIES_STM32H7X) || defined(CONFIG_SOC_SERIES_STM32U5X)
800 			/*
801 			 * Each channel in the sequence must be previously enabled in PCSEL.
802 			 * This register controls the analog switch integrated in the IO level.
803 			 */
804 			LL_ADC_SetChannelPreselection(adc, channel);
805 #endif /* CONFIG_SOC_SERIES_STM32H7X || CONFIG_SOC_SERIES_STM32U5X */
806 			LL_ADC_REG_SetSequencerRanks(adc, table_rank[channel_index], channel);
807 			LL_ADC_REG_SetSequencerLength(adc, table_seq_len[channel_index]);
808 		}
809 #endif /* ANY_ADC_SEQUENCER_TYPE_IS(FULLY_CONFIGURABLE) */
810 	}
811 
812 #if ANY_ADC_SEQUENCER_TYPE_IS(NOT_FULLY_CONFIGURABLE)
813 	if (config->sequencer_type == NOT_FULLY_CONFIGURABLE) {
814 		LL_ADC_REG_SetSequencerChannels(adc, channels_mask);
815 
816 #if !defined(CONFIG_SOC_SERIES_STM32F0X) && \
817 	!defined(CONFIG_SOC_SERIES_STM32L0X) && \
818 	!defined(CONFIG_SOC_SERIES_STM32U5X) && \
819 	!defined(CONFIG_SOC_SERIES_STM32WBAX)
820 		/*
821 		 * After modifying sequencer it is mandatory to wait for the
822 		 * assertion of CCRDY flag
823 		 */
824 		while (LL_ADC_IsActiveFlag_CCRDY(adc) == 0) {
825 		}
826 		LL_ADC_ClearFlag_CCRDY(adc);
827 #endif /* !CONFIG_SOC_SERIES_STM32F0X && !L0X && !U5X && !WBAX */
828 	}
829 #endif /* ANY_ADC_SEQUENCER_TYPE_IS(NOT_FULLY_CONFIGURABLE) */
830 
831 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) || \
832 	DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
833 	LL_ADC_SetSequencersScanMode(adc, LL_ADC_SEQ_SCAN_ENABLE);
834 #endif /* st_stm32f1_adc || st_stm32f4_adc */
835 
836 	return 0;
837 }
838 
839 static int start_read(const struct device *dev,
840 		      const struct adc_sequence *sequence)
841 {
842 	const struct adc_stm32_cfg *config = dev->config;
843 	struct adc_stm32_data *data = dev->data;
844 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
845 	int err;
846 
847 	data->buffer = sequence->buffer;
848 	data->channels = sequence->channels;
849 	data->channel_count = POPCOUNT(data->channels);
850 	data->samples_count = 0;
851 
852 	if (data->channel_count == 0) {
853 		LOG_ERR("No channels selected");
854 		return -EINVAL;
855 	}
856 
857 #if ANY_ADC_SEQUENCER_TYPE_IS(FULLY_CONFIGURABLE)
858 	if (data->channel_count > ARRAY_SIZE(table_seq_len)) {
859 		LOG_ERR("Too many channels for sequencer. Max: %d", ARRAY_SIZE(table_seq_len));
860 		return -EINVAL;
861 	}
862 #endif /* ANY_ADC_SEQUENCER_TYPE_IS(FULLY_CONFIGURABLE) */
863 
864 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) && !defined(CONFIG_ADC_STM32_DMA)
865 	/* Multiple samplings is only supported with DMA for F1 */
866 	if (data->channel_count > 1) {
867 		LOG_ERR("Without DMA, this device only supports single channel sampling");
868 		return -EINVAL;
869 	}
870 #endif /* DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) && !CONFIG_ADC_STM32_DMA */
871 
872 	/* Check and set the resolution */
873 	err = set_resolution(dev, sequence);
874 	if (err < 0) {
875 		return err;
876 	}
877 
878 	/* Configure the sequencer */
879 	err = set_sequencer(dev);
880 	if (err < 0) {
881 		return err;
882 	}
883 
884 	err = check_buffer(sequence, data->channel_count);
885 	if (err) {
886 		return err;
887 	}
888 
889 #ifdef HAS_OVERSAMPLING
890 	err = adc_stm32_oversampling(adc, sequence->oversampling);
891 	if (err) {
892 		return err;
893 	}
894 #else
895 	if (sequence->oversampling) {
896 		LOG_ERR("Oversampling not supported");
897 		return -ENOTSUP;
898 	}
899 #endif /* HAS_OVERSAMPLING */
900 
901 	if (sequence->calibrate) {
902 #if !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) && \
903 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
904 
905 		/* we cannot calibrate the ADC while the ADC is enabled */
906 		adc_stm32_disable(adc);
907 		adc_stm32_calib(dev);
908 #else
909 		LOG_ERR("Calibration not supported");
910 		return -ENOTSUP;
911 #endif
912 	}
913 
914 	/*
915 	 * Make sure the ADC is enabled as it might have been disabled earlier
916 	 * to set the resolution, to set the oversampling or to perform the
917 	 * calibration.
918 	 */
919 	adc_stm32_enable(adc);
920 
921 #if !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
922 	LL_ADC_ClearFlag_OVR(adc);
923 #endif /* !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) */
924 
925 #if !defined(CONFIG_ADC_STM32_DMA)
926 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
927 	/* Trigger an ISR after each sampling (not just end of sequence) */
928 	LL_ADC_REG_SetFlagEndOfConversion(adc, LL_ADC_REG_FLAG_EOC_UNITARY_CONV);
929 	LL_ADC_EnableIT_EOCS(adc);
930 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
931 	LL_ADC_EnableIT_EOS(adc);
932 #else
933 	LL_ADC_EnableIT_EOC(adc);
934 #endif
935 #endif /* CONFIG_ADC_STM32_DMA */
936 
937 	/* This call will start the DMA */
938 	adc_context_start_read(&data->ctx, sequence);
939 
940 	int result = adc_context_wait_for_completion(&data->ctx);
941 
942 #ifdef CONFIG_ADC_STM32_DMA
943 	/* check if there's anything wrong with dma start */
944 	result = (data->dma_error ? data->dma_error : result);
945 #endif
946 
947 	return result;
948 }
949 
950 static void adc_context_start_sampling(struct adc_context *ctx)
951 {
952 	struct adc_stm32_data *data =
953 		CONTAINER_OF(ctx, struct adc_stm32_data, ctx);
954 
955 	data->repeat_buffer = data->buffer;
956 
957 #ifdef CONFIG_ADC_STM32_DMA
958 	adc_stm32_dma_start(data->dev, data->buffer, data->channel_count);
959 #endif
960 	adc_stm32_start_conversion(data->dev);
961 }
962 
963 static void adc_context_update_buffer_pointer(struct adc_context *ctx,
964 					      bool repeat_sampling)
965 {
966 	struct adc_stm32_data *data =
967 		CONTAINER_OF(ctx, struct adc_stm32_data, ctx);
968 
969 	if (repeat_sampling) {
970 		data->buffer = data->repeat_buffer;
971 	}
972 }
973 
974 #ifndef CONFIG_ADC_STM32_DMA
975 static void adc_stm32_isr(const struct device *dev)
976 {
977 	struct adc_stm32_data *data = dev->data;
978 	const struct adc_stm32_cfg *config =
979 		(const struct adc_stm32_cfg *)dev->config;
980 	ADC_TypeDef *adc = config->base;
981 
982 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
983 	if (LL_ADC_IsActiveFlag_EOS(adc) == 1) {
984 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
985 	if (LL_ADC_IsActiveFlag_EOCS(adc) == 1) {
986 #else
987 	if (LL_ADC_IsActiveFlag_EOC(adc) == 1) {
988 #endif
989 		*data->buffer++ = LL_ADC_REG_ReadConversionData32(adc);
990 		/* ISR is triggered after each conversion, and at the end-of-sequence. */
991 		if (++data->samples_count == data->channel_count) {
992 			data->samples_count = 0;
993 			adc_context_on_sampling_done(&data->ctx, dev);
994 		}
995 	}
996 
997 	LOG_DBG("%s ISR triggered.", dev->name);
998 }
999 #endif /* !CONFIG_ADC_STM32_DMA */
1000 
1001 static void adc_context_on_complete(struct adc_context *ctx, int status)
1002 {
1003 	struct adc_stm32_data *data =
1004 		CONTAINER_OF(ctx, struct adc_stm32_data, ctx);
1005 	const struct adc_stm32_cfg *config = data->dev->config;
1006 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
1007 
1008 	ARG_UNUSED(status);
1009 
1010 	adc_stm32_disable(adc);
1011 
1012 	/* Reset acquisition time used for the sequence */
1013 	data->acq_time_index = -1;
1014 
1015 	/* Reset internal channels */
1016 	LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(adc),
1017 				       LL_ADC_PATH_INTERNAL_NONE);
1018 
1019 #if defined(CONFIG_SOC_SERIES_STM32H7X) || defined(CONFIG_SOC_SERIES_STM32U5X)
1020 	/* Reset channel preselection register */
1021 	LL_ADC_SetChannelPreselection(adc, 0);
1022 #endif /* CONFIG_SOC_SERIES_STM32H7X || CONFIG_SOC_SERIES_STM32U5X */
1023 }
1024 
1025 static int adc_stm32_read(const struct device *dev,
1026 			  const struct adc_sequence *sequence)
1027 {
1028 	struct adc_stm32_data *data = dev->data;
1029 	int error;
1030 
1031 	adc_context_lock(&data->ctx, false, NULL);
1032 	error = start_read(dev, sequence);
1033 	adc_context_release(&data->ctx, error);
1034 
1035 	return error;
1036 }
1037 
1038 #ifdef CONFIG_ADC_ASYNC
1039 static int adc_stm32_read_async(const struct device *dev,
1040 				 const struct adc_sequence *sequence,
1041 				 struct k_poll_signal *async)
1042 {
1043 	struct adc_stm32_data *data = dev->data;
1044 	int error;
1045 
1046 	adc_context_lock(&data->ctx, true, async);
1047 	error = start_read(dev, sequence);
1048 	adc_context_release(&data->ctx, error);
1049 
1050 	return error;
1051 }
1052 #endif
1053 
1054 static int adc_stm32_check_acq_time(const struct device *dev, uint16_t acq_time)
1055 {
1056 	const struct adc_stm32_cfg *config =
1057 		(const struct adc_stm32_cfg *)dev->config;
1058 
1059 	if (acq_time == ADC_ACQ_TIME_DEFAULT) {
1060 		return 0;
1061 	}
1062 
1063 	if (acq_time == ADC_ACQ_TIME_MAX) {
1064 		return STM32_NB_SAMPLING_TIME - 1;
1065 	}
1066 
1067 	for (int i = 0; i < STM32_NB_SAMPLING_TIME; i++) {
1068 		if (acq_time == ADC_ACQ_TIME(ADC_ACQ_TIME_TICKS,
1069 					     config->sampling_time_table[i])) {
1070 			return i;
1071 		}
1072 	}
1073 
1074 	LOG_ERR("Conversion time not supported.");
1075 	return -EINVAL;
1076 }
1077 
1078 static int adc_stm32_setup_speed(const struct device *dev, uint8_t id,
1079 				  uint8_t acq_time_index)
1080 {
1081 	const struct adc_stm32_cfg *config =
1082 		(const struct adc_stm32_cfg *)dev->config;
1083 	ADC_TypeDef *adc = config->base;
1084 
1085 	/*
1086 	 * For all series we use the fact that the macros LL_ADC_SAMPLINGTIME_*
1087 	 * that should be passed to the set functions are all coded on 3 bits
1088 	 * with 0 shift (ie 0 to 7). So acq_time_index is equivalent to the
1089 	 * macro we would use for the desired sampling time.
1090 	 */
1091 	switch (config->num_sampling_time_common_channels) {
1092 	case 0:
1093 #if ANY_NUM_COMMON_SAMPLING_TIME_CHANNELS_IS(0)
1094 		LL_ADC_SetChannelSamplingTime(adc,
1095 			__LL_ADC_DECIMAL_NB_TO_CHANNEL(id),
1096 			acq_time_index);
1097 #endif
1098 		break;
1099 	case 1:
1100 #if ANY_NUM_COMMON_SAMPLING_TIME_CHANNELS_IS(1)
1101 		LL_ADC_SetSamplingTimeCommonChannels(adc,
1102 			acq_time_index);
1103 #endif
1104 		break;
1105 	case 2:
1106 #if ANY_NUM_COMMON_SAMPLING_TIME_CHANNELS_IS(2)
1107 		LL_ADC_SetChannelSamplingTime(adc,
1108 			__LL_ADC_DECIMAL_NB_TO_CHANNEL(id),
1109 			LL_ADC_SAMPLINGTIME_COMMON_1);
1110 		LL_ADC_SetSamplingTimeCommonChannels(adc,
1111 			LL_ADC_SAMPLINGTIME_COMMON_1,
1112 			acq_time_index);
1113 #endif
1114 		break;
1115 	default:
1116 		LOG_ERR("Number of common sampling time channels not supported");
1117 		return -EINVAL;
1118 	}
1119 	return 0;
1120 }
1121 
1122 static int adc_stm32_channel_setup(const struct device *dev,
1123 				   const struct adc_channel_cfg *channel_cfg)
1124 {
1125 	const struct adc_stm32_cfg *config =
1126 		(const struct adc_stm32_cfg *)dev->config;
1127 
1128 	struct adc_stm32_data *data = dev->data;
1129 	int acq_time_index;
1130 
1131 	acq_time_index = adc_stm32_check_acq_time(dev,
1132 				channel_cfg->acquisition_time);
1133 	if (acq_time_index < 0) {
1134 		return acq_time_index;
1135 	}
1136 	if (config->num_sampling_time_common_channels) {
1137 		if (data->acq_time_index == -1) {
1138 			data->acq_time_index = acq_time_index;
1139 		} else {
1140 			/*
1141 			 * All families that use common channel must have
1142 			 * identical acquisition time.
1143 			 */
1144 			if (acq_time_index != data->acq_time_index) {
1145 				LOG_ERR("Multiple sampling times not supported");
1146 				return -EINVAL;
1147 			}
1148 		}
1149 	}
1150 
1151 	if (channel_cfg->differential) {
1152 		LOG_ERR("Differential channels are not supported");
1153 		return -EINVAL;
1154 	}
1155 
1156 	if (channel_cfg->gain != ADC_GAIN_1) {
1157 		LOG_ERR("Invalid channel gain");
1158 		return -EINVAL;
1159 	}
1160 
1161 	if (channel_cfg->reference != ADC_REF_INTERNAL) {
1162 		LOG_ERR("Invalid channel reference");
1163 		return -EINVAL;
1164 	}
1165 
1166 	if (adc_stm32_setup_speed(dev, channel_cfg->channel_id,
1167 				  acq_time_index) != 0) {
1168 		LOG_ERR("Invalid sampling time");
1169 		return -EINVAL;
1170 	}
1171 
1172 	LOG_DBG("Channel setup succeeded!");
1173 
1174 	return 0;
1175 }
1176 
1177 /* This symbol takes the value 1 if one of the device instances */
1178 /* is configured in dts with a domain clock */
1179 #if STM32_DT_INST_DEV_DOMAIN_CLOCK_SUPPORT
1180 #define STM32_ADC_DOMAIN_CLOCK_SUPPORT 1
1181 #else
1182 #define STM32_ADC_DOMAIN_CLOCK_SUPPORT 0
1183 #endif
1184 
1185 static int adc_stm32_set_clock(const struct device *dev)
1186 {
1187 	const struct adc_stm32_cfg *config = dev->config;
1188 	const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
1189 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
1190 
1191 	ARG_UNUSED(adc); /* Necessary to avoid warnings on some series */
1192 
1193 	if (clock_control_on(clk,
1194 		(clock_control_subsys_t) &config->pclken[0]) != 0) {
1195 		return -EIO;
1196 	}
1197 
1198 	if (IS_ENABLED(STM32_ADC_DOMAIN_CLOCK_SUPPORT) && (config->pclk_len > 1)) {
1199 		/* Enable ADC clock source */
1200 		if (clock_control_configure(clk,
1201 					    (clock_control_subsys_t) &config->pclken[1],
1202 					    NULL) != 0) {
1203 			return -EIO;
1204 		}
1205 	}
1206 
1207 #if defined(CONFIG_SOC_SERIES_STM32F0X)
1208 	LL_ADC_SetClock(adc, config->clk_prescaler);
1209 #elif defined(CONFIG_SOC_SERIES_STM32C0X) || \
1210 	defined(CONFIG_SOC_SERIES_STM32G0X) || \
1211 	defined(CONFIG_SOC_SERIES_STM32L0X) || \
1212 	(defined(CONFIG_SOC_SERIES_STM32WBX) && defined(ADC_SUPPORT_2_5_MSPS)) || \
1213 	defined(CONFIG_SOC_SERIES_STM32WLX)
1214 	if ((config->clk_prescaler == LL_ADC_CLOCK_SYNC_PCLK_DIV1) ||
1215 		(config->clk_prescaler == LL_ADC_CLOCK_SYNC_PCLK_DIV2) ||
1216 		(config->clk_prescaler == LL_ADC_CLOCK_SYNC_PCLK_DIV4)) {
1217 		LL_ADC_SetClock(adc, config->clk_prescaler);
1218 	} else {
1219 		LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(adc),
1220 				      config->clk_prescaler);
1221 		LL_ADC_SetClock(adc, LL_ADC_CLOCK_ASYNC);
1222 	}
1223 #elif !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
1224 	LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(adc),
1225 			      config->clk_prescaler);
1226 #endif
1227 
1228 	return 0;
1229 }
1230 
1231 static int adc_stm32_init(const struct device *dev)
1232 {
1233 	struct adc_stm32_data *data = dev->data;
1234 	const struct adc_stm32_cfg *config = dev->config;
1235 	const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
1236 	ADC_TypeDef *adc = (ADC_TypeDef *)config->base;
1237 	int err;
1238 
1239 	LOG_DBG("Initializing %s", dev->name);
1240 
1241 	if (!device_is_ready(clk)) {
1242 		LOG_ERR("clock control device not ready");
1243 		return -ENODEV;
1244 	}
1245 
1246 	data->dev = dev;
1247 
1248 	/*
1249 	 * For series that use common channels for sampling time, all
1250 	 * conversion time for all channels on one ADC instance has to
1251 	 * be the same.
1252 	 * For series that use two common channels, currently only one
1253 	 * of the two available common channel conversion times is used.
1254 	 * This additional variable is for checking if the conversion time
1255 	 * selection of all channels on one ADC instance is the same.
1256 	 */
1257 	data->acq_time_index = -1;
1258 
1259 	adc_stm32_set_clock(dev);
1260 
1261 	/* Configure dt provided device signals when available */
1262 	err = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
1263 	if (err < 0) {
1264 		LOG_ERR("ADC pinctrl setup failed (%d)", err);
1265 		return err;
1266 	}
1267 #if defined(CONFIG_SOC_SERIES_STM32U5X)
1268 	/* Enable the independent analog supply */
1269 	LL_PWR_EnableVDDA();
1270 #endif /* CONFIG_SOC_SERIES_STM32U5X */
1271 
1272 #ifdef CONFIG_ADC_STM32_DMA
1273 	if ((data->dma.dma_dev != NULL) &&
1274 	    !device_is_ready(data->dma.dma_dev)) {
1275 		LOG_ERR("%s device not ready", data->dma.dma_dev->name);
1276 		return -ENODEV;
1277 	}
1278 #endif
1279 
1280 #if defined(CONFIG_SOC_SERIES_STM32L4X) || \
1281 	defined(CONFIG_SOC_SERIES_STM32L5X) || \
1282 	defined(CONFIG_SOC_SERIES_STM32WBX) || \
1283 	defined(CONFIG_SOC_SERIES_STM32G4X) || \
1284 	defined(CONFIG_SOC_SERIES_STM32H5X) || \
1285 	defined(CONFIG_SOC_SERIES_STM32H7X) || \
1286 	defined(CONFIG_SOC_SERIES_STM32U5X)
1287 	/*
1288 	 * L4, WB, G4, H5, H7 and U5 series STM32 needs to be awaken from deep sleep
1289 	 * mode, and restore its calibration parameters if there are some
1290 	 * previously stored calibration parameters.
1291 	 */
1292 
1293 	LL_ADC_DisableDeepPowerDown(adc);
1294 #elif defined(CONFIG_SOC_SERIES_STM32WLX)
1295 	/* The ADC clock must be disabled by clock gating during CPU1 sleep/stop */
1296 	LL_APB2_GRP1_DisableClockSleep(LL_APB2_GRP1_PERIPH_ADC);
1297 #endif
1298 	/*
1299 	 * Many ADC modules need some time to be stabilized before performing
1300 	 * any enable or calibration actions.
1301 	 */
1302 #if !defined(CONFIG_SOC_SERIES_STM32F0X) && \
1303 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) && \
1304 	!DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
1305 	LL_ADC_EnableInternalRegulator(adc);
1306 	k_busy_wait(LL_ADC_DELAY_INTERNAL_REGUL_STAB_US);
1307 #endif
1308 
1309 #if defined(HAS_CALIBRATION) && !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
1310 	adc_stm32_disable(adc);
1311 	adc_stm32_calib(dev);
1312 	adc_stm32_calib_delay(dev);
1313 #endif /* HAS_CALIBRATION && !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) */
1314 
1315 	err = adc_stm32_enable(adc);
1316 	if (err < 0) {
1317 		return err;
1318 	}
1319 
1320 	config->irq_cfg_func();
1321 
1322 #if defined(HAS_CALIBRATION) && DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
1323 	adc_stm32_calib_delay(dev);
1324 	adc_stm32_calib(dev);
1325 	LL_ADC_REG_SetTriggerSource(adc, LL_ADC_REG_TRIG_SOFTWARE);
1326 #endif /* HAS_CALIBRATION && DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc) */
1327 
1328 #ifdef CONFIG_SOC_SERIES_STM32H7X
1329 	/*
1330 	 * To ensure linearity the factory calibration values
1331 	 * should be loaded on initialization.
1332 	 */
1333 	uint32_t channel_offset = 0U;
1334 	uint32_t linear_calib_buffer = 0U;
1335 
1336 	if (adc == ADC1) {
1337 		channel_offset = 0UL;
1338 	} else if (adc == ADC2) {
1339 		channel_offset = 8UL;
1340 	} else   /*Case ADC3*/ {
1341 		channel_offset = 16UL;
1342 	}
1343 	/* Read factory calibration factors */
1344 	for (uint32_t count = 0UL; count < ADC_LINEAR_CALIB_REG_COUNT; count++) {
1345 		linear_calib_buffer = *(uint32_t *)(
1346 			ADC_LINEAR_CALIB_REG_1_ADDR + channel_offset + count
1347 		);
1348 		LL_ADC_SetCalibrationLinearFactor(
1349 			adc, LL_ADC_CALIB_LINEARITY_WORD1 << count,
1350 			linear_calib_buffer
1351 		);
1352 	}
1353 #endif
1354 	adc_context_unlock_unconditionally(&data->ctx);
1355 
1356 	return 0;
1357 }
1358 
1359 static const struct adc_driver_api api_stm32_driver_api = {
1360 	.channel_setup = adc_stm32_channel_setup,
1361 	.read = adc_stm32_read,
1362 #ifdef CONFIG_ADC_ASYNC
1363 	.read_async = adc_stm32_read_async,
1364 #endif
1365 	.ref_internal = STM32_ADC_VREF_MV, /* VREF is usually connected to VDD */
1366 };
1367 
1368 #if defined(CONFIG_SOC_SERIES_STM32F0X)
1369 /* LL_ADC_CLOCK_ASYNC_DIV1 doesn't exist in F0 LL. Define it here. */
1370 #define LL_ADC_CLOCK_ASYNC_DIV1 LL_ADC_CLOCK_ASYNC
1371 #endif
1372 
1373 /* st_prescaler property requires 2 elements : clock ASYNC/SYNC and DIV */
1374 #define ADC_STM32_CLOCK(x)	DT_INST_PROP(x, st_adc_clock_source)
1375 #define ADC_STM32_DIV(x)	DT_INST_PROP(x, st_adc_prescaler)
1376 
1377 /* Macro to set the prefix depending on the 1st element: check if it is SYNC or ASYNC */
1378 #define ADC_STM32_CLOCK_PREFIX(x)			\
1379 	COND_CODE_1(IS_EQ(ADC_STM32_CLOCK(x), SYNC),	\
1380 		(LL_ADC_CLOCK_SYNC_PCLK_DIV),		\
1381 		(LL_ADC_CLOCK_ASYNC_DIV))
1382 
1383 /* Concat prefix (1st element) and DIV value (2nd element) of st,adc-prescaler */
1384 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32f1_adc)
1385 #define ADC_STM32_DT_PRESC(x)	0
1386 #else
1387 #define ADC_STM32_DT_PRESC(x)	\
1388 	_CONCAT(ADC_STM32_CLOCK_PREFIX(x), ADC_STM32_DIV(x))
1389 #endif
1390 
1391 #ifdef CONFIG_ADC_STM32_SHARED_IRQS
1392 
1393 bool adc_stm32_is_irq_active(ADC_TypeDef *adc)
1394 {
1395 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc)
1396 	return LL_ADC_IsActiveFlag_EOCS(adc) ||
1397 #else
1398 	return LL_ADC_IsActiveFlag_EOC(adc) ||
1399 #endif /* DT_HAS_COMPAT_STATUS_OKAY(st_stm32f4_adc) */
1400 	       LL_ADC_IsActiveFlag_OVR(adc) ||
1401 	       LL_ADC_IsActiveFlag_JEOS(adc) ||
1402 	       LL_ADC_IsActiveFlag_AWD1(adc);
1403 }
1404 
1405 #define HANDLE_IRQS(index)							\
1406 	static const struct device *const dev_##index =				\
1407 		DEVICE_DT_INST_GET(index);					\
1408 	const struct adc_stm32_cfg *cfg_##index = dev_##index->config;		\
1409 	ADC_TypeDef *adc_##index = (ADC_TypeDef *)(cfg_##index->base);		\
1410 										\
1411 	if (adc_stm32_is_irq_active(adc_##index)) {				\
1412 		adc_stm32_isr(dev_##index);					\
1413 	}
1414 
1415 static void adc_stm32_shared_irq_handler(void)
1416 {
1417 	DT_INST_FOREACH_STATUS_OKAY(HANDLE_IRQS);
1418 }
1419 
1420 static void adc_stm32_irq_init(void)
1421 {
1422 	if (init_irq) {
1423 		init_irq = false;
1424 		IRQ_CONNECT(DT_INST_IRQN(0),
1425 			DT_INST_IRQ(0, priority),
1426 			adc_stm32_shared_irq_handler, NULL, 0);
1427 		irq_enable(DT_INST_IRQN(0));
1428 	}
1429 }
1430 
1431 #define ADC_STM32_IRQ_CONFIG(index)
1432 #define ADC_STM32_IRQ_FUNC(index)					\
1433 	.irq_cfg_func = adc_stm32_irq_init,
1434 #define ADC_DMA_CHANNEL(id, dir, DIR, src, dest)
1435 
1436 #elif defined(CONFIG_ADC_STM32_DMA) /* !CONFIG_ADC_STM32_SHARED_IRQS */
1437 
1438 #define ADC_DMA_CHANNEL_INIT(index, name, dir_cap, src_dev, dest_dev)			\
1439 	.dma = {									\
1440 		.dma_dev = DEVICE_DT_GET(STM32_DMA_CTLR(index, name)),			\
1441 		.channel = DT_INST_DMAS_CELL_BY_NAME(index, name, channel),		\
1442 		.dma_cfg = {								\
1443 			.dma_slot = STM32_DMA_SLOT(index, name, slot),			\
1444 			.channel_direction = STM32_DMA_CONFIG_DIRECTION(		\
1445 				STM32_DMA_CHANNEL_CONFIG(index, name)),			\
1446 			.source_data_size = STM32_DMA_CONFIG_##src_dev##_DATA_SIZE(	\
1447 				STM32_DMA_CHANNEL_CONFIG(index, name)),			\
1448 			.dest_data_size = STM32_DMA_CONFIG_##dest_dev##_DATA_SIZE(	\
1449 				STM32_DMA_CHANNEL_CONFIG(index, name)),			\
1450 			.source_burst_length = 1,       /* SINGLE transfer */		\
1451 			.dest_burst_length = 1,         /* SINGLE transfer */		\
1452 			.channel_priority = STM32_DMA_CONFIG_PRIORITY(			\
1453 				STM32_DMA_CHANNEL_CONFIG(index, name)),			\
1454 			.dma_callback = dma_callback,					\
1455 			.block_count = 2,						\
1456 		},									\
1457 		.src_addr_increment = STM32_DMA_CONFIG_##src_dev##_ADDR_INC(		\
1458 			STM32_DMA_CHANNEL_CONFIG(index, name)),				\
1459 		.dst_addr_increment = STM32_DMA_CONFIG_##dest_dev##_ADDR_INC(		\
1460 			STM32_DMA_CHANNEL_CONFIG(index, name)),				\
1461 	}
1462 
1463 #define ADC_DMA_CHANNEL(id, dir, DIR, src, dest)					\
1464 	COND_CODE_1(DT_INST_DMAS_HAS_NAME(id, dir),					\
1465 		    (ADC_DMA_CHANNEL_INIT(id, dir, DIR, src, dest)),			\
1466 		    (EMPTY))
1467 
1468 #define ADC_STM32_IRQ_CONFIG(index)					\
1469 static void adc_stm32_cfg_func_##index(void){ EMPTY }
1470 #define ADC_STM32_IRQ_FUNC(index)					\
1471 	.irq_cfg_func = adc_stm32_cfg_func_##index,
1472 
1473 #else /* CONFIG_ADC_STM32_DMA */
1474 
1475 #define ADC_STM32_IRQ_CONFIG(index)					\
1476 static void adc_stm32_cfg_func_##index(void)				\
1477 {									\
1478 	IRQ_CONNECT(DT_INST_IRQN(index),				\
1479 		    DT_INST_IRQ(index, priority),			\
1480 		    adc_stm32_isr, DEVICE_DT_INST_GET(index), 0);	\
1481 	irq_enable(DT_INST_IRQN(index));				\
1482 }
1483 #define ADC_STM32_IRQ_FUNC(index)					\
1484 	.irq_cfg_func = adc_stm32_cfg_func_##index,
1485 #define ADC_DMA_CHANNEL(id, dir, DIR, src, dest)
1486 
1487 #endif /* CONFIG_ADC_STM32_DMA && CONFIG_ADC_STM32_SHARED_IRQS */
1488 
1489 
1490 #define ADC_STM32_INIT(index)						\
1491 									\
1492 PINCTRL_DT_INST_DEFINE(index);						\
1493 									\
1494 ADC_STM32_IRQ_CONFIG(index)						\
1495 									\
1496 static const struct stm32_pclken pclken_##index[] =			\
1497 				 STM32_DT_INST_CLOCKS(index);		\
1498 									\
1499 static const struct adc_stm32_cfg adc_stm32_cfg_##index = {		\
1500 	.base = (ADC_TypeDef *)DT_INST_REG_ADDR(index),			\
1501 	ADC_STM32_IRQ_FUNC(index)					\
1502 	.pclken = pclken_##index,					\
1503 	.pclk_len = DT_INST_NUM_CLOCKS(index),				\
1504 	.clk_prescaler = ADC_STM32_DT_PRESC(index),			\
1505 	.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(index),			\
1506 	.sequencer_type = DT_INST_PROP(index, st_adc_sequencer),	\
1507 	.sampling_time_table = DT_INST_PROP(index, sampling_times),	\
1508 	.num_sampling_time_common_channels =				\
1509 		DT_INST_PROP_OR(index, num_sampling_time_common_channels, 0),\
1510 	.res_table_size = DT_INST_PROP_LEN(index, resolutions),		\
1511 	.res_table = DT_INST_PROP(index, resolutions),			\
1512 };									\
1513 									\
1514 static struct adc_stm32_data adc_stm32_data_##index = {			\
1515 	ADC_CONTEXT_INIT_TIMER(adc_stm32_data_##index, ctx),		\
1516 	ADC_CONTEXT_INIT_LOCK(adc_stm32_data_##index, ctx),		\
1517 	ADC_CONTEXT_INIT_SYNC(adc_stm32_data_##index, ctx),		\
1518 	ADC_DMA_CHANNEL(index, dmamux, NULL, PERIPHERAL, MEMORY)	\
1519 };									\
1520 									\
1521 DEVICE_DT_INST_DEFINE(index,						\
1522 		    &adc_stm32_init, NULL,				\
1523 		    &adc_stm32_data_##index, &adc_stm32_cfg_##index,	\
1524 		    POST_KERNEL, CONFIG_ADC_INIT_PRIORITY,		\
1525 		    &api_stm32_driver_api);
1526 
1527 DT_INST_FOREACH_STATUS_OKAY(ADC_STM32_INIT)
1528