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