1 /*
2  * Copyright (c) 2016 Open-RnD Sp. z o.o.
3  * Copyright (c) 2016 Linaro Limited.
4  * Copyright (c) 2024 STMicroelectronics
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #define DT_DRV_COMPAT st_stm32_uart
10 
11 /**
12  * @brief Driver for UART port on STM32 family processor.
13  * @note  LPUART and U(S)ART have the same base and
14  *        majority of operations are performed the same way.
15  *        Please validate for newly added series.
16  */
17 
18 #include <zephyr/kernel.h>
19 #include <zephyr/arch/cpu.h>
20 #include <zephyr/sys/__assert.h>
21 #include <soc.h>
22 #include <zephyr/init.h>
23 #include <zephyr/drivers/interrupt_controller/exti_stm32.h>
24 #include <zephyr/drivers/clock_control.h>
25 #include <zephyr/pm/policy.h>
26 #include <zephyr/pm/device.h>
27 
28 #ifdef CONFIG_UART_ASYNC_API
29 #include <zephyr/drivers/dma/dma_stm32.h>
30 #include <zephyr/drivers/dma.h>
31 #endif
32 
33 #include <zephyr/linker/sections.h>
34 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
35 #include "uart_stm32.h"
36 
37 #include <stm32_ll_usart.h>
38 #include <stm32_ll_lpuart.h>
39 #if defined(CONFIG_PM) && defined(IS_UART_WAKEUP_FROMSTOP_INSTANCE)
40 #include <stm32_ll_exti.h>
41 #endif /* CONFIG_PM */
42 
43 #ifdef CONFIG_DCACHE
44 #include <zephyr/linker/linker-defs.h>
45 #include <zephyr/mem_mgmt/mem_attr.h>
46 #include <zephyr/dt-bindings/memory-attr/memory-attr-arm.h>
47 #endif /* CONFIG_DCACHE */
48 
49 #include <zephyr/logging/log.h>
50 #include <zephyr/irq.h>
51 LOG_MODULE_REGISTER(uart_stm32, CONFIG_UART_LOG_LEVEL);
52 
53 /* This symbol takes the value 1 if one of the device instances */
54 /* is configured in dts with a domain clock */
55 #if STM32_DT_INST_DEV_DOMAIN_CLOCK_SUPPORT
56 #define STM32_UART_DOMAIN_CLOCK_SUPPORT 1
57 #else
58 #define STM32_UART_DOMAIN_CLOCK_SUPPORT 0
59 #endif
60 
61 #define HAS_LPUART DT_HAS_COMPAT_STATUS_OKAY(st_stm32_lpuart)
62 
63 /* Available everywhere except l1, f1, f2, f4. */
64 #ifdef USART_CR3_DEM
65 #define HAS_DRIVER_ENABLE 1
66 #else
67 #define HAS_DRIVER_ENABLE 0
68 #endif
69 
70 #if HAS_LPUART
71 #ifdef USART_PRESC_PRESCALER
lpuartdiv_calc(const uint64_t clock_rate,const uint16_t presc_idx,const uint32_t baud_rate)72 uint32_t lpuartdiv_calc(const uint64_t clock_rate, const uint16_t presc_idx,
73 			const uint32_t baud_rate)
74 {
75 	uint64_t lpuartdiv;
76 
77 	lpuartdiv = clock_rate / LPUART_PRESCALER_TAB[presc_idx];
78 	lpuartdiv *= LPUART_LPUARTDIV_FREQ_MUL;
79 	lpuartdiv += baud_rate / 2;
80 	lpuartdiv /= baud_rate;
81 
82 	return (uint32_t)lpuartdiv;
83 }
84 #else
lpuartdiv_calc(const uint64_t clock_rate,const uint32_t baud_rate)85 uint32_t lpuartdiv_calc(const uint64_t clock_rate, const uint32_t baud_rate)
86 {
87 	uint64_t lpuartdiv;
88 
89 	lpuartdiv = clock_rate * LPUART_LPUARTDIV_FREQ_MUL;
90 	lpuartdiv += baud_rate / 2;
91 	lpuartdiv /= baud_rate;
92 
93 	return (uint32_t)lpuartdiv;
94 }
95 #endif /* USART_PRESC_PRESCALER */
96 #endif /* HAS_LPUART */
97 
98 #ifdef CONFIG_PM
uart_stm32_pm_policy_state_lock_get(const struct device * dev)99 static void uart_stm32_pm_policy_state_lock_get(const struct device *dev)
100 {
101 	struct uart_stm32_data *data = dev->data;
102 
103 	if (!data->pm_policy_state_on) {
104 		data->pm_policy_state_on = true;
105 		pm_policy_state_lock_get(PM_STATE_SUSPEND_TO_IDLE, PM_ALL_SUBSTATES);
106 		if (IS_ENABLED(CONFIG_PM_S2RAM)) {
107 			pm_policy_state_lock_get(PM_STATE_SUSPEND_TO_RAM, PM_ALL_SUBSTATES);
108 		}
109 	}
110 }
111 
uart_stm32_pm_policy_state_lock_put(const struct device * dev)112 static void uart_stm32_pm_policy_state_lock_put(const struct device *dev)
113 {
114 	struct uart_stm32_data *data = dev->data;
115 
116 	if (data->pm_policy_state_on) {
117 		data->pm_policy_state_on = false;
118 		pm_policy_state_lock_put(PM_STATE_SUSPEND_TO_IDLE, PM_ALL_SUBSTATES);
119 		if (IS_ENABLED(CONFIG_PM_S2RAM)) {
120 			pm_policy_state_lock_put(PM_STATE_SUSPEND_TO_RAM, PM_ALL_SUBSTATES);
121 		}
122 	}
123 }
124 #endif /* CONFIG_PM */
125 
uart_stm32_set_baudrate(const struct device * dev,uint32_t baud_rate)126 static inline void uart_stm32_set_baudrate(const struct device *dev, uint32_t baud_rate)
127 {
128 	const struct uart_stm32_config *config = dev->config;
129 	USART_TypeDef *usart = config->usart;
130 	struct uart_stm32_data *data = dev->data;
131 
132 	uint32_t clock_rate;
133 
134 	/* Get clock rate */
135 	if (IS_ENABLED(STM32_UART_DOMAIN_CLOCK_SUPPORT) && (config->pclk_len > 1)) {
136 		if (clock_control_get_rate(data->clock,
137 					   (clock_control_subsys_t)&config->pclken[1],
138 					   &clock_rate) < 0) {
139 			LOG_ERR("Failed call clock_control_get_rate(pclken[1])");
140 			return;
141 		}
142 	} else {
143 		if (clock_control_get_rate(data->clock,
144 					   (clock_control_subsys_t)&config->pclken[0],
145 					   &clock_rate) < 0) {
146 			LOG_ERR("Failed call clock_control_get_rate(pclken[0])");
147 			return;
148 		}
149 	}
150 
151 #if HAS_LPUART
152 	if (IS_LPUART_INSTANCE(usart)) {
153 		uint32_t lpuartdiv;
154 #ifdef USART_PRESC_PRESCALER
155 		uint8_t presc_idx;
156 		uint32_t presc_val;
157 
158 		for (presc_idx = 0; presc_idx < ARRAY_SIZE(LPUART_PRESCALER_TAB); presc_idx++) {
159 			lpuartdiv = lpuartdiv_calc(clock_rate, presc_idx, baud_rate);
160 			if (lpuartdiv >= LPUART_BRR_MIN_VALUE && lpuartdiv <= LPUART_BRR_MASK) {
161 				break;
162 			}
163 		}
164 
165 		if (presc_idx == ARRAY_SIZE(LPUART_PRESCALER_TAB)) {
166 			LOG_ERR("Unable to set %s to %d", dev->name, baud_rate);
167 			return;
168 		}
169 
170 		presc_val = presc_idx << USART_PRESC_PRESCALER_Pos;
171 
172 		LL_LPUART_SetPrescaler(usart, presc_val);
173 #else
174 		lpuartdiv = lpuartdiv_calc(clock_rate, baud_rate);
175 		if (lpuartdiv < LPUART_BRR_MIN_VALUE || lpuartdiv > LPUART_BRR_MASK) {
176 			LOG_ERR("Unable to set %s to %d", dev->name, baud_rate);
177 			return;
178 		}
179 #endif /* USART_PRESC_PRESCALER */
180 		LL_LPUART_SetBaudRate(usart,
181 				      clock_rate,
182 #ifdef USART_PRESC_PRESCALER
183 				      presc_val,
184 #endif
185 				      baud_rate);
186 		/* Check BRR is greater than or equal to 0x300 */
187 		__ASSERT(LL_LPUART_ReadReg(usart, BRR) >= 0x300U,
188 			 "BaudRateReg >= 0x300");
189 
190 		/* Check BRR is lower than or equal to 0xFFFFF */
191 		__ASSERT(LL_LPUART_ReadReg(usart, BRR) < 0x000FFFFFU,
192 			 "BaudRateReg < 0xFFFF");
193 	} else {
194 #endif /* HAS_LPUART */
195 #ifdef USART_CR1_OVER8
196 		LL_USART_SetOverSampling(usart,
197 					 LL_USART_OVERSAMPLING_16);
198 #endif
199 		LL_USART_SetBaudRate(usart,
200 				     clock_rate,
201 #ifdef USART_PRESC_PRESCALER
202 				     LL_USART_PRESCALER_DIV1,
203 #endif
204 #ifdef USART_CR1_OVER8
205 				     LL_USART_OVERSAMPLING_16,
206 #endif
207 				     baud_rate);
208 		/* Check BRR is greater than or equal to 16d */
209 		__ASSERT(LL_USART_ReadReg(usart, BRR) >= 16,
210 			 "BaudRateReg >= 16");
211 
212 #if HAS_LPUART
213 	}
214 #endif /* HAS_LPUART */
215 }
216 
uart_stm32_set_parity(const struct device * dev,uint32_t parity)217 static inline void uart_stm32_set_parity(const struct device *dev,
218 					 uint32_t parity)
219 {
220 	const struct uart_stm32_config *config = dev->config;
221 
222 	LL_USART_SetParity(config->usart, parity);
223 }
224 
uart_stm32_get_parity(const struct device * dev)225 static inline uint32_t uart_stm32_get_parity(const struct device *dev)
226 {
227 	const struct uart_stm32_config *config = dev->config;
228 
229 	return LL_USART_GetParity(config->usart);
230 }
231 
uart_stm32_set_stopbits(const struct device * dev,uint32_t stopbits)232 static inline void uart_stm32_set_stopbits(const struct device *dev,
233 					   uint32_t stopbits)
234 {
235 	const struct uart_stm32_config *config = dev->config;
236 
237 	LL_USART_SetStopBitsLength(config->usart, stopbits);
238 }
239 
uart_stm32_get_stopbits(const struct device * dev)240 static inline uint32_t uart_stm32_get_stopbits(const struct device *dev)
241 {
242 	const struct uart_stm32_config *config = dev->config;
243 
244 	return LL_USART_GetStopBitsLength(config->usart);
245 }
246 
uart_stm32_set_databits(const struct device * dev,uint32_t databits)247 static inline void uart_stm32_set_databits(const struct device *dev,
248 					   uint32_t databits)
249 {
250 	const struct uart_stm32_config *config = dev->config;
251 
252 	LL_USART_SetDataWidth(config->usart, databits);
253 }
254 
uart_stm32_get_databits(const struct device * dev)255 static inline uint32_t uart_stm32_get_databits(const struct device *dev)
256 {
257 	const struct uart_stm32_config *config = dev->config;
258 
259 	return LL_USART_GetDataWidth(config->usart);
260 }
261 
uart_stm32_set_hwctrl(const struct device * dev,uint32_t hwctrl)262 static inline void uart_stm32_set_hwctrl(const struct device *dev,
263 					 uint32_t hwctrl)
264 {
265 	const struct uart_stm32_config *config = dev->config;
266 
267 	LL_USART_SetHWFlowCtrl(config->usart, hwctrl);
268 }
269 
uart_stm32_get_hwctrl(const struct device * dev)270 static inline uint32_t uart_stm32_get_hwctrl(const struct device *dev)
271 {
272 	const struct uart_stm32_config *config = dev->config;
273 
274 	return LL_USART_GetHWFlowCtrl(config->usart);
275 }
276 
277 #if HAS_DRIVER_ENABLE
uart_stm32_set_driver_enable(const struct device * dev,bool driver_enable)278 static inline void uart_stm32_set_driver_enable(const struct device *dev,
279 						bool driver_enable)
280 {
281 	const struct uart_stm32_config *config = dev->config;
282 
283 	if (driver_enable) {
284 		LL_USART_EnableDEMode(config->usart);
285 	} else {
286 		LL_USART_DisableDEMode(config->usart);
287 	}
288 }
289 
uart_stm32_get_driver_enable(const struct device * dev)290 static inline bool uart_stm32_get_driver_enable(const struct device *dev)
291 {
292 	const struct uart_stm32_config *config = dev->config;
293 
294 	return LL_USART_IsEnabledDEMode(config->usart);
295 }
296 #endif
297 
uart_stm32_cfg2ll_parity(enum uart_config_parity parity)298 static inline uint32_t uart_stm32_cfg2ll_parity(enum uart_config_parity parity)
299 {
300 	switch (parity) {
301 	case UART_CFG_PARITY_ODD:
302 		return LL_USART_PARITY_ODD;
303 	case UART_CFG_PARITY_EVEN:
304 		return LL_USART_PARITY_EVEN;
305 	case UART_CFG_PARITY_NONE:
306 	default:
307 		return LL_USART_PARITY_NONE;
308 	}
309 }
310 
uart_stm32_ll2cfg_parity(uint32_t parity)311 static inline enum uart_config_parity uart_stm32_ll2cfg_parity(uint32_t parity)
312 {
313 	switch (parity) {
314 	case LL_USART_PARITY_ODD:
315 		return UART_CFG_PARITY_ODD;
316 	case LL_USART_PARITY_EVEN:
317 		return UART_CFG_PARITY_EVEN;
318 	case LL_USART_PARITY_NONE:
319 	default:
320 		return UART_CFG_PARITY_NONE;
321 	}
322 }
323 
uart_stm32_cfg2ll_stopbits(const struct uart_stm32_config * config,enum uart_config_stop_bits sb)324 static inline uint32_t uart_stm32_cfg2ll_stopbits(const struct uart_stm32_config *config,
325 							enum uart_config_stop_bits sb)
326 {
327 	switch (sb) {
328 /* Some MCU's don't support 0.5 stop bits */
329 #ifdef LL_USART_STOPBITS_0_5
330 	case UART_CFG_STOP_BITS_0_5:
331 #if HAS_LPUART
332 		if (IS_LPUART_INSTANCE(config->usart)) {
333 			/* return the default */
334 			return LL_USART_STOPBITS_1;
335 		}
336 #endif /* HAS_LPUART */
337 		return LL_USART_STOPBITS_0_5;
338 #endif	/* LL_USART_STOPBITS_0_5 */
339 	case UART_CFG_STOP_BITS_1:
340 		return LL_USART_STOPBITS_1;
341 /* Some MCU's don't support 1.5 stop bits */
342 #ifdef LL_USART_STOPBITS_1_5
343 	case UART_CFG_STOP_BITS_1_5:
344 #if HAS_LPUART
345 		if (IS_LPUART_INSTANCE(config->usart)) {
346 			/* return the default */
347 			return LL_USART_STOPBITS_2;
348 		}
349 #endif
350 		return LL_USART_STOPBITS_1_5;
351 #endif	/* LL_USART_STOPBITS_1_5 */
352 	case UART_CFG_STOP_BITS_2:
353 	default:
354 		return LL_USART_STOPBITS_2;
355 	}
356 }
357 
uart_stm32_ll2cfg_stopbits(uint32_t sb)358 static inline enum uart_config_stop_bits uart_stm32_ll2cfg_stopbits(uint32_t sb)
359 {
360 	switch (sb) {
361 /* Some MCU's don't support 0.5 stop bits */
362 #ifdef LL_USART_STOPBITS_0_5
363 	case LL_USART_STOPBITS_0_5:
364 		return UART_CFG_STOP_BITS_0_5;
365 #endif	/* LL_USART_STOPBITS_0_5 */
366 	case LL_USART_STOPBITS_1:
367 		return UART_CFG_STOP_BITS_1;
368 /* Some MCU's don't support 1.5 stop bits */
369 #ifdef LL_USART_STOPBITS_1_5
370 	case LL_USART_STOPBITS_1_5:
371 		return UART_CFG_STOP_BITS_1_5;
372 #endif	/* LL_USART_STOPBITS_1_5 */
373 	case LL_USART_STOPBITS_2:
374 	default:
375 		return UART_CFG_STOP_BITS_2;
376 	}
377 }
378 
uart_stm32_cfg2ll_databits(enum uart_config_data_bits db,enum uart_config_parity p)379 static inline uint32_t uart_stm32_cfg2ll_databits(enum uart_config_data_bits db,
380 						  enum uart_config_parity p)
381 {
382 	switch (db) {
383 /* Some MCU's don't support 7B or 9B datawidth */
384 #ifdef LL_USART_DATAWIDTH_7B
385 	case UART_CFG_DATA_BITS_7:
386 		if (p == UART_CFG_PARITY_NONE) {
387 			return LL_USART_DATAWIDTH_7B;
388 		} else {
389 			return LL_USART_DATAWIDTH_8B;
390 		}
391 #endif	/* LL_USART_DATAWIDTH_7B */
392 #ifdef LL_USART_DATAWIDTH_9B
393 	case UART_CFG_DATA_BITS_9:
394 		return LL_USART_DATAWIDTH_9B;
395 #endif	/* LL_USART_DATAWIDTH_9B */
396 	case UART_CFG_DATA_BITS_8:
397 	default:
398 		if (p == UART_CFG_PARITY_NONE) {
399 			return LL_USART_DATAWIDTH_8B;
400 #ifdef LL_USART_DATAWIDTH_9B
401 		} else {
402 			return LL_USART_DATAWIDTH_9B;
403 #endif
404 		}
405 		return LL_USART_DATAWIDTH_8B;
406 	}
407 }
408 
uart_stm32_ll2cfg_databits(uint32_t db,uint32_t p)409 static inline enum uart_config_data_bits uart_stm32_ll2cfg_databits(uint32_t db,
410 								    uint32_t p)
411 {
412 	switch (db) {
413 /* Some MCU's don't support 7B or 9B datawidth */
414 #ifdef LL_USART_DATAWIDTH_7B
415 	case LL_USART_DATAWIDTH_7B:
416 		if (p == LL_USART_PARITY_NONE) {
417 			return UART_CFG_DATA_BITS_7;
418 		} else {
419 			return UART_CFG_DATA_BITS_6;
420 		}
421 #endif	/* LL_USART_DATAWIDTH_7B */
422 #ifdef LL_USART_DATAWIDTH_9B
423 	case LL_USART_DATAWIDTH_9B:
424 		if (p == LL_USART_PARITY_NONE) {
425 			return UART_CFG_DATA_BITS_9;
426 		} else {
427 			return UART_CFG_DATA_BITS_8;
428 		}
429 #endif	/* LL_USART_DATAWIDTH_9B */
430 	case LL_USART_DATAWIDTH_8B:
431 	default:
432 		if (p == LL_USART_PARITY_NONE) {
433 			return UART_CFG_DATA_BITS_8;
434 		} else {
435 			return UART_CFG_DATA_BITS_7;
436 		}
437 	}
438 }
439 
440 /**
441  * @brief  Get LL hardware flow control define from
442  *         Zephyr hardware flow control option.
443  * @note   Supports only UART_CFG_FLOW_CTRL_RTS_CTS and UART_CFG_FLOW_CTRL_RS485.
444  * @param  fc: Zephyr hardware flow control option.
445  * @retval LL_USART_HWCONTROL_RTS_CTS, or LL_USART_HWCONTROL_NONE.
446  */
uart_stm32_cfg2ll_hwctrl(enum uart_config_flow_control fc)447 static inline uint32_t uart_stm32_cfg2ll_hwctrl(enum uart_config_flow_control fc)
448 {
449 	if (fc == UART_CFG_FLOW_CTRL_RTS_CTS) {
450 		return LL_USART_HWCONTROL_RTS_CTS;
451 	} else if (fc == UART_CFG_FLOW_CTRL_RS485) {
452 		/* Driver Enable is handled separately */
453 		return LL_USART_HWCONTROL_NONE;
454 	}
455 
456 	return LL_USART_HWCONTROL_NONE;
457 }
458 
459 /**
460  * @brief  Get Zephyr hardware flow control option from
461  *         LL hardware flow control define.
462  * @note   Supports only LL_USART_HWCONTROL_RTS_CTS.
463  * @param  fc: LL hardware flow control definition.
464  * @retval UART_CFG_FLOW_CTRL_RTS_CTS, or UART_CFG_FLOW_CTRL_NONE.
465  */
uart_stm32_ll2cfg_hwctrl(uint32_t fc)466 static inline enum uart_config_flow_control uart_stm32_ll2cfg_hwctrl(uint32_t fc)
467 {
468 	if (fc == LL_USART_HWCONTROL_RTS_CTS) {
469 		return UART_CFG_FLOW_CTRL_RTS_CTS;
470 	}
471 
472 	return UART_CFG_FLOW_CTRL_NONE;
473 }
474 
uart_stm32_parameters_set(const struct device * dev,const struct uart_config * cfg)475 static void uart_stm32_parameters_set(const struct device *dev,
476 				      const struct uart_config *cfg)
477 {
478 	const struct uart_stm32_config *config = dev->config;
479 	struct uart_stm32_data *data = dev->data;
480 	struct uart_config *uart_cfg = data->uart_cfg;
481 	const uint32_t parity = uart_stm32_cfg2ll_parity(cfg->parity);
482 	const uint32_t stopbits = uart_stm32_cfg2ll_stopbits(config, cfg->stop_bits);
483 	const uint32_t databits = uart_stm32_cfg2ll_databits(cfg->data_bits,
484 							     cfg->parity);
485 	const uint32_t flowctrl = uart_stm32_cfg2ll_hwctrl(cfg->flow_ctrl);
486 #if HAS_DRIVER_ENABLE
487 	bool driver_enable = cfg->flow_ctrl == UART_CFG_FLOW_CTRL_RS485;
488 #endif
489 
490 	if (cfg == uart_cfg) {
491 		/* Called via (re-)init function, so the SoC either just booted,
492 		 * or is returning from a low-power state where it lost register
493 		 * contents
494 		 */
495 		LL_USART_ConfigCharacter(config->usart,
496 					 databits,
497 					 parity,
498 					 stopbits);
499 		uart_stm32_set_hwctrl(dev, flowctrl);
500 		uart_stm32_set_baudrate(dev, cfg->baudrate);
501 	} else {
502 		/* Called from application/subsys via uart_configure syscall */
503 		if (parity != uart_stm32_get_parity(dev)) {
504 			uart_stm32_set_parity(dev, parity);
505 		}
506 
507 		if (stopbits != uart_stm32_get_stopbits(dev)) {
508 			uart_stm32_set_stopbits(dev, stopbits);
509 		}
510 
511 		if (databits != uart_stm32_get_databits(dev)) {
512 			uart_stm32_set_databits(dev, databits);
513 		}
514 
515 		if (flowctrl != uart_stm32_get_hwctrl(dev)) {
516 			uart_stm32_set_hwctrl(dev, flowctrl);
517 		}
518 
519 #if HAS_DRIVER_ENABLE
520 		if (driver_enable != uart_stm32_get_driver_enable(dev)) {
521 			uart_stm32_set_driver_enable(dev, driver_enable);
522 		}
523 #endif
524 
525 		if (cfg->baudrate != uart_cfg->baudrate) {
526 			uart_stm32_set_baudrate(dev, cfg->baudrate);
527 			uart_cfg->baudrate = cfg->baudrate;
528 		}
529 	}
530 }
531 
532 #ifdef CONFIG_UART_USE_RUNTIME_CONFIGURE
uart_stm32_configure(const struct device * dev,const struct uart_config * cfg)533 static int uart_stm32_configure(const struct device *dev,
534 				const struct uart_config *cfg)
535 {
536 	const struct uart_stm32_config *config = dev->config;
537 	USART_TypeDef *usart = config->usart;
538 	struct uart_stm32_data *data = dev->data;
539 	struct uart_config *uart_cfg = data->uart_cfg;
540 	const uint32_t parity = uart_stm32_cfg2ll_parity(cfg->parity);
541 	const uint32_t stopbits = uart_stm32_cfg2ll_stopbits(config, cfg->stop_bits);
542 	const uint32_t databits = uart_stm32_cfg2ll_databits(cfg->data_bits,
543 							     cfg->parity);
544 
545 	/* Hardware doesn't support mark or space parity */
546 	if ((cfg->parity == UART_CFG_PARITY_MARK) ||
547 	    (cfg->parity == UART_CFG_PARITY_SPACE)) {
548 		return -ENOTSUP;
549 	}
550 
551 	/* Driver does not supports parity + 9 databits */
552 	if ((cfg->parity != UART_CFG_PARITY_NONE) &&
553 	    (cfg->data_bits == UART_CFG_DATA_BITS_9)) {
554 		return -ENOTSUP;
555 	}
556 
557 	/* When the transformed ll stop bits don't match with what was requested, then it's not
558 	 * supported
559 	 */
560 	if (uart_stm32_ll2cfg_stopbits(stopbits) != cfg->stop_bits) {
561 		return -ENOTSUP;
562 	}
563 
564 	/* When the transformed ll databits don't match with what was requested, then it's not
565 	 * supported
566 	 */
567 	if (uart_stm32_ll2cfg_databits(databits, parity) != cfg->data_bits) {
568 		return -ENOTSUP;
569 	}
570 
571 	/* Driver supports only RTS/CTS and RS485 flow control */
572 	if (!(cfg->flow_ctrl == UART_CFG_FLOW_CTRL_NONE
573 		|| (cfg->flow_ctrl == UART_CFG_FLOW_CTRL_RTS_CTS &&
574 			IS_UART_HWFLOW_INSTANCE(usart))
575 #if HAS_DRIVER_ENABLE
576 		|| (cfg->flow_ctrl == UART_CFG_FLOW_CTRL_RS485 &&
577 			IS_UART_DRIVER_ENABLE_INSTANCE(usart))
578 #endif
579 		)) {
580 		return -ENOTSUP;
581 	}
582 
583 	LL_USART_Disable(usart);
584 
585 	/* Set basic parameters, such as data-/stop-bit, parity, and baudrate */
586 	uart_stm32_parameters_set(dev, cfg);
587 
588 	LL_USART_Enable(usart);
589 
590 	/* Upon successful configuration, persist the syscall-passed
591 	 * uart_config.
592 	 * This allows restoring it, should the device return from a low-power
593 	 * mode in which register contents are lost.
594 	 */
595 	*uart_cfg = *cfg;
596 
597 	return 0;
598 };
599 
uart_stm32_config_get(const struct device * dev,struct uart_config * cfg)600 static int uart_stm32_config_get(const struct device *dev,
601 				 struct uart_config *cfg)
602 {
603 	struct uart_stm32_data *data = dev->data;
604 	struct uart_config *uart_cfg = data->uart_cfg;
605 
606 	cfg->baudrate = uart_cfg->baudrate;
607 	cfg->parity = uart_stm32_ll2cfg_parity(uart_stm32_get_parity(dev));
608 	cfg->stop_bits = uart_stm32_ll2cfg_stopbits(
609 		uart_stm32_get_stopbits(dev));
610 	cfg->data_bits = uart_stm32_ll2cfg_databits(
611 		uart_stm32_get_databits(dev), uart_stm32_get_parity(dev));
612 	cfg->flow_ctrl = uart_stm32_ll2cfg_hwctrl(
613 		uart_stm32_get_hwctrl(dev));
614 #if HAS_DRIVER_ENABLE
615 	if (uart_stm32_get_driver_enable(dev)) {
616 		cfg->flow_ctrl = UART_CFG_FLOW_CTRL_RS485;
617 	}
618 #endif
619 	return 0;
620 }
621 #endif /* CONFIG_UART_USE_RUNTIME_CONFIGURE */
622 
623 typedef void (*poll_in_fn)(
624 	USART_TypeDef *usart,
625 	void *in);
626 
uart_stm32_poll_in_visitor(const struct device * dev,void * in,poll_in_fn get_fn)627 static int uart_stm32_poll_in_visitor(const struct device *dev, void *in, poll_in_fn get_fn)
628 {
629 	const struct uart_stm32_config *config = dev->config;
630 	USART_TypeDef *usart = config->usart;
631 
632 	/* Clear overrun error flag */
633 	if (LL_USART_IsActiveFlag_ORE(usart)) {
634 		LL_USART_ClearFlag_ORE(usart);
635 	}
636 
637 	/*
638 	 * On stm32 F4X, F1X, and F2X, the RXNE flag is affected (cleared) by
639 	 * the uart_err_check function call (on errors flags clearing)
640 	 */
641 	if (!LL_USART_IsActiveFlag_RXNE(usart)) {
642 		return -1;
643 	}
644 
645 	get_fn(usart, in);
646 
647 	return 0;
648 }
649 
650 typedef void (*poll_out_fn)(
651 	USART_TypeDef *usart, void *out);
652 
uart_stm32_poll_out_visitor(const struct device * dev,void * out,poll_out_fn set_fn)653 static void uart_stm32_poll_out_visitor(const struct device *dev, void *out, poll_out_fn set_fn)
654 {
655 	const struct uart_stm32_config *config = dev->config;
656 	USART_TypeDef *usart = config->usart;
657 #ifdef CONFIG_PM
658 	struct uart_stm32_data *data = dev->data;
659 #endif
660 	unsigned int key;
661 
662 	/* Wait for TXE flag to be raised
663 	 * When TXE flag is raised, we lock interrupts to prevent interrupts (notably that of usart)
664 	 * or thread switch. Then, we can safely send our character. The character sent will be
665 	 * interlaced with the characters potentially send with interrupt transmission API
666 	 */
667 	while (1) {
668 		if (LL_USART_IsActiveFlag_TXE(usart)) {
669 			key = irq_lock();
670 			if (LL_USART_IsActiveFlag_TXE(usart)) {
671 				break;
672 			}
673 			irq_unlock(key);
674 		}
675 	}
676 
677 #ifdef CONFIG_PM
678 
679 	/* If an interrupt transmission is in progress, the pm constraint is already managed by the
680 	 * call of uart_stm32_irq_tx_[en|dis]able
681 	 */
682 	if (!data->tx_poll_stream_on && !data->tx_int_stream_on) {
683 		data->tx_poll_stream_on = true;
684 
685 		/* Don't allow system to suspend until stream
686 		 * transmission has completed
687 		 */
688 		uart_stm32_pm_policy_state_lock_get(dev);
689 
690 		/* Enable TC interrupt so we can release suspend
691 		 * constraint when done
692 		 */
693 		LL_USART_EnableIT_TC(usart);
694 	}
695 #endif /* CONFIG_PM */
696 
697 	set_fn(usart, out);
698 	irq_unlock(key);
699 }
700 
poll_in_u8(USART_TypeDef * usart,void * in)701 static void poll_in_u8(USART_TypeDef *usart, void *in)
702 {
703 	*((unsigned char *)in) = (unsigned char)LL_USART_ReceiveData8(usart);
704 }
705 
poll_out_u8(USART_TypeDef * usart,void * out)706 static void poll_out_u8(USART_TypeDef *usart, void *out)
707 {
708 	LL_USART_TransmitData8(usart, *((uint8_t *)out));
709 }
710 
uart_stm32_poll_in(const struct device * dev,unsigned char * c)711 static int uart_stm32_poll_in(const struct device *dev, unsigned char *c)
712 {
713 	return uart_stm32_poll_in_visitor(dev, (void *)c, poll_in_u8);
714 }
715 
uart_stm32_poll_out(const struct device * dev,unsigned char c)716 static void uart_stm32_poll_out(const struct device *dev, unsigned char c)
717 {
718 	uart_stm32_poll_out_visitor(dev, (void *)&c, poll_out_u8);
719 }
720 
721 #ifdef CONFIG_UART_WIDE_DATA
722 
poll_out_u9(USART_TypeDef * usart,void * out)723 static void poll_out_u9(USART_TypeDef *usart, void *out)
724 {
725 	LL_USART_TransmitData9(usart, *((uint16_t *)out));
726 }
727 
poll_in_u9(USART_TypeDef * usart,void * in)728 static void poll_in_u9(USART_TypeDef *usart, void *in)
729 {
730 	*((uint16_t *)in) = LL_USART_ReceiveData9(usart);
731 }
732 
uart_stm32_poll_in_u16(const struct device * dev,uint16_t * in_u16)733 static int uart_stm32_poll_in_u16(const struct device *dev, uint16_t *in_u16)
734 {
735 	return uart_stm32_poll_in_visitor(dev, (void *)in_u16, poll_in_u9);
736 }
737 
uart_stm32_poll_out_u16(const struct device * dev,uint16_t out_u16)738 static void uart_stm32_poll_out_u16(const struct device *dev, uint16_t out_u16)
739 {
740 	uart_stm32_poll_out_visitor(dev, (void *)&out_u16, poll_out_u9);
741 }
742 
743 #endif
744 
uart_stm32_err_check(const struct device * dev)745 static int uart_stm32_err_check(const struct device *dev)
746 {
747 	const struct uart_stm32_config *config = dev->config;
748 	USART_TypeDef *usart = config->usart;
749 	uint32_t err = 0U;
750 
751 	/* Check for errors, then clear them.
752 	 * Some SoC clear all error flags when at least
753 	 * one is cleared. (e.g. F4X, F1X, and F2X).
754 	 * The stm32 F4X, F1X, and F2X also reads the usart DR when clearing Errors
755 	 */
756 	if (LL_USART_IsActiveFlag_ORE(usart)) {
757 		err |= UART_ERROR_OVERRUN;
758 	}
759 
760 	if (LL_USART_IsActiveFlag_PE(usart)) {
761 		err |= UART_ERROR_PARITY;
762 	}
763 
764 	if (LL_USART_IsActiveFlag_FE(usart)) {
765 		err |= UART_ERROR_FRAMING;
766 	}
767 
768 	if (LL_USART_IsActiveFlag_NE(usart)) {
769 		err |= UART_ERROR_NOISE;
770 	}
771 
772 #if !defined(CONFIG_SOC_SERIES_STM32F0X) || defined(USART_LIN_SUPPORT)
773 	if (LL_USART_IsActiveFlag_LBD(usart)) {
774 		err |= UART_BREAK;
775 	}
776 
777 	if (err & UART_BREAK) {
778 		LL_USART_ClearFlag_LBD(usart);
779 	}
780 #endif
781 	/* Clearing error :
782 	 * the stm32 F4X, F1X, and F2X sw sequence is reading the usart SR
783 	 * then the usart DR to clear the Error flags ORE, PE, FE, NE
784 	 * --> so is the RXNE flag also cleared !
785 	 */
786 	if (err & UART_ERROR_OVERRUN) {
787 		LL_USART_ClearFlag_ORE(usart);
788 	}
789 
790 	if (err & UART_ERROR_PARITY) {
791 		LL_USART_ClearFlag_PE(usart);
792 	}
793 
794 	if (err & UART_ERROR_FRAMING) {
795 		LL_USART_ClearFlag_FE(usart);
796 	}
797 
798 	if (err & UART_ERROR_NOISE) {
799 		LL_USART_ClearFlag_NE(usart);
800 	}
801 
802 	return err;
803 }
804 
__uart_stm32_get_clock(const struct device * dev)805 static inline void __uart_stm32_get_clock(const struct device *dev)
806 {
807 	struct uart_stm32_data *data = dev->data;
808 	const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
809 
810 	data->clock = clk;
811 }
812 
813 #ifdef CONFIG_UART_INTERRUPT_DRIVEN
814 
815 typedef void (*fifo_fill_fn)(USART_TypeDef *usart, const void *tx_data,
816 			     const uint8_t offset);
817 
uart_stm32_fifo_fill_visitor(const struct device * dev,const void * tx_data,int size,fifo_fill_fn fill_fn)818 static int uart_stm32_fifo_fill_visitor(const struct device *dev, const void *tx_data, int size,
819 					fifo_fill_fn fill_fn)
820 {
821 	const struct uart_stm32_config *config = dev->config;
822 	USART_TypeDef *usart = config->usart;
823 	uint8_t num_tx = 0U;
824 	unsigned int key;
825 
826 	if (!LL_USART_IsActiveFlag_TXE(usart)) {
827 		return num_tx;
828 	}
829 
830 	/* Lock interrupts to prevent nested interrupts or thread switch */
831 	key = irq_lock();
832 
833 	while ((size - num_tx > 0) && LL_USART_IsActiveFlag_TXE(usart)) {
834 		/* TXE flag will be cleared with byte write to DR|RDR register */
835 
836 		/* Send a character */
837 		fill_fn(usart, tx_data, num_tx);
838 		num_tx++;
839 	}
840 
841 	irq_unlock(key);
842 
843 	return num_tx;
844 }
845 
fifo_fill_with_u8(USART_TypeDef * usart,const void * tx_data,const uint8_t offset)846 static void fifo_fill_with_u8(USART_TypeDef *usart,
847 					 const void *tx_data, const uint8_t offset)
848 {
849 	const uint8_t *data = (const uint8_t *)tx_data;
850 	/* Send a character (8bit) */
851 	LL_USART_TransmitData8(usart, data[offset]);
852 }
853 
uart_stm32_fifo_fill(const struct device * dev,const uint8_t * tx_data,int size)854 static int uart_stm32_fifo_fill(const struct device *dev, const uint8_t *tx_data, int size)
855 {
856 	if (uart_stm32_ll2cfg_databits(uart_stm32_get_databits(dev), uart_stm32_get_parity(dev)) ==
857 	    UART_CFG_DATA_BITS_9) {
858 		return -ENOTSUP;
859 	}
860 	return uart_stm32_fifo_fill_visitor(dev, (const void *)tx_data, size,
861 					    fifo_fill_with_u8);
862 }
863 
864 typedef void (*fifo_read_fn)(USART_TypeDef *usart, void *rx_data,
865 			     const uint8_t offset);
866 
uart_stm32_fifo_read_visitor(const struct device * dev,void * rx_data,const int size,fifo_read_fn read_fn)867 static int uart_stm32_fifo_read_visitor(const struct device *dev, void *rx_data, const int size,
868 					fifo_read_fn read_fn)
869 {
870 	const struct uart_stm32_config *config = dev->config;
871 	USART_TypeDef *usart = config->usart;
872 	uint8_t num_rx = 0U;
873 
874 	while ((size - num_rx > 0) && LL_USART_IsActiveFlag_RXNE(usart)) {
875 		/* RXNE flag will be cleared upon read from DR|RDR register */
876 
877 		read_fn(usart, rx_data, num_rx);
878 		num_rx++;
879 
880 		/* Clear overrun error flag */
881 		if (LL_USART_IsActiveFlag_ORE(usart)) {
882 			LL_USART_ClearFlag_ORE(usart);
883 			/*
884 			 * On stm32 F4X, F1X, and F2X, the RXNE flag is affected (cleared) by
885 			 * the uart_err_check function call (on errors flags clearing)
886 			 */
887 		}
888 	}
889 
890 	return num_rx;
891 }
892 
fifo_read_with_u8(USART_TypeDef * usart,void * rx_data,const uint8_t offset)893 static void fifo_read_with_u8(USART_TypeDef *usart, void *rx_data,
894 					 const uint8_t offset)
895 {
896 	uint8_t *data = (uint8_t *)rx_data;
897 
898 	data[offset] = LL_USART_ReceiveData8(usart);
899 }
900 
uart_stm32_fifo_read(const struct device * dev,uint8_t * rx_data,const int size)901 static int uart_stm32_fifo_read(const struct device *dev, uint8_t *rx_data, const int size)
902 {
903 	if (uart_stm32_ll2cfg_databits(uart_stm32_get_databits(dev), uart_stm32_get_parity(dev)) ==
904 	    UART_CFG_DATA_BITS_9) {
905 		return -ENOTSUP;
906 	}
907 	return uart_stm32_fifo_read_visitor(dev, (void *)rx_data, size,
908 					    fifo_read_with_u8);
909 }
910 
911 #ifdef CONFIG_UART_WIDE_DATA
912 
fifo_fill_with_u16(USART_TypeDef * usart,const void * tx_data,const uint8_t offset)913 static void fifo_fill_with_u16(USART_TypeDef *usart,
914 					  const void *tx_data, const uint8_t offset)
915 {
916 	const uint16_t *data = (const uint16_t *)tx_data;
917 
918 	/* Send a character (9bit) */
919 	LL_USART_TransmitData9(usart, data[offset]);
920 }
921 
uart_stm32_fifo_fill_u16(const struct device * dev,const uint16_t * tx_data,int size)922 static int uart_stm32_fifo_fill_u16(const struct device *dev, const uint16_t *tx_data, int size)
923 {
924 	if (uart_stm32_ll2cfg_databits(uart_stm32_get_databits(dev), uart_stm32_get_parity(dev)) !=
925 	    UART_CFG_DATA_BITS_9) {
926 		return -ENOTSUP;
927 	}
928 	return uart_stm32_fifo_fill_visitor(dev, (const void *)tx_data, size,
929 					    fifo_fill_with_u16);
930 }
931 
fifo_read_with_u16(USART_TypeDef * usart,void * rx_data,const uint8_t offset)932 static void fifo_read_with_u16(USART_TypeDef *usart, void *rx_data,
933 					  const uint8_t offset)
934 {
935 	uint16_t *data = (uint16_t *)rx_data;
936 
937 	data[offset] = LL_USART_ReceiveData9(usart);
938 }
939 
uart_stm32_fifo_read_u16(const struct device * dev,uint16_t * rx_data,const int size)940 static int uart_stm32_fifo_read_u16(const struct device *dev, uint16_t *rx_data, const int size)
941 {
942 	if (uart_stm32_ll2cfg_databits(uart_stm32_get_databits(dev), uart_stm32_get_parity(dev)) !=
943 	    UART_CFG_DATA_BITS_9) {
944 		return -ENOTSUP;
945 	}
946 	return uart_stm32_fifo_read_visitor(dev, (void *)rx_data, size,
947 					    fifo_read_with_u16);
948 }
949 
950 #endif
951 
uart_stm32_irq_tx_enable(const struct device * dev)952 static void uart_stm32_irq_tx_enable(const struct device *dev)
953 {
954 	const struct uart_stm32_config *config = dev->config;
955 #ifdef CONFIG_PM
956 	struct uart_stm32_data *data = dev->data;
957 	unsigned int key;
958 #endif
959 
960 #ifdef CONFIG_PM
961 	key = irq_lock();
962 	data->tx_poll_stream_on = false;
963 	data->tx_int_stream_on = true;
964 	uart_stm32_pm_policy_state_lock_get(dev);
965 #endif
966 	LL_USART_EnableIT_TC(config->usart);
967 
968 #ifdef CONFIG_PM
969 	irq_unlock(key);
970 #endif
971 }
972 
uart_stm32_irq_tx_disable(const struct device * dev)973 static void uart_stm32_irq_tx_disable(const struct device *dev)
974 {
975 	const struct uart_stm32_config *config = dev->config;
976 #ifdef CONFIG_PM
977 	struct uart_stm32_data *data = dev->data;
978 	unsigned int key;
979 
980 	key = irq_lock();
981 #endif
982 
983 	LL_USART_DisableIT_TC(config->usart);
984 
985 #ifdef CONFIG_PM
986 	data->tx_int_stream_on = false;
987 	uart_stm32_pm_policy_state_lock_put(dev);
988 #endif
989 
990 #ifdef CONFIG_PM
991 	irq_unlock(key);
992 #endif
993 }
994 
uart_stm32_irq_tx_ready(const struct device * dev)995 static int uart_stm32_irq_tx_ready(const struct device *dev)
996 {
997 	const struct uart_stm32_config *config = dev->config;
998 
999 	return LL_USART_IsActiveFlag_TXE(config->usart) &&
1000 		LL_USART_IsEnabledIT_TC(config->usart);
1001 }
1002 
uart_stm32_irq_tx_complete(const struct device * dev)1003 static int uart_stm32_irq_tx_complete(const struct device *dev)
1004 {
1005 	const struct uart_stm32_config *config = dev->config;
1006 
1007 	return LL_USART_IsActiveFlag_TC(config->usart);
1008 }
1009 
uart_stm32_irq_rx_enable(const struct device * dev)1010 static void uart_stm32_irq_rx_enable(const struct device *dev)
1011 {
1012 	const struct uart_stm32_config *config = dev->config;
1013 
1014 	LL_USART_EnableIT_RXNE(config->usart);
1015 }
1016 
uart_stm32_irq_rx_disable(const struct device * dev)1017 static void uart_stm32_irq_rx_disable(const struct device *dev)
1018 {
1019 	const struct uart_stm32_config *config = dev->config;
1020 
1021 	LL_USART_DisableIT_RXNE(config->usart);
1022 }
1023 
uart_stm32_irq_rx_ready(const struct device * dev)1024 static int uart_stm32_irq_rx_ready(const struct device *dev)
1025 {
1026 	const struct uart_stm32_config *config = dev->config;
1027 	/*
1028 	 * On stm32 F4X, F1X, and F2X, the RXNE flag is affected (cleared) by
1029 	 * the uart_err_check function call (on errors flags clearing)
1030 	 */
1031 	return LL_USART_IsActiveFlag_RXNE(config->usart);
1032 }
1033 
uart_stm32_irq_err_enable(const struct device * dev)1034 static void uart_stm32_irq_err_enable(const struct device *dev)
1035 {
1036 	const struct uart_stm32_config *config = dev->config;
1037 	USART_TypeDef *usart = config->usart;
1038 
1039 	/* Enable FE, ORE interruptions */
1040 	LL_USART_EnableIT_ERROR(usart);
1041 #if !defined(CONFIG_SOC_SERIES_STM32F0X) || defined(USART_LIN_SUPPORT)
1042 	/* Enable Line break detection */
1043 	if (IS_UART_LIN_INSTANCE(usart)) {
1044 		LL_USART_EnableIT_LBD(usart);
1045 	}
1046 #endif
1047 	/* Enable parity error interruption */
1048 	LL_USART_EnableIT_PE(usart);
1049 }
1050 
uart_stm32_irq_err_disable(const struct device * dev)1051 static void uart_stm32_irq_err_disable(const struct device *dev)
1052 {
1053 	const struct uart_stm32_config *config = dev->config;
1054 	USART_TypeDef *usart = config->usart;
1055 
1056 	/* Disable FE, ORE interruptions */
1057 	LL_USART_DisableIT_ERROR(usart);
1058 #if !defined(CONFIG_SOC_SERIES_STM32F0X) || defined(USART_LIN_SUPPORT)
1059 	/* Disable Line break detection */
1060 	if (IS_UART_LIN_INSTANCE(usart)) {
1061 		LL_USART_DisableIT_LBD(usart);
1062 	}
1063 #endif
1064 	/* Disable parity error interruption */
1065 	LL_USART_DisableIT_PE(usart);
1066 }
1067 
uart_stm32_irq_is_pending(const struct device * dev)1068 static int uart_stm32_irq_is_pending(const struct device *dev)
1069 {
1070 	const struct uart_stm32_config *config = dev->config;
1071 	USART_TypeDef *usart = config->usart;
1072 
1073 	return ((LL_USART_IsActiveFlag_RXNE(usart) &&
1074 		 LL_USART_IsEnabledIT_RXNE(usart)) ||
1075 		(LL_USART_IsActiveFlag_TC(usart) &&
1076 		 LL_USART_IsEnabledIT_TC(usart)));
1077 }
1078 
uart_stm32_irq_update(const struct device * dev)1079 static int uart_stm32_irq_update(const struct device *dev)
1080 {
1081 	return 1;
1082 }
1083 
uart_stm32_irq_callback_set(const struct device * dev,uart_irq_callback_user_data_t cb,void * cb_data)1084 static void uart_stm32_irq_callback_set(const struct device *dev,
1085 					uart_irq_callback_user_data_t cb,
1086 					void *cb_data)
1087 {
1088 	struct uart_stm32_data *data = dev->data;
1089 
1090 	data->user_cb = cb;
1091 	data->user_data = cb_data;
1092 
1093 #if defined(CONFIG_UART_EXCLUSIVE_API_CALLBACKS)
1094 	data->async_cb = NULL;
1095 	data->async_user_data = NULL;
1096 #endif
1097 }
1098 
1099 #endif /* CONFIG_UART_INTERRUPT_DRIVEN */
1100 
1101 #ifdef CONFIG_UART_ASYNC_API
1102 
async_user_callback(struct uart_stm32_data * data,struct uart_event * event)1103 static inline void async_user_callback(struct uart_stm32_data *data,
1104 				struct uart_event *event)
1105 {
1106 	if (data->async_cb) {
1107 		data->async_cb(data->uart_dev, event, data->async_user_data);
1108 	}
1109 }
1110 
async_evt_rx_rdy(struct uart_stm32_data * data)1111 static inline void async_evt_rx_rdy(struct uart_stm32_data *data)
1112 {
1113 	LOG_DBG("rx_rdy: (%d %d)", data->dma_rx.offset, data->dma_rx.counter);
1114 
1115 	struct uart_event event = {
1116 		.type = UART_RX_RDY,
1117 		.data.rx.buf = data->dma_rx.buffer,
1118 		.data.rx.len = data->dma_rx.counter - data->dma_rx.offset,
1119 		.data.rx.offset = data->dma_rx.offset
1120 	};
1121 
1122 	/* update the current pos for new data */
1123 	data->dma_rx.offset = data->dma_rx.counter;
1124 
1125 	/* send event only for new data */
1126 	if (event.data.rx.len > 0) {
1127 		async_user_callback(data, &event);
1128 	}
1129 }
1130 
async_evt_rx_err(struct uart_stm32_data * data,int err_code)1131 static inline void async_evt_rx_err(struct uart_stm32_data *data, int err_code)
1132 {
1133 	LOG_DBG("rx error: %d", err_code);
1134 
1135 	struct uart_event event = {
1136 		.type = UART_RX_STOPPED,
1137 		.data.rx_stop.reason = err_code,
1138 		.data.rx_stop.data.len = data->dma_rx.counter,
1139 		.data.rx_stop.data.offset = 0,
1140 		.data.rx_stop.data.buf = data->dma_rx.buffer
1141 	};
1142 
1143 	async_user_callback(data, &event);
1144 }
1145 
async_evt_tx_done(struct uart_stm32_data * data)1146 static inline void async_evt_tx_done(struct uart_stm32_data *data)
1147 {
1148 	LOG_DBG("tx done: %d", data->dma_tx.counter);
1149 
1150 	struct uart_event event = {
1151 		.type = UART_TX_DONE,
1152 		.data.tx.buf = data->dma_tx.buffer,
1153 		.data.tx.len = data->dma_tx.counter
1154 	};
1155 
1156 	/* Reset tx buffer */
1157 	data->dma_tx.buffer_length = 0;
1158 	data->dma_tx.counter = 0;
1159 
1160 	async_user_callback(data, &event);
1161 }
1162 
async_evt_tx_abort(struct uart_stm32_data * data)1163 static inline void async_evt_tx_abort(struct uart_stm32_data *data)
1164 {
1165 	LOG_DBG("tx abort: %d", data->dma_tx.counter);
1166 
1167 	struct uart_event event = {
1168 		.type = UART_TX_ABORTED,
1169 		.data.tx.buf = data->dma_tx.buffer,
1170 		.data.tx.len = data->dma_tx.counter
1171 	};
1172 
1173 	/* Reset tx buffer */
1174 	data->dma_tx.buffer_length = 0;
1175 	data->dma_tx.counter = 0;
1176 
1177 	async_user_callback(data, &event);
1178 }
1179 
async_evt_rx_buf_request(struct uart_stm32_data * data)1180 static inline void async_evt_rx_buf_request(struct uart_stm32_data *data)
1181 {
1182 	struct uart_event evt = {
1183 		.type = UART_RX_BUF_REQUEST,
1184 	};
1185 
1186 	async_user_callback(data, &evt);
1187 }
1188 
async_evt_rx_buf_release(struct uart_stm32_data * data)1189 static inline void async_evt_rx_buf_release(struct uart_stm32_data *data)
1190 {
1191 	struct uart_event evt = {
1192 		.type = UART_RX_BUF_RELEASED,
1193 		.data.rx_buf.buf = data->dma_rx.buffer,
1194 	};
1195 
1196 	async_user_callback(data, &evt);
1197 }
1198 
async_timer_start(struct k_work_delayable * work,int32_t timeout)1199 static inline void async_timer_start(struct k_work_delayable *work,
1200 				     int32_t timeout)
1201 {
1202 	if ((timeout != SYS_FOREVER_US) && (timeout != 0)) {
1203 		/* start timer */
1204 		LOG_DBG("async timer started for %d us", timeout);
1205 		k_work_reschedule(work, K_USEC(timeout));
1206 	}
1207 }
1208 
uart_stm32_dma_rx_flush(const struct device * dev)1209 static void uart_stm32_dma_rx_flush(const struct device *dev)
1210 {
1211 	struct dma_status stat;
1212 	struct uart_stm32_data *data = dev->data;
1213 
1214 	if (dma_get_status(data->dma_rx.dma_dev,
1215 				data->dma_rx.dma_channel, &stat) == 0) {
1216 		size_t rx_rcv_len = data->dma_rx.buffer_length -
1217 					stat.pending_length;
1218 		if (rx_rcv_len > data->dma_rx.offset) {
1219 			data->dma_rx.counter = rx_rcv_len;
1220 
1221 			async_evt_rx_rdy(data);
1222 		}
1223 	}
1224 }
1225 
1226 #endif /* CONFIG_UART_ASYNC_API */
1227 
1228 #if defined(CONFIG_UART_INTERRUPT_DRIVEN) || \
1229 	defined(CONFIG_UART_ASYNC_API) || \
1230 	defined(CONFIG_PM)
1231 
uart_stm32_isr(const struct device * dev)1232 static void uart_stm32_isr(const struct device *dev)
1233 {
1234 	struct uart_stm32_data *data = dev->data;
1235 #if defined(CONFIG_PM) || defined(CONFIG_UART_ASYNC_API)
1236 	const struct uart_stm32_config *config = dev->config;
1237 	USART_TypeDef *usart = config->usart;
1238 #endif
1239 
1240 #ifdef CONFIG_PM
1241 	if (LL_USART_IsEnabledIT_TC(usart) &&
1242 		LL_USART_IsActiveFlag_TC(usart)) {
1243 
1244 		if (data->tx_poll_stream_on) {
1245 			/* A poll stream transmission just completed,
1246 			 * allow system to suspend
1247 			 */
1248 			LL_USART_DisableIT_TC(usart);
1249 			data->tx_poll_stream_on = false;
1250 			uart_stm32_pm_policy_state_lock_put(dev);
1251 		}
1252 		/* Stream transmission was either async or IRQ based,
1253 		 * constraint will be released at the same time TC IT
1254 		 * is disabled
1255 		 */
1256 	}
1257 #endif
1258 
1259 #ifdef CONFIG_UART_INTERRUPT_DRIVEN
1260 	if (data->user_cb) {
1261 		data->user_cb(dev, data->user_data);
1262 	}
1263 #endif /* CONFIG_UART_INTERRUPT_DRIVEN */
1264 
1265 #ifdef CONFIG_UART_ASYNC_API
1266 	if (LL_USART_IsEnabledIT_IDLE(usart) &&
1267 			LL_USART_IsActiveFlag_IDLE(usart)) {
1268 
1269 		LL_USART_ClearFlag_IDLE(usart);
1270 
1271 		LOG_DBG("idle interrupt occurred");
1272 
1273 		if (data->dma_rx.timeout == 0) {
1274 			uart_stm32_dma_rx_flush(dev);
1275 		} else {
1276 			/* Start the RX timer not null */
1277 			async_timer_start(&data->dma_rx.timeout_work,
1278 								data->dma_rx.timeout);
1279 		}
1280 	} else if (LL_USART_IsEnabledIT_TC(usart) &&
1281 			LL_USART_IsActiveFlag_TC(usart)) {
1282 
1283 		LL_USART_DisableIT_TC(usart);
1284 		/* Generate TX_DONE event when transmission is done */
1285 		async_evt_tx_done(data);
1286 
1287 #ifdef CONFIG_PM
1288 		uart_stm32_pm_policy_state_lock_put(dev);
1289 #endif
1290 	} else if (LL_USART_IsEnabledIT_RXNE(usart) &&
1291 			LL_USART_IsActiveFlag_RXNE(usart)) {
1292 #ifdef USART_SR_RXNE
1293 		/* clear the RXNE flag, because Rx data was not read */
1294 		LL_USART_ClearFlag_RXNE(usart);
1295 #else
1296 		/* clear the RXNE by flushing the fifo, because Rx data was not read */
1297 		LL_USART_RequestRxDataFlush(usart);
1298 #endif /* USART_SR_RXNE */
1299 	}
1300 
1301 	/* Clear errors */
1302 	uart_stm32_err_check(dev);
1303 #endif /* CONFIG_UART_ASYNC_API */
1304 
1305 #if defined(CONFIG_PM) && defined(IS_UART_WAKEUP_FROMSTOP_INSTANCE) \
1306 	&& defined(USART_CR3_WUFIE)
1307 	if (LL_USART_IsEnabledIT_WKUP(usart) &&
1308 		LL_USART_IsActiveFlag_WKUP(usart)) {
1309 
1310 		LL_USART_ClearFlag_WKUP(usart);
1311 #ifdef USART_ISR_REACK
1312 		while (LL_USART_IsActiveFlag_REACK(usart) == 0) {
1313 		}
1314 #endif
1315 	}
1316 #endif
1317 }
1318 #endif /* CONFIG_UART_INTERRUPT_DRIVEN || CONFIG_UART_ASYNC_API || CONFIG_PM */
1319 
1320 #ifdef CONFIG_UART_ASYNC_API
1321 
1322 #ifdef CONFIG_DCACHE
buf_in_nocache(uintptr_t buf,size_t len_bytes)1323 static bool buf_in_nocache(uintptr_t buf, size_t len_bytes)
1324 {
1325 	bool buf_within_nocache = false;
1326 
1327 #ifdef CONFIG_NOCACHE_MEMORY
1328 	buf_within_nocache = (buf >= ((uintptr_t)_nocache_ram_start)) &&
1329 		((buf + len_bytes - 1) <= ((uintptr_t)_nocache_ram_end));
1330 	if (buf_within_nocache) {
1331 		return true;
1332 	}
1333 #endif /* CONFIG_NOCACHE_MEMORY */
1334 
1335 	buf_within_nocache = mem_attr_check_buf(
1336 		(void *)buf, len_bytes, DT_MEM_ARM_MPU_RAM_NOCACHE) == 0;
1337 	if (buf_within_nocache) {
1338 		return true;
1339 	}
1340 
1341 	buf_within_nocache = (buf >= ((uintptr_t)__rodata_region_start)) &&
1342 		((buf + len_bytes - 1) <= ((uintptr_t)__rodata_region_end));
1343 
1344 	return buf_within_nocache;
1345 }
1346 #endif /* CONFIG_DCACHE */
1347 
uart_stm32_async_callback_set(const struct device * dev,uart_callback_t callback,void * user_data)1348 static int uart_stm32_async_callback_set(const struct device *dev,
1349 					 uart_callback_t callback,
1350 					 void *user_data)
1351 {
1352 	struct uart_stm32_data *data = dev->data;
1353 
1354 	data->async_cb = callback;
1355 	data->async_user_data = user_data;
1356 
1357 #if defined(CONFIG_UART_EXCLUSIVE_API_CALLBACKS)
1358 	data->user_cb = NULL;
1359 	data->user_data = NULL;
1360 #endif
1361 
1362 	return 0;
1363 }
1364 
uart_stm32_dma_tx_enable(const struct device * dev)1365 static inline void uart_stm32_dma_tx_enable(const struct device *dev)
1366 {
1367 	const struct uart_stm32_config *config = dev->config;
1368 
1369 	LL_USART_EnableDMAReq_TX(config->usart);
1370 }
1371 
uart_stm32_dma_tx_disable(const struct device * dev)1372 static inline void uart_stm32_dma_tx_disable(const struct device *dev)
1373 {
1374 #ifdef CONFIG_UART_STM32U5_ERRATA_DMAT
1375 	ARG_UNUSED(dev);
1376 
1377 	/*
1378 	 * Errata Sheet ES0499 : STM32U575xx and STM32U585xx device errata
1379 	 * USART does not generate DMA requests after setting/clearing DMAT bit
1380 	 * (also seen on stm32H5 serie)
1381 	 */
1382 #else
1383 	const struct uart_stm32_config *config = dev->config;
1384 
1385 	LL_USART_DisableDMAReq_TX(config->usart);
1386 #endif
1387 }
1388 
uart_stm32_dma_rx_enable(const struct device * dev)1389 static inline void uart_stm32_dma_rx_enable(const struct device *dev)
1390 {
1391 	const struct uart_stm32_config *config = dev->config;
1392 	struct uart_stm32_data *data = dev->data;
1393 
1394 	LL_USART_EnableDMAReq_RX(config->usart);
1395 
1396 	data->dma_rx.enabled = true;
1397 }
1398 
uart_stm32_dma_rx_disable(const struct device * dev)1399 static inline void uart_stm32_dma_rx_disable(const struct device *dev)
1400 {
1401 	struct uart_stm32_data *data = dev->data;
1402 
1403 	data->dma_rx.enabled = false;
1404 }
1405 
uart_stm32_async_rx_disable(const struct device * dev)1406 static int uart_stm32_async_rx_disable(const struct device *dev)
1407 {
1408 	const struct uart_stm32_config *config = dev->config;
1409 	USART_TypeDef *usart = config->usart;
1410 	struct uart_stm32_data *data = dev->data;
1411 	struct uart_event disabled_event = {
1412 		.type = UART_RX_DISABLED
1413 	};
1414 
1415 	if (!data->dma_rx.enabled) {
1416 		async_user_callback(data, &disabled_event);
1417 		return -EFAULT;
1418 	}
1419 
1420 	LL_USART_DisableIT_IDLE(usart);
1421 
1422 	uart_stm32_dma_rx_flush(dev);
1423 
1424 	async_evt_rx_buf_release(data);
1425 
1426 	uart_stm32_dma_rx_disable(dev);
1427 
1428 	(void)k_work_cancel_delayable(&data->dma_rx.timeout_work);
1429 
1430 	dma_stop(data->dma_rx.dma_dev, data->dma_rx.dma_channel);
1431 
1432 	if (data->rx_next_buffer) {
1433 		struct uart_event rx_next_buf_release_evt = {
1434 			.type = UART_RX_BUF_RELEASED,
1435 			.data.rx_buf.buf = data->rx_next_buffer,
1436 		};
1437 		async_user_callback(data, &rx_next_buf_release_evt);
1438 	}
1439 
1440 	data->rx_next_buffer = NULL;
1441 	data->rx_next_buffer_len = 0;
1442 
1443 	/* When async rx is disabled, enable interruptible instance of uart to function normally */
1444 	LL_USART_EnableIT_RXNE(usart);
1445 
1446 	LOG_DBG("rx: disabled");
1447 
1448 	async_user_callback(data, &disabled_event);
1449 
1450 	return 0;
1451 }
1452 
uart_stm32_dma_tx_cb(const struct device * dma_dev,void * user_data,uint32_t channel,int status)1453 void uart_stm32_dma_tx_cb(const struct device *dma_dev, void *user_data,
1454 			       uint32_t channel, int status)
1455 {
1456 	const struct device *uart_dev = user_data;
1457 	struct uart_stm32_data *data = uart_dev->data;
1458 	struct dma_status stat;
1459 	unsigned int key = irq_lock();
1460 
1461 	/* Disable TX */
1462 	uart_stm32_dma_tx_disable(uart_dev);
1463 
1464 	(void)k_work_cancel_delayable(&data->dma_tx.timeout_work);
1465 
1466 	if (!dma_get_status(data->dma_tx.dma_dev,
1467 				data->dma_tx.dma_channel, &stat)) {
1468 		data->dma_tx.counter = data->dma_tx.buffer_length -
1469 					stat.pending_length;
1470 	}
1471 
1472 	data->dma_tx.buffer_length = 0;
1473 
1474 	irq_unlock(key);
1475 }
1476 
uart_stm32_dma_replace_buffer(const struct device * dev)1477 static void uart_stm32_dma_replace_buffer(const struct device *dev)
1478 {
1479 	const struct uart_stm32_config *config = dev->config;
1480 	USART_TypeDef *usart = config->usart;
1481 	struct uart_stm32_data *data = dev->data;
1482 
1483 	/* Replace the buffer and reload the DMA */
1484 	LOG_DBG("Replacing RX buffer: %d", data->rx_next_buffer_len);
1485 
1486 	/* reload DMA */
1487 	data->dma_rx.offset = 0;
1488 	data->dma_rx.counter = 0;
1489 	data->dma_rx.buffer = data->rx_next_buffer;
1490 	data->dma_rx.buffer_length = data->rx_next_buffer_len;
1491 	data->dma_rx.blk_cfg.block_size = data->dma_rx.buffer_length;
1492 	data->dma_rx.blk_cfg.dest_address = (uint32_t)data->dma_rx.buffer;
1493 	data->rx_next_buffer = NULL;
1494 	data->rx_next_buffer_len = 0;
1495 
1496 	dma_reload(data->dma_rx.dma_dev, data->dma_rx.dma_channel,
1497 			data->dma_rx.blk_cfg.source_address,
1498 			data->dma_rx.blk_cfg.dest_address,
1499 			data->dma_rx.blk_cfg.block_size);
1500 
1501 	dma_start(data->dma_rx.dma_dev, data->dma_rx.dma_channel);
1502 
1503 	LL_USART_ClearFlag_IDLE(usart);
1504 
1505 	/* Request next buffer */
1506 	async_evt_rx_buf_request(data);
1507 }
1508 
uart_stm32_dma_rx_cb(const struct device * dma_dev,void * user_data,uint32_t channel,int status)1509 void uart_stm32_dma_rx_cb(const struct device *dma_dev, void *user_data,
1510 			       uint32_t channel, int status)
1511 {
1512 	const struct device *uart_dev = user_data;
1513 	struct uart_stm32_data *data = uart_dev->data;
1514 
1515 	if (status < 0) {
1516 		async_evt_rx_err(data, status);
1517 		return;
1518 	}
1519 
1520 	(void)k_work_cancel_delayable(&data->dma_rx.timeout_work);
1521 
1522 	/* true since this functions occurs when buffer if full */
1523 	data->dma_rx.counter = data->dma_rx.buffer_length;
1524 
1525 	async_evt_rx_rdy(data);
1526 
1527 	if (data->rx_next_buffer != NULL) {
1528 		async_evt_rx_buf_release(data);
1529 
1530 		/* replace the buffer when the current
1531 		 * is full and not the same as the next
1532 		 * one.
1533 		 */
1534 		uart_stm32_dma_replace_buffer(uart_dev);
1535 	} else {
1536 		/* Buffer full without valid next buffer,
1537 		 * an UART_RX_DISABLED event must be generated,
1538 		 * but uart_stm32_async_rx_disable() cannot be
1539 		 * called in ISR context. So force the RX timeout
1540 		 * to minimum value and let the RX timeout to do the job.
1541 		 */
1542 		k_work_reschedule(&data->dma_rx.timeout_work, K_TICKS(1));
1543 	}
1544 }
1545 
uart_stm32_async_tx(const struct device * dev,const uint8_t * tx_data,size_t buf_size,int32_t timeout)1546 static int uart_stm32_async_tx(const struct device *dev,
1547 		const uint8_t *tx_data, size_t buf_size, int32_t timeout)
1548 {
1549 	const struct uart_stm32_config *config = dev->config;
1550 	USART_TypeDef *usart = config->usart;
1551 	struct uart_stm32_data *data = dev->data;
1552 	int ret;
1553 
1554 	if (data->dma_tx.dma_dev == NULL) {
1555 		return -ENODEV;
1556 	}
1557 
1558 	if (data->dma_tx.buffer_length != 0) {
1559 		return -EBUSY;
1560 	}
1561 
1562 #ifdef CONFIG_DCACHE
1563 	if (!buf_in_nocache((uintptr_t)tx_data, buf_size)) {
1564 		LOG_ERR("Tx buffer should be placed in a nocache memory region");
1565 		return -EFAULT;
1566 	}
1567 #endif /* CONFIG_DCACHE */
1568 
1569 	data->dma_tx.buffer = (uint8_t *)tx_data;
1570 	data->dma_tx.buffer_length = buf_size;
1571 	data->dma_tx.timeout = timeout;
1572 
1573 	LOG_DBG("tx: l=%d", data->dma_tx.buffer_length);
1574 
1575 	/* Clear TC flag */
1576 	LL_USART_ClearFlag_TC(usart);
1577 
1578 	/* Enable TC interrupt so we can signal correct TX done */
1579 	LL_USART_EnableIT_TC(usart);
1580 
1581 	/* set source address */
1582 	data->dma_tx.blk_cfg.source_address = (uint32_t)data->dma_tx.buffer;
1583 	data->dma_tx.blk_cfg.block_size = data->dma_tx.buffer_length;
1584 
1585 	ret = dma_config(data->dma_tx.dma_dev, data->dma_tx.dma_channel,
1586 				&data->dma_tx.dma_cfg);
1587 
1588 	if (ret != 0) {
1589 		LOG_ERR("dma tx config error!");
1590 		return -EINVAL;
1591 	}
1592 
1593 	if (dma_start(data->dma_tx.dma_dev, data->dma_tx.dma_channel)) {
1594 		LOG_ERR("UART err: TX DMA start failed!");
1595 		return -EFAULT;
1596 	}
1597 
1598 	/* Start TX timer */
1599 	async_timer_start(&data->dma_tx.timeout_work, data->dma_tx.timeout);
1600 
1601 #ifdef CONFIG_PM
1602 
1603 	/* Do not allow system to suspend until transmission has completed */
1604 	uart_stm32_pm_policy_state_lock_get(dev);
1605 #endif
1606 
1607 	/* Enable TX DMA requests */
1608 	uart_stm32_dma_tx_enable(dev);
1609 
1610 	return 0;
1611 }
1612 
uart_stm32_async_rx_enable(const struct device * dev,uint8_t * rx_buf,size_t buf_size,int32_t timeout)1613 static int uart_stm32_async_rx_enable(const struct device *dev,
1614 		uint8_t *rx_buf, size_t buf_size, int32_t timeout)
1615 {
1616 	const struct uart_stm32_config *config = dev->config;
1617 	USART_TypeDef *usart = config->usart;
1618 	struct uart_stm32_data *data = dev->data;
1619 	int ret;
1620 
1621 	if (data->dma_rx.dma_dev == NULL) {
1622 		return -ENODEV;
1623 	}
1624 
1625 	if (data->dma_rx.enabled) {
1626 		LOG_WRN("RX was already enabled");
1627 		return -EBUSY;
1628 	}
1629 
1630 #ifdef CONFIG_DCACHE
1631 	if (!buf_in_nocache((uintptr_t)rx_buf, buf_size)) {
1632 		LOG_ERR("Rx buffer should be placed in a nocache memory region");
1633 		return -EFAULT;
1634 	}
1635 #endif /* CONFIG_DCACHE */
1636 
1637 	data->dma_rx.offset = 0;
1638 	data->dma_rx.buffer = rx_buf;
1639 	data->dma_rx.buffer_length = buf_size;
1640 	data->dma_rx.counter = 0;
1641 	data->dma_rx.timeout = timeout;
1642 
1643 	/* Disable RX interrupts to let DMA to handle it */
1644 	LL_USART_DisableIT_RXNE(usart);
1645 
1646 	data->dma_rx.blk_cfg.block_size = buf_size;
1647 	data->dma_rx.blk_cfg.dest_address = (uint32_t)data->dma_rx.buffer;
1648 
1649 	ret = dma_config(data->dma_rx.dma_dev, data->dma_rx.dma_channel,
1650 				&data->dma_rx.dma_cfg);
1651 
1652 	if (ret != 0) {
1653 		LOG_ERR("UART ERR: RX DMA config failed!");
1654 		return -EINVAL;
1655 	}
1656 
1657 	if (dma_start(data->dma_rx.dma_dev, data->dma_rx.dma_channel)) {
1658 		LOG_ERR("UART ERR: RX DMA start failed!");
1659 		return -EFAULT;
1660 	}
1661 
1662 	/* Flush RX data buffer */
1663 #ifdef USART_SR_RXNE
1664 	LL_USART_ClearFlag_RXNE(usart);
1665 #else
1666 	LL_USART_RequestRxDataFlush(usart);
1667 #endif /* USART_SR_RXNE */
1668 
1669 	/* Enable RX DMA requests */
1670 	uart_stm32_dma_rx_enable(dev);
1671 
1672 	/* Enable IRQ IDLE to define the end of a
1673 	 * RX DMA transaction.
1674 	 */
1675 	LL_USART_ClearFlag_IDLE(usart);
1676 	LL_USART_EnableIT_IDLE(usart);
1677 
1678 	LL_USART_EnableIT_ERROR(usart);
1679 
1680 	/* Request next buffer */
1681 	async_evt_rx_buf_request(data);
1682 
1683 	LOG_DBG("async rx enabled");
1684 
1685 	return ret;
1686 }
1687 
uart_stm32_async_tx_abort(const struct device * dev)1688 static int uart_stm32_async_tx_abort(const struct device *dev)
1689 {
1690 	struct uart_stm32_data *data = dev->data;
1691 	size_t tx_buffer_length = data->dma_tx.buffer_length;
1692 	struct dma_status stat;
1693 
1694 	if (tx_buffer_length == 0) {
1695 		return -EFAULT;
1696 	}
1697 
1698 	(void)k_work_cancel_delayable(&data->dma_tx.timeout_work);
1699 	if (!dma_get_status(data->dma_tx.dma_dev,
1700 				data->dma_tx.dma_channel, &stat)) {
1701 		data->dma_tx.counter = tx_buffer_length - stat.pending_length;
1702 	}
1703 
1704 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32u5_dma)
1705 	dma_suspend(data->dma_tx.dma_dev, data->dma_tx.dma_channel);
1706 #endif
1707 	dma_stop(data->dma_tx.dma_dev, data->dma_tx.dma_channel);
1708 	async_evt_tx_abort(data);
1709 
1710 	return 0;
1711 }
1712 
uart_stm32_async_rx_timeout(struct k_work * work)1713 static void uart_stm32_async_rx_timeout(struct k_work *work)
1714 {
1715 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
1716 	struct uart_dma_stream *rx_stream = CONTAINER_OF(dwork,
1717 			struct uart_dma_stream, timeout_work);
1718 	struct uart_stm32_data *data = CONTAINER_OF(rx_stream,
1719 			struct uart_stm32_data, dma_rx);
1720 	const struct device *dev = data->uart_dev;
1721 
1722 	LOG_DBG("rx timeout");
1723 
1724 	if (data->dma_rx.counter == data->dma_rx.buffer_length) {
1725 		uart_stm32_async_rx_disable(dev);
1726 	} else {
1727 		uart_stm32_dma_rx_flush(dev);
1728 	}
1729 }
1730 
uart_stm32_async_tx_timeout(struct k_work * work)1731 static void uart_stm32_async_tx_timeout(struct k_work *work)
1732 {
1733 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
1734 	struct uart_dma_stream *tx_stream = CONTAINER_OF(dwork,
1735 			struct uart_dma_stream, timeout_work);
1736 	struct uart_stm32_data *data = CONTAINER_OF(tx_stream,
1737 			struct uart_stm32_data, dma_tx);
1738 	const struct device *dev = data->uart_dev;
1739 
1740 	uart_stm32_async_tx_abort(dev);
1741 
1742 	LOG_DBG("tx: async timeout");
1743 }
1744 
uart_stm32_async_rx_buf_rsp(const struct device * dev,uint8_t * buf,size_t len)1745 static int uart_stm32_async_rx_buf_rsp(const struct device *dev, uint8_t *buf,
1746 				       size_t len)
1747 {
1748 	struct uart_stm32_data *data = dev->data;
1749 	unsigned int key;
1750 	int err = 0;
1751 
1752 	LOG_DBG("replace buffer (%d)", len);
1753 
1754 	key = irq_lock();
1755 
1756 	if (data->rx_next_buffer != NULL) {
1757 		err = -EBUSY;
1758 	} else if (!data->dma_rx.enabled) {
1759 		err = -EACCES;
1760 	} else {
1761 #ifdef CONFIG_DCACHE
1762 		if (!buf_in_nocache((uintptr_t)buf, len)) {
1763 			LOG_ERR("Rx buffer should be placed in a nocache memory region");
1764 			return -EFAULT;
1765 		}
1766 #endif /* CONFIG_DCACHE */
1767 		data->rx_next_buffer = buf;
1768 		data->rx_next_buffer_len = len;
1769 	}
1770 
1771 	irq_unlock(key);
1772 
1773 	return err;
1774 }
1775 
uart_stm32_async_init(const struct device * dev)1776 static int uart_stm32_async_init(const struct device *dev)
1777 {
1778 	const struct uart_stm32_config *config = dev->config;
1779 	USART_TypeDef *usart = config->usart;
1780 	struct uart_stm32_data *data = dev->data;
1781 
1782 	data->uart_dev = dev;
1783 
1784 	if (data->dma_rx.dma_dev != NULL) {
1785 		if (!device_is_ready(data->dma_rx.dma_dev)) {
1786 			return -ENODEV;
1787 		}
1788 	}
1789 
1790 	if (data->dma_tx.dma_dev != NULL) {
1791 		if (!device_is_ready(data->dma_tx.dma_dev)) {
1792 			return -ENODEV;
1793 		}
1794 	}
1795 
1796 	/* Disable both TX and RX DMA requests */
1797 	uart_stm32_dma_rx_disable(dev);
1798 	uart_stm32_dma_tx_disable(dev);
1799 
1800 	k_work_init_delayable(&data->dma_rx.timeout_work,
1801 			    uart_stm32_async_rx_timeout);
1802 	k_work_init_delayable(&data->dma_tx.timeout_work,
1803 			    uart_stm32_async_tx_timeout);
1804 
1805 	/* Configure dma rx config */
1806 	memset(&data->dma_rx.blk_cfg, 0, sizeof(data->dma_rx.blk_cfg));
1807 
1808 #if defined(CONFIG_SOC_SERIES_STM32F1X) || \
1809 	defined(CONFIG_SOC_SERIES_STM32F2X) || \
1810 	defined(CONFIG_SOC_SERIES_STM32F4X) || \
1811 	defined(CONFIG_SOC_SERIES_STM32L1X)
1812 	data->dma_rx.blk_cfg.source_address =
1813 				LL_USART_DMA_GetRegAddr(usart);
1814 #else
1815 	data->dma_rx.blk_cfg.source_address =
1816 				LL_USART_DMA_GetRegAddr(usart,
1817 						LL_USART_DMA_REG_DATA_RECEIVE);
1818 #endif
1819 
1820 	data->dma_rx.blk_cfg.dest_address = 0; /* dest not ready */
1821 
1822 	if (data->dma_rx.src_addr_increment) {
1823 		data->dma_rx.blk_cfg.source_addr_adj = DMA_ADDR_ADJ_INCREMENT;
1824 	} else {
1825 		data->dma_rx.blk_cfg.source_addr_adj = DMA_ADDR_ADJ_NO_CHANGE;
1826 	}
1827 
1828 	if (data->dma_rx.dst_addr_increment) {
1829 		data->dma_rx.blk_cfg.dest_addr_adj = DMA_ADDR_ADJ_INCREMENT;
1830 	} else {
1831 		data->dma_rx.blk_cfg.dest_addr_adj = DMA_ADDR_ADJ_NO_CHANGE;
1832 	}
1833 
1834 	/* RX disable circular buffer */
1835 	data->dma_rx.blk_cfg.source_reload_en  = 0;
1836 	data->dma_rx.blk_cfg.dest_reload_en = 0;
1837 	data->dma_rx.blk_cfg.fifo_mode_control = data->dma_rx.fifo_threshold;
1838 
1839 	data->dma_rx.dma_cfg.head_block = &data->dma_rx.blk_cfg;
1840 	data->dma_rx.dma_cfg.user_data = (void *)dev;
1841 	data->rx_next_buffer = NULL;
1842 	data->rx_next_buffer_len = 0;
1843 
1844 	/* Configure dma tx config */
1845 	memset(&data->dma_tx.blk_cfg, 0, sizeof(data->dma_tx.blk_cfg));
1846 
1847 #if defined(CONFIG_SOC_SERIES_STM32F1X) || \
1848 	defined(CONFIG_SOC_SERIES_STM32F2X) || \
1849 	defined(CONFIG_SOC_SERIES_STM32F4X) || \
1850 	defined(CONFIG_SOC_SERIES_STM32L1X)
1851 	data->dma_tx.blk_cfg.dest_address =
1852 			LL_USART_DMA_GetRegAddr(usart);
1853 #else
1854 	data->dma_tx.blk_cfg.dest_address =
1855 			LL_USART_DMA_GetRegAddr(usart,
1856 					LL_USART_DMA_REG_DATA_TRANSMIT);
1857 #endif
1858 
1859 	data->dma_tx.blk_cfg.source_address = 0; /* not ready */
1860 
1861 	if (data->dma_tx.src_addr_increment) {
1862 		data->dma_tx.blk_cfg.source_addr_adj = DMA_ADDR_ADJ_INCREMENT;
1863 	} else {
1864 		data->dma_tx.blk_cfg.source_addr_adj = DMA_ADDR_ADJ_NO_CHANGE;
1865 	}
1866 
1867 	if (data->dma_tx.dst_addr_increment) {
1868 		data->dma_tx.blk_cfg.dest_addr_adj = DMA_ADDR_ADJ_INCREMENT;
1869 	} else {
1870 		data->dma_tx.blk_cfg.dest_addr_adj = DMA_ADDR_ADJ_NO_CHANGE;
1871 	}
1872 
1873 	data->dma_tx.blk_cfg.fifo_mode_control = data->dma_tx.fifo_threshold;
1874 
1875 	data->dma_tx.dma_cfg.head_block = &data->dma_tx.blk_cfg;
1876 	data->dma_tx.dma_cfg.user_data = (void *)dev;
1877 
1878 	return 0;
1879 }
1880 
1881 #ifdef CONFIG_UART_WIDE_DATA
1882 
uart_stm32_async_tx_u16(const struct device * dev,const uint16_t * tx_data,size_t buf_size,int32_t timeout)1883 static int uart_stm32_async_tx_u16(const struct device *dev, const uint16_t *tx_data,
1884 				   size_t buf_size, int32_t timeout)
1885 {
1886 	return uart_stm32_async_tx(dev, (const uint8_t *)tx_data, buf_size * 2, timeout);
1887 }
1888 
uart_stm32_async_rx_enable_u16(const struct device * dev,uint16_t * buf,size_t len,int32_t timeout)1889 static int uart_stm32_async_rx_enable_u16(const struct device *dev, uint16_t *buf, size_t len,
1890 					  int32_t timeout)
1891 {
1892 	return uart_stm32_async_rx_enable(dev, (uint8_t *)buf, len * 2, timeout);
1893 }
1894 
uart_stm32_async_rx_buf_rsp_u16(const struct device * dev,uint16_t * buf,size_t len)1895 static int uart_stm32_async_rx_buf_rsp_u16(const struct device *dev, uint16_t *buf, size_t len)
1896 {
1897 	return uart_stm32_async_rx_buf_rsp(dev, (uint8_t *)buf, len * 2);
1898 }
1899 
1900 #endif
1901 
1902 #endif /* CONFIG_UART_ASYNC_API */
1903 
1904 static const struct uart_driver_api uart_stm32_driver_api = {
1905 	.poll_in = uart_stm32_poll_in,
1906 	.poll_out = uart_stm32_poll_out,
1907 #ifdef CONFIG_UART_WIDE_DATA
1908 	.poll_in_u16 = uart_stm32_poll_in_u16,
1909 	.poll_out_u16 = uart_stm32_poll_out_u16,
1910 #endif
1911 	.err_check = uart_stm32_err_check,
1912 #ifdef CONFIG_UART_USE_RUNTIME_CONFIGURE
1913 	.configure = uart_stm32_configure,
1914 	.config_get = uart_stm32_config_get,
1915 #endif /* CONFIG_UART_USE_RUNTIME_CONFIGURE */
1916 #ifdef CONFIG_UART_INTERRUPT_DRIVEN
1917 	.fifo_fill = uart_stm32_fifo_fill,
1918 	.fifo_read = uart_stm32_fifo_read,
1919 #ifdef CONFIG_UART_WIDE_DATA
1920 	.fifo_fill_u16 = uart_stm32_fifo_fill_u16,
1921 	.fifo_read_u16 = uart_stm32_fifo_read_u16,
1922 #endif
1923 	.irq_tx_enable = uart_stm32_irq_tx_enable,
1924 	.irq_tx_disable = uart_stm32_irq_tx_disable,
1925 	.irq_tx_ready = uart_stm32_irq_tx_ready,
1926 	.irq_tx_complete = uart_stm32_irq_tx_complete,
1927 	.irq_rx_enable = uart_stm32_irq_rx_enable,
1928 	.irq_rx_disable = uart_stm32_irq_rx_disable,
1929 	.irq_rx_ready = uart_stm32_irq_rx_ready,
1930 	.irq_err_enable = uart_stm32_irq_err_enable,
1931 	.irq_err_disable = uart_stm32_irq_err_disable,
1932 	.irq_is_pending = uart_stm32_irq_is_pending,
1933 	.irq_update = uart_stm32_irq_update,
1934 	.irq_callback_set = uart_stm32_irq_callback_set,
1935 #endif /* CONFIG_UART_INTERRUPT_DRIVEN */
1936 #ifdef CONFIG_UART_ASYNC_API
1937 	.callback_set = uart_stm32_async_callback_set,
1938 	.tx = uart_stm32_async_tx,
1939 	.tx_abort = uart_stm32_async_tx_abort,
1940 	.rx_enable = uart_stm32_async_rx_enable,
1941 	.rx_disable = uart_stm32_async_rx_disable,
1942 	.rx_buf_rsp = uart_stm32_async_rx_buf_rsp,
1943 #ifdef CONFIG_UART_WIDE_DATA
1944 	.tx_u16 = uart_stm32_async_tx_u16,
1945 	.rx_enable_u16 = uart_stm32_async_rx_enable_u16,
1946 	.rx_buf_rsp_u16 = uart_stm32_async_rx_buf_rsp_u16,
1947 #endif
1948 #endif /* CONFIG_UART_ASYNC_API */
1949 };
1950 
uart_stm32_clocks_enable(const struct device * dev)1951 static int uart_stm32_clocks_enable(const struct device *dev)
1952 {
1953 	const struct uart_stm32_config *config = dev->config;
1954 	struct uart_stm32_data *data = dev->data;
1955 	int err;
1956 
1957 	__uart_stm32_get_clock(dev);
1958 
1959 	if (!device_is_ready(data->clock)) {
1960 		LOG_ERR("clock control device not ready");
1961 		return -ENODEV;
1962 	}
1963 
1964 	/* enable clock */
1965 	err = clock_control_on(data->clock, (clock_control_subsys_t)&config->pclken[0]);
1966 	if (err != 0) {
1967 		LOG_ERR("Could not enable (LP)UART clock");
1968 		return err;
1969 	}
1970 
1971 	if (IS_ENABLED(STM32_UART_DOMAIN_CLOCK_SUPPORT) && (config->pclk_len > 1)) {
1972 		err = clock_control_configure(DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE),
1973 					      (clock_control_subsys_t) &config->pclken[1],
1974 					      NULL);
1975 		if (err != 0) {
1976 			LOG_ERR("Could not select UART domain clock");
1977 			return err;
1978 		}
1979 	}
1980 
1981 	return 0;
1982 }
1983 
uart_stm32_registers_configure(const struct device * dev)1984 static int uart_stm32_registers_configure(const struct device *dev)
1985 {
1986 	const struct uart_stm32_config *config = dev->config;
1987 	USART_TypeDef *usart = config->usart;
1988 	struct uart_stm32_data *data = dev->data;
1989 	struct uart_config *uart_cfg = data->uart_cfg;
1990 
1991 	LL_USART_Disable(usart);
1992 
1993 	if (!device_is_ready(config->reset.dev)) {
1994 		LOG_ERR("reset controller not ready");
1995 		return -ENODEV;
1996 	}
1997 
1998 	/* Reset UART to default state using RCC */
1999 	(void)reset_line_toggle_dt(&config->reset);
2000 
2001 	/* TX/RX direction */
2002 	LL_USART_SetTransferDirection(usart, LL_USART_DIRECTION_TX_RX);
2003 
2004 	/* Set basic parameters, such as data-/stop-bit, parity, and baudrate */
2005 	uart_stm32_parameters_set(dev, uart_cfg);
2006 
2007 	/* Enable the single wire / half-duplex mode */
2008 	if (config->single_wire) {
2009 		LL_USART_EnableHalfDuplex(usart);
2010 	}
2011 
2012 #ifdef LL_USART_TXRX_SWAPPED
2013 	if (config->tx_rx_swap) {
2014 		LL_USART_SetTXRXSwap(usart, LL_USART_TXRX_SWAPPED);
2015 	}
2016 #endif
2017 
2018 #ifdef LL_USART_RXPIN_LEVEL_INVERTED
2019 	if (config->rx_invert) {
2020 		LL_USART_SetRXPinLevel(usart, LL_USART_RXPIN_LEVEL_INVERTED);
2021 	}
2022 #endif
2023 
2024 #ifdef LL_USART_TXPIN_LEVEL_INVERTED
2025 	if (config->tx_invert) {
2026 		LL_USART_SetTXPinLevel(usart, LL_USART_TXPIN_LEVEL_INVERTED);
2027 	}
2028 #endif
2029 
2030 #if HAS_DRIVER_ENABLE
2031 	if (config->de_enable) {
2032 		if (!IS_UART_DRIVER_ENABLE_INSTANCE(usart)) {
2033 			LOG_ERR("%s does not support driver enable", dev->name);
2034 			return -EINVAL;
2035 		}
2036 
2037 		uart_stm32_set_driver_enable(dev, true);
2038 		LL_USART_SetDEAssertionTime(usart, config->de_assert_time);
2039 		LL_USART_SetDEDeassertionTime(usart, config->de_deassert_time);
2040 
2041 		if (config->de_invert) {
2042 			LL_USART_SetDESignalPolarity(usart, LL_USART_DE_POLARITY_LOW);
2043 		}
2044 	}
2045 #endif
2046 
2047 #ifdef USART_CR1_FIFOEN
2048 	if (config->fifo_enable) {
2049 		LL_USART_EnableFIFO(usart);
2050 	}
2051 #endif
2052 
2053 #if defined(CONFIG_PM) && defined(IS_UART_WAKEUP_FROMSTOP_INSTANCE)
2054 	if (config->wakeup_source) {
2055 		/* Enable ability to wakeup device in Stop mode
2056 		 * Effect depends on CONFIG_PM_DEVICE status:
2057 		 * CONFIG_PM_DEVICE=n : Always active
2058 		 * CONFIG_PM_DEVICE=y : Controlled by pm_device_wakeup_enable()
2059 		 */
2060 #ifdef USART_CR3_WUFIE
2061 		LL_USART_SetWKUPType(usart, LL_USART_WAKEUP_ON_RXNE);
2062 		LL_USART_EnableIT_WKUP(usart);
2063 		LL_USART_ClearFlag_WKUP(usart);
2064 #endif
2065 		LL_USART_EnableInStopMode(usart);
2066 
2067 		if (config->wakeup_line != STM32_EXTI_LINE_NONE) {
2068 			/* Prepare the WAKEUP with the expected EXTI line */
2069 			LL_EXTI_EnableIT_0_31(BIT(config->wakeup_line));
2070 		}
2071 	}
2072 #endif /* CONFIG_PM */
2073 
2074 	LL_USART_Enable(usart);
2075 
2076 #ifdef USART_ISR_TEACK
2077 	/* Wait until TEACK flag is set */
2078 	while (!(LL_USART_IsActiveFlag_TEACK(usart))) {
2079 	}
2080 #endif /* !USART_ISR_TEACK */
2081 
2082 #ifdef USART_ISR_REACK
2083 	/* Wait until REACK flag is set */
2084 	while (!(LL_USART_IsActiveFlag_REACK(usart))) {
2085 	}
2086 #endif /* !USART_ISR_REACK */
2087 
2088 	return 0;
2089 }
2090 
2091 /**
2092  * @brief Initialize UART channel
2093  *
2094  * This routine is called to reset the chip in a quiescent state.
2095  * It is assumed that this function is called only once per UART.
2096  *
2097  * @param dev UART device struct
2098  *
2099  * @return 0
2100  */
uart_stm32_init(const struct device * dev)2101 static int uart_stm32_init(const struct device *dev)
2102 {
2103 	const struct uart_stm32_config *config = dev->config;
2104 	int err;
2105 
2106 	err = uart_stm32_clocks_enable(dev);
2107 	if (err < 0) {
2108 		return err;
2109 	}
2110 
2111 	/* Configure dt provided device signals when available */
2112 	err = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
2113 	if (err < 0) {
2114 		return err;
2115 	}
2116 
2117 	err = uart_stm32_registers_configure(dev);
2118 	if (err < 0) {
2119 		return err;
2120 	}
2121 
2122 #if defined(CONFIG_PM) || \
2123 	defined(CONFIG_UART_INTERRUPT_DRIVEN) || \
2124 	defined(CONFIG_UART_ASYNC_API)
2125 	config->irq_config_func(dev);
2126 #endif /* CONFIG_PM || CONFIG_UART_INTERRUPT_DRIVEN || CONFIG_UART_ASYNC_API */
2127 
2128 #ifdef CONFIG_UART_ASYNC_API
2129 	return uart_stm32_async_init(dev);
2130 #else
2131 	return 0;
2132 #endif
2133 }
2134 
2135 #ifdef CONFIG_PM_DEVICE
uart_stm32_suspend_setup(const struct device * dev)2136 static void uart_stm32_suspend_setup(const struct device *dev)
2137 {
2138 	const struct uart_stm32_config *config = dev->config;
2139 	USART_TypeDef *usart = config->usart;
2140 
2141 #ifdef USART_ISR_BUSY
2142 	/* Make sure that no USART transfer is on-going */
2143 	while (LL_USART_IsActiveFlag_BUSY(usart) == 1) {
2144 	}
2145 #endif
2146 	while (LL_USART_IsActiveFlag_TC(usart) == 0) {
2147 	}
2148 #ifdef USART_ISR_REACK
2149 	/* Make sure that USART is ready for reception */
2150 	while (LL_USART_IsActiveFlag_REACK(usart) == 0) {
2151 	}
2152 #endif
2153 	/* Clear OVERRUN flag */
2154 	LL_USART_ClearFlag_ORE(usart);
2155 }
2156 
uart_stm32_pm_action(const struct device * dev,enum pm_device_action action)2157 static int uart_stm32_pm_action(const struct device *dev,
2158 			       enum pm_device_action action)
2159 {
2160 	const struct uart_stm32_config *config = dev->config;
2161 	struct uart_stm32_data *data = dev->data;
2162 	int err;
2163 
2164 
2165 	switch (action) {
2166 	case PM_DEVICE_ACTION_RESUME:
2167 		/* Set pins to active state */
2168 		err = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
2169 		if (err < 0) {
2170 			return err;
2171 		}
2172 
2173 		/* Enable clock */
2174 		err = clock_control_on(data->clock,
2175 					(clock_control_subsys_t)&config->pclken[0]);
2176 		if (err < 0) {
2177 			LOG_ERR("Could not enable (LP)UART clock");
2178 			return err;
2179 		}
2180 
2181 		if ((IS_ENABLED(CONFIG_PM_S2RAM)) &&
2182 			(!LL_USART_IsEnabled(config->usart))) {
2183 			/* When exiting low power mode, check whether UART is enabled.
2184 			 * If not, it means we are exiting Suspend to RAM mode (STM32
2185 			 * Standby), and the driver needs to be reinitialized.
2186 			 */
2187 			uart_stm32_init(dev);
2188 		}
2189 		break;
2190 	case PM_DEVICE_ACTION_SUSPEND:
2191 		uart_stm32_suspend_setup(dev);
2192 		/* Stop device clock. Note: fixed clocks are not handled yet. */
2193 		err = clock_control_off(data->clock, (clock_control_subsys_t)&config->pclken[0]);
2194 		if (err < 0) {
2195 			LOG_ERR("Could not enable (LP)UART clock");
2196 			return err;
2197 		}
2198 
2199 		/* Move pins to sleep state */
2200 		err = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_SLEEP);
2201 		if ((err < 0) && (err != -ENOENT)) {
2202 			/*
2203 			 * If returning -ENOENT, no pins where defined for sleep mode :
2204 			 * Do not output on console (might sleep already) when going to sleep,
2205 			 * "(LP)UART pinctrl sleep state not available"
2206 			 * and don't block PM suspend.
2207 			 * Else return the error.
2208 			 */
2209 			return err;
2210 		}
2211 		break;
2212 	default:
2213 		return -ENOTSUP;
2214 	}
2215 
2216 	return 0;
2217 }
2218 #endif /* CONFIG_PM_DEVICE */
2219 
2220 #ifdef CONFIG_UART_ASYNC_API
2221 
2222 /* src_dev and dest_dev should be 'MEMORY' or 'PERIPHERAL'. */
2223 #define UART_DMA_CHANNEL_INIT(index, dir, dir_cap, src_dev, dest_dev)	\
2224 	.dma_dev = DEVICE_DT_GET(STM32_DMA_CTLR(index, dir)),			\
2225 	.dma_channel = DT_INST_DMAS_CELL_BY_NAME(index, dir, channel),	\
2226 	.dma_cfg = {							\
2227 		.dma_slot = STM32_DMA_SLOT(index, dir, slot),\
2228 		.channel_direction = STM32_DMA_CONFIG_DIRECTION(	\
2229 					STM32_DMA_CHANNEL_CONFIG(index, dir)),\
2230 		.channel_priority = STM32_DMA_CONFIG_PRIORITY(		\
2231 				STM32_DMA_CHANNEL_CONFIG(index, dir)),	\
2232 		.source_data_size = STM32_DMA_CONFIG_##src_dev##_DATA_SIZE(\
2233 					STM32_DMA_CHANNEL_CONFIG(index, dir)),\
2234 		.dest_data_size = STM32_DMA_CONFIG_##dest_dev##_DATA_SIZE(\
2235 				STM32_DMA_CHANNEL_CONFIG(index, dir)),\
2236 		.source_burst_length = 1, /* SINGLE transfer */		\
2237 		.dest_burst_length = 1,					\
2238 		.block_count = 1,					\
2239 		.dma_callback = uart_stm32_dma_##dir##_cb,		\
2240 	},								\
2241 	.src_addr_increment = STM32_DMA_CONFIG_##src_dev##_ADDR_INC(	\
2242 				STM32_DMA_CHANNEL_CONFIG(index, dir)),	\
2243 	.dst_addr_increment = STM32_DMA_CONFIG_##dest_dev##_ADDR_INC(	\
2244 				STM32_DMA_CHANNEL_CONFIG(index, dir)),	\
2245 	.fifo_threshold = STM32_DMA_FEATURES_FIFO_THRESHOLD(		\
2246 				STM32_DMA_FEATURES(index, dir)),		\
2247 
2248 #endif
2249 
2250 #if defined(CONFIG_UART_INTERRUPT_DRIVEN) || defined(CONFIG_UART_ASYNC_API) || \
2251 	defined(CONFIG_PM)
2252 #define STM32_UART_IRQ_HANDLER_DECL(index)				\
2253 	static void uart_stm32_irq_config_func_##index(const struct device *dev);
2254 #define STM32_UART_IRQ_HANDLER(index)					\
2255 static void uart_stm32_irq_config_func_##index(const struct device *dev)	\
2256 {									\
2257 	IRQ_CONNECT(DT_INST_IRQN(index),				\
2258 		DT_INST_IRQ(index, priority),				\
2259 		uart_stm32_isr, DEVICE_DT_INST_GET(index),		\
2260 		0);							\
2261 	irq_enable(DT_INST_IRQN(index));				\
2262 }
2263 #else
2264 #define STM32_UART_IRQ_HANDLER_DECL(index) /* Not used */
2265 #define STM32_UART_IRQ_HANDLER(index) /* Not used */
2266 #endif
2267 
2268 #if defined(CONFIG_UART_INTERRUPT_DRIVEN) || defined(CONFIG_UART_ASYNC_API) || \
2269 	defined(CONFIG_PM)
2270 #define STM32_UART_IRQ_HANDLER_FUNC(index)				\
2271 	.irq_config_func = uart_stm32_irq_config_func_##index,
2272 #else
2273 #define STM32_UART_IRQ_HANDLER_FUNC(index) /* Not used */
2274 #endif
2275 
2276 #ifdef CONFIG_UART_ASYNC_API
2277 #define UART_DMA_CHANNEL(index, dir, DIR, src, dest)			\
2278 .dma_##dir = {								\
2279 	COND_CODE_1(DT_INST_DMAS_HAS_NAME(index, dir),			\
2280 		 (UART_DMA_CHANNEL_INIT(index, dir, DIR, src, dest)),	\
2281 		 (NULL))						\
2282 	},
2283 
2284 #else
2285 #define UART_DMA_CHANNEL(index, dir, DIR, src, dest)
2286 #endif
2287 
2288 #ifdef CONFIG_PM
2289 #define STM32_UART_PM_WAKEUP(index)						\
2290 	.wakeup_source = DT_INST_PROP(index, wakeup_source),			\
2291 	.wakeup_line = COND_CODE_1(DT_INST_NODE_HAS_PROP(index, wakeup_line),	\
2292 			(DT_INST_PROP(index, wakeup_line)),			\
2293 			(STM32_EXTI_LINE_NONE)),
2294 #else
2295 #define STM32_UART_PM_WAKEUP(index) /* Not used */
2296 #endif
2297 
2298 /* Ensure DTS doesn't present an incompatible parity configuration.
2299  * Mark/space parity isn't supported on the STM32 family.
2300  * If 9 data bits are configured, ensure that a parity bit isn't set.
2301  */
2302 #define STM32_UART_CHECK_DT_PARITY(index)				\
2303 BUILD_ASSERT(								\
2304 	!(DT_INST_ENUM_IDX_OR(index, parity, STM32_UART_DEFAULT_PARITY)	\
2305 					== UART_CFG_PARITY_MARK ||	\
2306 	DT_INST_ENUM_IDX_OR(index, parity, STM32_UART_DEFAULT_PARITY)	\
2307 					== UART_CFG_PARITY_SPACE),	\
2308 	"Node " DT_NODE_PATH(DT_DRV_INST(index))			\
2309 	" has unsupported parity configuration");			\
2310 BUILD_ASSERT(								\
2311 	!(DT_INST_ENUM_IDX_OR(index, parity, STM32_UART_DEFAULT_PARITY)	\
2312 					!= UART_CFG_PARITY_NONE	&&	\
2313 	DT_INST_ENUM_IDX_OR(index, data_bits,				\
2314 			    STM32_UART_DEFAULT_DATA_BITS)		\
2315 					== UART_CFG_DATA_BITS_9),	\
2316 	"Node " DT_NODE_PATH(DT_DRV_INST(index))			\
2317 		" has unsupported parity + data bits combination");
2318 
2319 /* Ensure DTS doesn't present an incompatible data bits configuration
2320  * The STM32 family doesn't support 5 data bits, or 6 data bits without parity.
2321  * Only some series support 7 data bits.
2322  */
2323 #ifdef LL_USART_DATAWIDTH_7B
2324 #define STM32_UART_CHECK_DT_DATA_BITS(index)				\
2325 BUILD_ASSERT(								\
2326 	!(DT_INST_ENUM_IDX_OR(index, data_bits,				\
2327 			      STM32_UART_DEFAULT_DATA_BITS)		\
2328 					== UART_CFG_DATA_BITS_5 ||	\
2329 		(DT_INST_ENUM_IDX_OR(index, data_bits,			\
2330 				    STM32_UART_DEFAULT_DATA_BITS)	\
2331 					== UART_CFG_DATA_BITS_6 &&	\
2332 		DT_INST_ENUM_IDX_OR(index, parity,			\
2333 				    STM32_UART_DEFAULT_PARITY)		\
2334 					== UART_CFG_PARITY_NONE)),	\
2335 	"Node " DT_NODE_PATH(DT_DRV_INST(index))			\
2336 		" has unsupported data bits configuration");
2337 #else
2338 #define STM32_UART_CHECK_DT_DATA_BITS(index)				\
2339 BUILD_ASSERT(								\
2340 	!(DT_INST_ENUM_IDX_OR(index, data_bits,				\
2341 			      STM32_UART_DEFAULT_DATA_BITS)		\
2342 					== UART_CFG_DATA_BITS_5 ||	\
2343 	DT_INST_ENUM_IDX_OR(index, data_bits,				\
2344 			    STM32_UART_DEFAULT_DATA_BITS)		\
2345 					== UART_CFG_DATA_BITS_6 ||	\
2346 		(DT_INST_ENUM_IDX_OR(index, data_bits,			\
2347 			    STM32_UART_DEFAULT_DATA_BITS)		\
2348 					== UART_CFG_DATA_BITS_7 &&	\
2349 		DT_INST_ENUM_IDX_OR(index, parity,			\
2350 				    STM32_UART_DEFAULT_PARITY)		\
2351 					== UART_CFG_PARITY_NONE)),	\
2352 	"Node " DT_NODE_PATH(DT_DRV_INST(index))			\
2353 		" has unsupported data bits configuration");
2354 #endif
2355 
2356 /* Ensure DTS doesn't present an incompatible stop bits configuration.
2357  * Some STM32 series USARTs don't support 0.5 stop bits, and it generally isn't
2358  * supported for LPUART.
2359  */
2360 #ifndef LL_USART_STOPBITS_0_5
2361 #define STM32_UART_CHECK_DT_STOP_BITS_0_5(index)			\
2362 BUILD_ASSERT(								\
2363 	!(DT_INST_ENUM_IDX_OR(index, stop_bits,				\
2364 			      STM32_UART_DEFAULT_STOP_BITS)		\
2365 					== UART_CFG_STOP_BITS_0_5),	\
2366 	"Node " DT_NODE_PATH(DT_DRV_INST(index))			\
2367 		" has unsupported stop bits configuration");
2368 /* LPUARTs don't support 0.5 stop bits configurations */
2369 #else
2370 #define STM32_UART_CHECK_DT_STOP_BITS_0_5(index)			\
2371 BUILD_ASSERT(								\
2372 	!(DT_HAS_COMPAT_STATUS_OKAY(st_stm32_lpuart) &&			\
2373 	  DT_INST_ENUM_IDX_OR(index, stop_bits,				\
2374 			      STM32_UART_DEFAULT_STOP_BITS)		\
2375 					== UART_CFG_STOP_BITS_0_5),	\
2376 	"Node " DT_NODE_PATH(DT_DRV_INST(index))			\
2377 		" has unsupported stop bits configuration");
2378 #endif
2379 
2380 /* Ensure DTS doesn't present an incompatible stop bits configuration.
2381  * Some STM32 series USARTs don't support 1.5 stop bits, and it generally isn't
2382  * supported for LPUART.
2383  */
2384 #ifndef LL_USART_STOPBITS_1_5
2385 #define STM32_UART_CHECK_DT_STOP_BITS_1_5(index)			\
2386 BUILD_ASSERT(								\
2387 	DT_INST_ENUM_IDX_OR(index, stop_bits,				\
2388 			    STM32_UART_DEFAULT_STOP_BITS)		\
2389 					!= UART_CFG_STOP_BITS_1_5,	\
2390 	"Node " DT_NODE_PATH(DT_DRV_INST(index))			\
2391 		" has unsupported stop bits configuration");
2392 /* LPUARTs don't support 1.5 stop bits configurations */
2393 #else
2394 #define STM32_UART_CHECK_DT_STOP_BITS_1_5(index)			\
2395 BUILD_ASSERT(								\
2396 	!(DT_HAS_COMPAT_STATUS_OKAY(st_stm32_lpuart) &&			\
2397 	  DT_INST_ENUM_IDX_OR(index, stop_bits,				\
2398 			      STM32_UART_DEFAULT_STOP_BITS)		\
2399 					== UART_CFG_STOP_BITS_1_5),	\
2400 	"Node " DT_NODE_PATH(DT_DRV_INST(index))			\
2401 		" has unsupported stop bits configuration");
2402 #endif
2403 
2404 #define STM32_UART_INIT(index)						\
2405 STM32_UART_IRQ_HANDLER_DECL(index)					\
2406 									\
2407 PINCTRL_DT_INST_DEFINE(index);						\
2408 									\
2409 static const struct stm32_pclken pclken_##index[] =			\
2410 					    STM32_DT_INST_CLOCKS(index);\
2411 									\
2412 static struct uart_config uart_cfg_##index = {				\
2413 	.baudrate  = DT_INST_PROP_OR(index, current_speed,		\
2414 				     STM32_UART_DEFAULT_BAUDRATE),	\
2415 	.parity    = DT_INST_ENUM_IDX_OR(index, parity,			\
2416 					 STM32_UART_DEFAULT_PARITY),	\
2417 	.stop_bits = DT_INST_ENUM_IDX_OR(index, stop_bits,		\
2418 					 STM32_UART_DEFAULT_STOP_BITS),	\
2419 	.data_bits = DT_INST_ENUM_IDX_OR(index, data_bits,		\
2420 					 STM32_UART_DEFAULT_DATA_BITS),	\
2421 	.flow_ctrl = DT_INST_PROP(index, hw_flow_control)		\
2422 					? UART_CFG_FLOW_CTRL_RTS_CTS	\
2423 					: UART_CFG_FLOW_CTRL_NONE,	\
2424 };									\
2425 									\
2426 static const struct uart_stm32_config uart_stm32_cfg_##index = {	\
2427 	.usart = (USART_TypeDef *)DT_INST_REG_ADDR(index),		\
2428 	.reset = RESET_DT_SPEC_GET(DT_DRV_INST(index)),			\
2429 	.pclken = pclken_##index,					\
2430 	.pclk_len = DT_INST_NUM_CLOCKS(index),				\
2431 	.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(index),			\
2432 	.single_wire = DT_INST_PROP(index, single_wire),		\
2433 	.tx_rx_swap = DT_INST_PROP(index, tx_rx_swap),			\
2434 	.rx_invert = DT_INST_PROP(index, rx_invert),			\
2435 	.tx_invert = DT_INST_PROP(index, tx_invert),			\
2436 	.de_enable = DT_INST_PROP(index, de_enable),			\
2437 	.de_assert_time = DT_INST_PROP(index, de_assert_time),		\
2438 	.de_deassert_time = DT_INST_PROP(index, de_deassert_time),	\
2439 	.de_invert = DT_INST_PROP(index, de_invert),			\
2440 	.fifo_enable = DT_INST_PROP(index, fifo_enable),		\
2441 	STM32_UART_IRQ_HANDLER_FUNC(index)				\
2442 	STM32_UART_PM_WAKEUP(index)					\
2443 };									\
2444 									\
2445 static struct uart_stm32_data uart_stm32_data_##index = {		\
2446 	.uart_cfg = &uart_cfg_##index,					\
2447 	UART_DMA_CHANNEL(index, rx, RX, PERIPHERAL, MEMORY)		\
2448 	UART_DMA_CHANNEL(index, tx, TX, MEMORY, PERIPHERAL)		\
2449 };									\
2450 									\
2451 PM_DEVICE_DT_INST_DEFINE(index, uart_stm32_pm_action);			\
2452 									\
2453 DEVICE_DT_INST_DEFINE(index,						\
2454 		    uart_stm32_init,					\
2455 		    PM_DEVICE_DT_INST_GET(index),			\
2456 		    &uart_stm32_data_##index, &uart_stm32_cfg_##index,	\
2457 		    PRE_KERNEL_1, CONFIG_SERIAL_INIT_PRIORITY,		\
2458 		    &uart_stm32_driver_api);				\
2459 									\
2460 STM32_UART_IRQ_HANDLER(index)						\
2461 									\
2462 STM32_UART_CHECK_DT_PARITY(index)					\
2463 STM32_UART_CHECK_DT_DATA_BITS(index)					\
2464 STM32_UART_CHECK_DT_STOP_BITS_0_5(index)				\
2465 STM32_UART_CHECK_DT_STOP_BITS_1_5(index)
2466 
2467 DT_INST_FOREACH_STATUS_OKAY(STM32_UART_INIT)
2468