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