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