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