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