1 /*
2  * Copyright (c) 2023 Linaro Limited
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file  udc_stm32.c
9  * @brief STM32 USB device controller (UDC) driver
10  */
11 
12 #include <soc.h>
13 #include <stm32_ll_bus.h>
14 #include <stm32_ll_pwr.h>
15 #include <stm32_ll_rcc.h>
16 #include <stm32_ll_system.h>
17 #include <string.h>
18 #include <zephyr/irq.h>
19 #include <zephyr/drivers/gpio.h>
20 #include <zephyr/drivers/pinctrl.h>
21 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
22 #include <zephyr/sys/util.h>
23 
24 #include "udc_common.h"
25 
26 #include <zephyr/logging/log.h>
27 LOG_MODULE_REGISTER(udc_stm32, CONFIG_UDC_DRIVER_LOG_LEVEL);
28 
29 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs)
30 #define DT_DRV_COMPAT st_stm32_otghs
31 #define UDC_STM32_IRQ_NAME     otghs
32 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otgfs)
33 #define DT_DRV_COMPAT st_stm32_otgfs
34 #define UDC_STM32_IRQ_NAME     otgfs
35 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_usb)
36 #define DT_DRV_COMPAT st_stm32_usb
37 #define UDC_STM32_IRQ_NAME     usb
38 #endif
39 
40 #define UDC_STM32_IRQ		DT_INST_IRQ_BY_NAME(0, UDC_STM32_IRQ_NAME, irq)
41 #define UDC_STM32_IRQ_PRI	DT_INST_IRQ_BY_NAME(0, UDC_STM32_IRQ_NAME, priority)
42 
43 struct udc_stm32_data  {
44 	PCD_HandleTypeDef pcd;
45 	const struct device *dev;
46 	uint32_t irq;
47 	uint32_t occupied_mem;
48 	void (*pcd_prepare)(const struct device *dev);
49 	int (*clk_enable)(void);
50 	int (*clk_disable)(void);
51 	struct k_thread thread_data;
52 	struct k_msgq msgq_data;
53 };
54 
55 struct udc_stm32_config {
56 	uint32_t num_endpoints;
57 	uint32_t pma_offset;
58 	uint32_t dram_size;
59 	uint16_t ep0_mps;
60 	uint16_t ep_mps;
61 	int speed_idx;
62 };
63 
64 enum udc_stm32_msg_type {
65 	UDC_STM32_MSG_SETUP,
66 	UDC_STM32_MSG_DATA_OUT,
67 	UDC_STM32_MSG_DATA_IN,
68 };
69 
70 struct udc_stm32_msg {
71 	uint8_t type;
72 	uint8_t ep;
73 	uint16_t rx_count;
74 };
75 
udc_stm32_lock(const struct device * dev)76 static void udc_stm32_lock(const struct device *dev)
77 {
78 	udc_lock_internal(dev, K_FOREVER);
79 }
80 
udc_stm32_unlock(const struct device * dev)81 static void udc_stm32_unlock(const struct device *dev)
82 {
83 	udc_unlock_internal(dev);
84 }
85 
86 #define hpcd2data(hpcd) CONTAINER_OF(hpcd, struct udc_stm32_data, pcd);
87 
HAL_PCD_ResetCallback(PCD_HandleTypeDef * hpcd)88 void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd)
89 {
90 	struct udc_stm32_data *priv = hpcd2data(hpcd);
91 	const struct device *dev = priv->dev;
92 	const struct udc_stm32_config *cfg = dev->config;
93 	struct udc_ep_config *ep;
94 
95 	/* Re-Enable control endpoints */
96 	ep = udc_get_ep_cfg(dev, USB_CONTROL_EP_OUT);
97 	if (ep && ep->stat.enabled) {
98 		HAL_PCD_EP_Open(&priv->pcd, USB_CONTROL_EP_OUT, cfg->ep0_mps,
99 				EP_TYPE_CTRL);
100 	}
101 
102 	ep = udc_get_ep_cfg(dev, USB_CONTROL_EP_IN);
103 	if (ep && ep->stat.enabled) {
104 		HAL_PCD_EP_Open(&priv->pcd, USB_CONTROL_EP_IN, cfg->ep0_mps,
105 				EP_TYPE_CTRL);
106 	}
107 
108 	udc_submit_event(priv->dev, UDC_EVT_RESET, 0);
109 }
110 
HAL_PCD_ConnectCallback(PCD_HandleTypeDef * hpcd)111 void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd)
112 {
113 	struct udc_stm32_data *priv = hpcd2data(hpcd);
114 
115 	udc_submit_event(priv->dev, UDC_EVT_VBUS_READY, 0);
116 }
117 
HAL_PCD_DisconnectCallback(PCD_HandleTypeDef * hpcd)118 void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd)
119 {
120 	struct udc_stm32_data *priv = hpcd2data(hpcd);
121 
122 	udc_submit_event(priv->dev, UDC_EVT_VBUS_REMOVED, 0);
123 }
124 
HAL_PCD_SuspendCallback(PCD_HandleTypeDef * hpcd)125 void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd)
126 {
127 	struct udc_stm32_data *priv = hpcd2data(hpcd);
128 
129 	udc_set_suspended(priv->dev, true);
130 	udc_submit_event(priv->dev, UDC_EVT_SUSPEND, 0);
131 }
132 
HAL_PCD_ResumeCallback(PCD_HandleTypeDef * hpcd)133 void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd)
134 {
135 	struct udc_stm32_data *priv = hpcd2data(hpcd);
136 
137 	udc_set_suspended(priv->dev, false);
138 	udc_submit_event(priv->dev, UDC_EVT_RESUME, 0);
139 }
140 
HAL_PCD_SetupStageCallback(PCD_HandleTypeDef * hpcd)141 void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd)
142 {
143 	struct udc_stm32_data *priv = hpcd2data(hpcd);
144 	struct udc_stm32_msg msg = {.type = UDC_STM32_MSG_SETUP};
145 	int err;
146 
147 	err = k_msgq_put(&priv->msgq_data, &msg, K_NO_WAIT);
148 
149 	if (err < 0) {
150 		LOG_ERR("UDC Message queue overrun");
151 	}
152 }
153 
HAL_PCD_SOFCallback(PCD_HandleTypeDef * hpcd)154 void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd)
155 {
156 	struct udc_stm32_data *priv = hpcd2data(hpcd);
157 
158 	udc_submit_event(priv->dev, UDC_EVT_SOF, 0);
159 }
160 
usbd_ctrl_feed_dout(const struct device * dev,const size_t length)161 static int usbd_ctrl_feed_dout(const struct device *dev, const size_t length)
162 {
163 	struct udc_stm32_data *priv = udc_get_private(dev);
164 	struct udc_ep_config *cfg = udc_get_ep_cfg(dev, USB_CONTROL_EP_OUT);
165 	struct net_buf *buf;
166 
167 	buf = udc_ctrl_alloc(dev, USB_CONTROL_EP_OUT, length);
168 	if (buf == NULL) {
169 		return -ENOMEM;
170 	}
171 
172 	k_fifo_put(&cfg->fifo, buf);
173 
174 	HAL_PCD_EP_Receive(&priv->pcd, cfg->addr, buf->data, buf->size);
175 
176 	return 0;
177 }
178 
udc_stm32_flush_tx_fifo(const struct device * dev)179 static void udc_stm32_flush_tx_fifo(const struct device *dev)
180 {
181 	struct udc_stm32_data *priv = udc_get_private(dev);
182 	struct udc_ep_config *cfg = udc_get_ep_cfg(dev, USB_CONTROL_EP_OUT);
183 
184 	HAL_PCD_EP_Receive(&priv->pcd, cfg->addr, NULL, 0);
185 }
186 
udc_stm32_tx(const struct device * dev,uint8_t ep,struct net_buf * buf)187 static int udc_stm32_tx(const struct device *dev, uint8_t ep,
188 			struct net_buf *buf)
189 {
190 	struct udc_stm32_data *priv = udc_get_private(dev);
191 	const struct udc_stm32_config *cfg = dev->config;
192 	uint8_t *data; uint32_t len;
193 	HAL_StatusTypeDef status;
194 
195 	LOG_DBG("TX ep 0x%02x len %u", ep, buf->len);
196 
197 	if (udc_ep_is_busy(dev, ep)) {
198 		return 0;
199 	}
200 
201 	data = buf->data;
202 	len = buf->len;
203 
204 	if (ep == USB_CONTROL_EP_IN) {
205 		len = MIN(cfg->ep0_mps, buf->len);
206 	}
207 
208 	buf->data += len;
209 	buf->len -= len;
210 
211 	status = HAL_PCD_EP_Transmit(&priv->pcd, ep, data, len);
212 	if (status != HAL_OK) {
213 		LOG_ERR("HAL_PCD_EP_Transmit failed(0x%02x), %d", ep, (int)status);
214 		return -EIO;
215 	}
216 
217 	udc_ep_set_busy(dev, ep, true);
218 
219 	if (ep == USB_CONTROL_EP_IN && len > 0) {
220 		/* Wait for an empty package from the host.
221 		 * This also flushes the TX FIFO to the host.
222 		 */
223 		if (DT_HAS_COMPAT_STATUS_OKAY(st_stm32_usb)) {
224 			udc_stm32_flush_tx_fifo(dev);
225 		} else {
226 			usbd_ctrl_feed_dout(dev, 0);
227 		}
228 	}
229 
230 	return 0;
231 }
232 
udc_stm32_rx(const struct device * dev,uint8_t ep,struct net_buf * buf)233 static int udc_stm32_rx(const struct device *dev, uint8_t ep,
234 			struct net_buf *buf)
235 {
236 	struct udc_stm32_data *priv = udc_get_private(dev);
237 	HAL_StatusTypeDef status;
238 
239 	LOG_DBG("RX ep 0x%02x len %u", ep, buf->size);
240 
241 	if (udc_ep_is_busy(dev, ep)) {
242 		return 0;
243 	}
244 
245 	status = HAL_PCD_EP_Receive(&priv->pcd, ep, buf->data, buf->size);
246 	if (status != HAL_OK) {
247 		LOG_ERR("HAL_PCD_EP_Receive failed(0x%02x), %d", ep, (int)status);
248 		return -EIO;
249 	}
250 
251 	udc_ep_set_busy(dev, ep, true);
252 
253 	return 0;
254 }
255 
HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef * hpcd,uint8_t epnum)256 void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
257 {
258 	uint32_t rx_count = HAL_PCD_EP_GetRxCount(hpcd, epnum);
259 	struct udc_stm32_data *priv = hpcd2data(hpcd);
260 	struct udc_stm32_msg msg = {
261 		.type = UDC_STM32_MSG_DATA_OUT,
262 		.ep = epnum,
263 		.rx_count = rx_count,
264 	};
265 	int err;
266 
267 	err = k_msgq_put(&priv->msgq_data, &msg, K_NO_WAIT);
268 	if (err != 0) {
269 		LOG_ERR("UDC Message queue overrun");
270 	}
271 }
272 
HAL_PCD_DataInStageCallback(PCD_HandleTypeDef * hpcd,uint8_t epnum)273 void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
274 {
275 	struct udc_stm32_data *priv = hpcd2data(hpcd);
276 	struct udc_stm32_msg msg = {
277 		.type = UDC_STM32_MSG_DATA_IN,
278 		.ep = epnum,
279 	};
280 	int err;
281 
282 	err = k_msgq_put(&priv->msgq_data, &msg, K_NO_WAIT);
283 	if (err != 0) {
284 		LOG_ERR("UDC Message queue overrun");
285 	}
286 }
287 
handle_msg_data_out(struct udc_stm32_data * priv,uint8_t epnum,uint16_t rx_count)288 static void handle_msg_data_out(struct udc_stm32_data *priv, uint8_t epnum, uint16_t rx_count)
289 {
290 	const struct device *dev = priv->dev;
291 	uint8_t ep = epnum | USB_EP_DIR_OUT;
292 	struct net_buf *buf;
293 
294 	LOG_DBG("DataOut ep 0x%02x",  ep);
295 
296 	udc_ep_set_busy(dev, ep, false);
297 
298 	buf = udc_buf_get(dev, ep);
299 	if (unlikely(buf == NULL)) {
300 		LOG_ERR("ep 0x%02x queue is empty", ep);
301 		return;
302 	}
303 
304 	net_buf_add(buf, rx_count);
305 
306 	if (ep == USB_CONTROL_EP_OUT) {
307 		if (udc_ctrl_stage_is_status_out(dev)) {
308 			udc_ctrl_update_stage(dev, buf);
309 			udc_ctrl_submit_status(dev, buf);
310 		} else {
311 			udc_ctrl_update_stage(dev, buf);
312 		}
313 
314 		if (udc_ctrl_stage_is_status_in(dev)) {
315 			udc_ctrl_submit_s_out_status(dev, buf);
316 		}
317 	} else {
318 		udc_submit_ep_event(dev, buf, 0);
319 	}
320 
321 	buf = udc_buf_peek(dev, ep);
322 	if (buf) {
323 		udc_stm32_rx(dev, ep, buf);
324 	}
325 }
326 
handle_msg_data_in(struct udc_stm32_data * priv,uint8_t epnum)327 static void handle_msg_data_in(struct udc_stm32_data *priv, uint8_t epnum)
328 {
329 	const struct device *dev = priv->dev;
330 	uint8_t ep = epnum | USB_EP_DIR_IN;
331 	struct net_buf *buf;
332 
333 	LOG_DBG("DataIn ep 0x%02x",  ep);
334 
335 	udc_ep_set_busy(dev, ep, false);
336 
337 	buf = udc_buf_peek(dev, ep);
338 	if (unlikely(buf == NULL)) {
339 		return;
340 	}
341 
342 	if (ep == USB_CONTROL_EP_IN && buf->len) {
343 		const struct udc_stm32_config *cfg = dev->config;
344 		uint32_t len = MIN(cfg->ep0_mps, buf->len);
345 
346 		HAL_PCD_EP_Transmit(&priv->pcd, ep, buf->data, len);
347 
348 		buf->len -= len;
349 		buf->data += len;
350 
351 		return;
352 	}
353 
354 	if (udc_ep_buf_has_zlp(buf)) {
355 		udc_ep_buf_clear_zlp(buf);
356 		HAL_PCD_EP_Transmit(&priv->pcd, ep, buf->data, 0);
357 
358 		return;
359 	}
360 
361 	udc_buf_get(dev, ep);
362 
363 	if (ep == USB_CONTROL_EP_IN) {
364 		if (udc_ctrl_stage_is_status_in(dev) ||
365 		    udc_ctrl_stage_is_no_data(dev)) {
366 			/* Status stage finished, notify upper layer */
367 			udc_ctrl_submit_status(dev, buf);
368 		}
369 
370 		/* Update to next stage of control transfer */
371 		udc_ctrl_update_stage(dev, buf);
372 
373 		if (udc_ctrl_stage_is_status_out(dev)) {
374 			/*
375 			 * IN transfer finished, release buffer,
376 			 * control OUT buffer should be already fed.
377 			 */
378 			net_buf_unref(buf);
379 		}
380 
381 		return;
382 	}
383 
384 	udc_submit_ep_event(dev, buf, 0);
385 
386 	buf = udc_buf_peek(dev, ep);
387 	if (buf) {
388 		udc_stm32_tx(dev, ep, buf);
389 	}
390 }
391 
handle_msg_setup(struct udc_stm32_data * priv)392 static void handle_msg_setup(struct udc_stm32_data *priv)
393 {
394 	struct usb_setup_packet *setup = (void *)priv->pcd.Setup;
395 	const struct device *dev = priv->dev;
396 	struct net_buf *buf;
397 	int err;
398 
399 	buf = udc_ctrl_alloc(dev, USB_CONTROL_EP_OUT, sizeof(struct usb_setup_packet));
400 	if (buf == NULL) {
401 		LOG_ERR("Failed to allocate for setup");
402 		return;
403 	}
404 
405 	udc_ep_buf_set_setup(buf);
406 	memcpy(buf->data, setup, 8);
407 	net_buf_add(buf, 8);
408 
409 	udc_ctrl_update_stage(dev, buf);
410 
411 	if (!buf->len) {
412 		return;
413 	}
414 
415 	if ((setup->bmRequestType == 0) && (setup->bRequest == USB_SREQ_SET_ADDRESS)) {
416 		/* HAL requires we set the address before submitting status */
417 		HAL_PCD_SetAddress(&priv->pcd, setup->wValue);
418 	}
419 
420 	if (udc_ctrl_stage_is_data_out(dev)) {
421 		/*  Allocate and feed buffer for data OUT stage */
422 		err = usbd_ctrl_feed_dout(dev, udc_data_stage_length(buf));
423 		if (err == -ENOMEM) {
424 			udc_submit_ep_event(dev, buf, err);
425 		}
426 	} else if (udc_ctrl_stage_is_data_in(dev)) {
427 		udc_ctrl_submit_s_in_status(dev);
428 	} else {
429 		udc_ctrl_submit_s_status(dev);
430 	}
431 }
432 
udc_stm32_thread_handler(void * arg1,void * arg2,void * arg3)433 static void udc_stm32_thread_handler(void *arg1, void *arg2, void *arg3)
434 {
435 	const struct device *dev = arg1;
436 	struct udc_stm32_data *priv = udc_get_private(dev);
437 	struct udc_stm32_msg msg;
438 
439 	while (true) {
440 		k_msgq_get(&priv->msgq_data, &msg, K_FOREVER);
441 		switch (msg.type) {
442 		case UDC_STM32_MSG_SETUP:
443 			handle_msg_setup(priv);
444 			break;
445 		case UDC_STM32_MSG_DATA_IN:
446 			handle_msg_data_in(priv, msg.ep);
447 			break;
448 		case UDC_STM32_MSG_DATA_OUT:
449 			handle_msg_data_out(priv, msg.ep, msg.rx_count);
450 			break;
451 		}
452 	}
453 }
454 
455 #if DT_INST_NODE_HAS_PROP(0, disconnect_gpios)
HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef * hpcd,uint8_t state)456 void HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef *hpcd, uint8_t state)
457 {
458 	struct gpio_dt_spec usb_disconnect = GPIO_DT_SPEC_INST_GET(0, disconnect_gpios);
459 
460 	gpio_pin_configure_dt(&usb_disconnect,
461 			      state ? GPIO_OUTPUT_ACTIVE : GPIO_OUTPUT_INACTIVE);
462 }
463 #endif
464 
udc_stm32_irq(const struct device * dev)465 static void udc_stm32_irq(const struct device *dev)
466 {
467 	const struct udc_stm32_data *priv =  udc_get_private(dev);
468 
469 	/* HAL irq handler will call the related above callback */
470 	HAL_PCD_IRQHandler((PCD_HandleTypeDef *)&priv->pcd);
471 }
472 
udc_stm32_init(const struct device * dev)473 int udc_stm32_init(const struct device *dev)
474 {
475 	struct udc_stm32_data *priv = udc_get_private(dev);
476 	HAL_StatusTypeDef status;
477 
478 	if (priv->clk_enable && priv->clk_enable()) {
479 		LOG_ERR("Error enabling clock(s)");
480 		return -EIO;
481 	}
482 
483 	priv->pcd_prepare(dev);
484 
485 	status = HAL_PCD_Init(&priv->pcd);
486 	if (status != HAL_OK) {
487 		LOG_ERR("PCD_Init failed, %d", (int)status);
488 		return -EIO;
489 	}
490 
491 	HAL_PCD_Stop(&priv->pcd);
492 
493 	return 0;
494 }
495 
496 #if defined(USB) || defined(USB_DRD_FS)
udc_stm32_mem_init(const struct device * dev)497 static inline void udc_stm32_mem_init(const struct device *dev)
498 {
499 	struct udc_stm32_data *priv = udc_get_private(dev);
500 	const struct udc_stm32_config *cfg = dev->config;
501 
502 	priv->occupied_mem = cfg->pma_offset;
503 }
504 
udc_stm32_ep_mem_config(const struct device * dev,struct udc_ep_config * ep,bool enable)505 static int udc_stm32_ep_mem_config(const struct device *dev,
506 				   struct udc_ep_config *ep,
507 				   bool enable)
508 {
509 	struct udc_stm32_data *priv = udc_get_private(dev);
510 	const struct udc_stm32_config *cfg = dev->config;
511 	uint32_t size;
512 
513 	size = MIN(udc_mps_ep_size(ep), cfg->ep_mps);
514 
515 	if (!enable) {
516 		priv->occupied_mem -= size;
517 		return 0;
518 	}
519 
520 	if (priv->occupied_mem + size >= cfg->dram_size) {
521 		LOG_ERR("Unable to allocate FIFO for 0x%02x", ep->addr);
522 		return -ENOMEM;
523 	}
524 
525 	/* Configure PMA offset for the endpoint */
526 	HAL_PCDEx_PMAConfig(&priv->pcd, ep->addr, PCD_SNG_BUF,
527 			    priv->occupied_mem);
528 
529 	priv->occupied_mem += size;
530 
531 	return 0;
532 }
533 #else
udc_stm32_mem_init(const struct device * dev)534 static void udc_stm32_mem_init(const struct device *dev)
535 {
536 	struct udc_stm32_data *priv = udc_get_private(dev);
537 	const struct udc_stm32_config *cfg = dev->config;
538 	int words;
539 
540 	LOG_DBG("DRAM size: %ub", cfg->dram_size);
541 
542 	if (cfg->ep_mps % 4 || cfg->ep0_mps % 4) {
543 		LOG_ERR("Not a 32-bit word multiple: ep0(%u)|ep(%u)",
544 			cfg->ep0_mps, cfg->ep_mps);
545 		return;
546 	}
547 
548 	/* The documentation is not clear at all about RX FiFo size requirement,
549 	 * 160 has been selected through trial and error.
550 	 */
551 	words = MAX(160, cfg->ep_mps / 4);
552 	HAL_PCDEx_SetRxFiFo(&priv->pcd, words);
553 	priv->occupied_mem = words * 4;
554 
555 	/* For EP0 TX, reserve only one MPS */
556 	HAL_PCDEx_SetTxFiFo(&priv->pcd, 0, cfg->ep0_mps / 4);
557 	priv->occupied_mem += cfg->ep0_mps;
558 
559 	/* Reset TX allocs */
560 	for (unsigned int i = 1U; i < cfg->num_endpoints; i++) {
561 		HAL_PCDEx_SetTxFiFo(&priv->pcd, i, 0);
562 	}
563 }
564 
udc_stm32_ep_mem_config(const struct device * dev,struct udc_ep_config * ep,bool enable)565 static int udc_stm32_ep_mem_config(const struct device *dev,
566 				   struct udc_ep_config *ep,
567 				   bool enable)
568 {
569 	struct udc_stm32_data *priv = udc_get_private(dev);
570 	const struct udc_stm32_config *cfg = dev->config;
571 	unsigned int words;
572 
573 	if (!(ep->addr & USB_EP_DIR_IN) || !USB_EP_GET_IDX(ep->addr)) {
574 		return 0;
575 	}
576 
577 	words = MIN(udc_mps_ep_size(ep), cfg->ep_mps) / 4;
578 	words = (words <= 64) ? words * 2 : words;
579 
580 	if (!enable) {
581 		if (priv->occupied_mem >= (words * 4)) {
582 			priv->occupied_mem -= (words * 4);
583 		}
584 		HAL_PCDEx_SetTxFiFo(&priv->pcd, USB_EP_GET_IDX(ep->addr), 0);
585 		return 0;
586 	}
587 
588 	if (cfg->dram_size - priv->occupied_mem < words * 4) {
589 		LOG_ERR("Unable to allocate FIFO for 0x%02x", ep->addr);
590 		return -ENOMEM;
591 	}
592 
593 	HAL_PCDEx_SetTxFiFo(&priv->pcd, USB_EP_GET_IDX(ep->addr), words);
594 
595 	priv->occupied_mem += words * 4;
596 
597 	return 0;
598 }
599 #endif
600 
udc_stm32_enable(const struct device * dev)601 static int udc_stm32_enable(const struct device *dev)
602 {
603 	struct udc_stm32_data *priv = udc_get_private(dev);
604 	const struct udc_stm32_config *cfg = dev->config;
605 	HAL_StatusTypeDef status;
606 	int ret;
607 
608 	LOG_DBG("Enable UDC");
609 
610 	udc_stm32_mem_init(dev);
611 
612 	status = HAL_PCD_Start(&priv->pcd);
613 	if (status != HAL_OK) {
614 		LOG_ERR("PCD_Start failed, %d", (int)status);
615 		return -EIO;
616 	}
617 
618 	ret = udc_ep_enable_internal(dev, USB_CONTROL_EP_OUT,
619 				     USB_EP_TYPE_CONTROL, cfg->ep0_mps, 0);
620 	if (ret) {
621 		LOG_ERR("Failed enabling ep 0x%02x", USB_CONTROL_EP_OUT);
622 		return ret;
623 	}
624 
625 	ret |= udc_ep_enable_internal(dev, USB_CONTROL_EP_IN,
626 				      USB_EP_TYPE_CONTROL, cfg->ep0_mps, 0);
627 	if (ret) {
628 		LOG_ERR("Failed enabling ep 0x%02x", USB_CONTROL_EP_IN);
629 		return ret;
630 	}
631 
632 	irq_enable(priv->irq);
633 
634 	return 0;
635 }
636 
udc_stm32_disable(const struct device * dev)637 static int udc_stm32_disable(const struct device *dev)
638 {
639 	struct udc_stm32_data *priv = udc_get_private(dev);
640 	HAL_StatusTypeDef status;
641 
642 	irq_disable(UDC_STM32_IRQ);
643 
644 	if (udc_ep_disable_internal(dev, USB_CONTROL_EP_OUT)) {
645 		LOG_ERR("Failed to disable control endpoint");
646 		return -EIO;
647 	}
648 
649 	if (udc_ep_disable_internal(dev, USB_CONTROL_EP_IN)) {
650 		LOG_ERR("Failed to disable control endpoint");
651 		return -EIO;
652 	}
653 
654 	status = HAL_PCD_Stop(&priv->pcd);
655 	if (status != HAL_OK) {
656 		LOG_ERR("PCD_Stop failed, %d", (int)status);
657 		return -EIO;
658 	}
659 
660 	return 0;
661 }
662 
udc_stm32_shutdown(const struct device * dev)663 static int udc_stm32_shutdown(const struct device *dev)
664 {
665 	struct udc_stm32_data *priv = udc_get_private(dev);
666 	HAL_StatusTypeDef status;
667 
668 	status = HAL_PCD_DeInit(&priv->pcd);
669 	if (status != HAL_OK) {
670 		LOG_ERR("PCD_DeInit failed, %d", (int)status);
671 		/* continue anyway */
672 	}
673 
674 	if (priv->clk_disable && priv->clk_disable()) {
675 		LOG_ERR("Error disabling clock(s)");
676 		/* continue anyway */
677 	}
678 
679 	if (irq_is_enabled(priv->irq)) {
680 		irq_disable(priv->irq);
681 	}
682 
683 	return 0;
684 }
685 
udc_stm32_set_address(const struct device * dev,const uint8_t addr)686 static int udc_stm32_set_address(const struct device *dev, const uint8_t addr)
687 {
688 	struct udc_stm32_data *priv = udc_get_private(dev);
689 	HAL_StatusTypeDef status;
690 
691 	LOG_DBG("Set Address %u", addr);
692 
693 	status = HAL_PCD_SetAddress(&priv->pcd, addr);
694 	if (status != HAL_OK) {
695 		LOG_ERR("HAL_PCD_SetAddress failed(0x%02x), %d",
696 			addr, (int)status);
697 		return -EIO;
698 	}
699 
700 	return 0;
701 }
702 
udc_stm32_host_wakeup(const struct device * dev)703 static int udc_stm32_host_wakeup(const struct device *dev)
704 {
705 	struct udc_stm32_data *priv = udc_get_private(dev);
706 	HAL_StatusTypeDef status;
707 
708 	status = HAL_PCD_ActivateRemoteWakeup(&priv->pcd);
709 	if (status != HAL_OK) {
710 		LOG_ERR("HAL_PCD_ActivateRemoteWakeup, %d", (int)status);
711 		return -EIO;
712 	}
713 
714 	/* Must be active from 1ms to 15ms as per reference manual. */
715 	k_sleep(K_MSEC(2));
716 
717 	status = HAL_PCD_DeActivateRemoteWakeup(&priv->pcd);
718 	if (status != HAL_OK) {
719 		return -EIO;
720 	}
721 
722 	return 0;
723 }
724 
udc_stm32_ep_enable(const struct device * dev,struct udc_ep_config * ep_cfg)725 static int udc_stm32_ep_enable(const struct device *dev,
726 			       struct udc_ep_config *ep_cfg)
727 {
728 	struct udc_stm32_data *priv = udc_get_private(dev);
729 	HAL_StatusTypeDef status;
730 	uint8_t ep_type;
731 	int ret;
732 
733 	LOG_DBG("Enable ep 0x%02x", ep_cfg->addr);
734 
735 	switch (ep_cfg->attributes & USB_EP_TRANSFER_TYPE_MASK) {
736 	case USB_EP_TYPE_CONTROL:
737 		ep_type = EP_TYPE_CTRL;
738 		break;
739 	case USB_EP_TYPE_BULK:
740 		ep_type = EP_TYPE_BULK;
741 		break;
742 	case USB_EP_TYPE_INTERRUPT:
743 		ep_type = EP_TYPE_INTR;
744 		break;
745 	case USB_EP_TYPE_ISO:
746 		ep_type = EP_TYPE_ISOC;
747 		break;
748 	default:
749 		return -EINVAL;
750 	}
751 
752 	ret = udc_stm32_ep_mem_config(dev, ep_cfg, true);
753 	if (ret) {
754 		return ret;
755 	}
756 
757 	status = HAL_PCD_EP_Open(&priv->pcd, ep_cfg->addr,
758 				 udc_mps_ep_size(ep_cfg), ep_type);
759 	if (status != HAL_OK) {
760 		LOG_ERR("HAL_PCD_EP_Open failed(0x%02x), %d",
761 			ep_cfg->addr, (int)status);
762 		return -EIO;
763 	}
764 
765 	return 0;
766 }
767 
udc_stm32_ep_disable(const struct device * dev,struct udc_ep_config * ep)768 static int udc_stm32_ep_disable(const struct device *dev,
769 			      struct udc_ep_config *ep)
770 {
771 	struct udc_stm32_data *priv = udc_get_private(dev);
772 	HAL_StatusTypeDef status;
773 
774 	LOG_DBG("Disable ep 0x%02x", ep->addr);
775 
776 	status = HAL_PCD_EP_Close(&priv->pcd, ep->addr);
777 	if (status != HAL_OK) {
778 		LOG_ERR("HAL_PCD_EP_Close failed(0x%02x), %d",
779 			ep->addr, (int)status);
780 		return -EIO;
781 	}
782 
783 	return udc_stm32_ep_mem_config(dev, ep, false);
784 }
785 
udc_stm32_ep_set_halt(const struct device * dev,struct udc_ep_config * cfg)786 static int udc_stm32_ep_set_halt(const struct device *dev,
787 				 struct udc_ep_config *cfg)
788 {
789 	struct udc_stm32_data *priv = udc_get_private(dev);
790 	HAL_StatusTypeDef status;
791 
792 	LOG_DBG("Halt ep 0x%02x", cfg->addr);
793 
794 	status = HAL_PCD_EP_SetStall(&priv->pcd, cfg->addr);
795 	if (status != HAL_OK) {
796 		LOG_ERR("HAL_PCD_EP_SetStall failed(0x%02x), %d",
797 			cfg->addr, (int)status);
798 		return -EIO;
799 	}
800 
801 	return 0;
802 }
803 
udc_stm32_ep_clear_halt(const struct device * dev,struct udc_ep_config * cfg)804 static int udc_stm32_ep_clear_halt(const struct device *dev,
805 				   struct udc_ep_config *cfg)
806 {
807 	struct udc_stm32_data *priv = udc_get_private(dev);
808 	HAL_StatusTypeDef status;
809 
810 	LOG_DBG("Clear halt for ep 0x%02x", cfg->addr);
811 
812 	status = HAL_PCD_EP_ClrStall(&priv->pcd, cfg->addr);
813 	if (status != HAL_OK) {
814 		LOG_ERR("HAL_PCD_EP_ClrStall failed(0x%02x), %d",
815 			cfg->addr, (int)status);
816 		return -EIO;
817 	}
818 
819 	return 0;
820 }
821 
udc_stm32_ep_flush(const struct device * dev,struct udc_ep_config * cfg)822 static int udc_stm32_ep_flush(const struct device *dev,
823 			      struct udc_ep_config *cfg)
824 {
825 	struct udc_stm32_data *priv = udc_get_private(dev);
826 	HAL_StatusTypeDef status;
827 
828 	LOG_DBG("Flush ep 0x%02x", cfg->addr);
829 
830 	status = HAL_PCD_EP_Flush(&priv->pcd, cfg->addr);
831 	if (status != HAL_OK) {
832 		LOG_ERR("HAL_PCD_EP_Flush failed(0x%02x), %d",
833 			cfg->addr, (int)status);
834 		return -EIO;
835 	}
836 
837 	return 0;
838 }
839 
udc_stm32_ep_enqueue(const struct device * dev,struct udc_ep_config * epcfg,struct net_buf * buf)840 static int udc_stm32_ep_enqueue(const struct device *dev,
841 				struct udc_ep_config *epcfg,
842 				struct net_buf *buf)
843 {
844 	unsigned int lock_key;
845 	int ret;
846 
847 	udc_buf_put(epcfg, buf);
848 
849 	lock_key = irq_lock();
850 
851 	if (USB_EP_DIR_IS_IN(epcfg->addr)) {
852 		ret = udc_stm32_tx(dev, epcfg->addr, buf);
853 	} else {
854 		ret = udc_stm32_rx(dev, epcfg->addr, buf);
855 	}
856 
857 	irq_unlock(lock_key);
858 
859 	return ret;
860 }
861 
udc_stm32_ep_dequeue(const struct device * dev,struct udc_ep_config * epcfg)862 static int udc_stm32_ep_dequeue(const struct device *dev,
863 				struct udc_ep_config *epcfg)
864 {
865 	struct net_buf *buf;
866 
867 	udc_stm32_ep_flush(dev, epcfg);
868 
869 	buf = udc_buf_get_all(dev, epcfg->addr);
870 	if (buf) {
871 		udc_submit_ep_event(dev, buf, -ECONNABORTED);
872 	}
873 
874 	udc_ep_set_busy(dev, epcfg->addr, false);
875 
876 	return 0;
877 }
878 
udc_stm32_device_speed(const struct device * dev)879 static enum udc_bus_speed udc_stm32_device_speed(const struct device *dev)
880 {
881 	struct udc_stm32_data *priv = udc_get_private(dev);
882 
883 #ifdef USBD_HS_SPEED
884 	if (priv->pcd.Init.speed == USBD_HS_SPEED) {
885 		return UDC_BUS_SPEED_HS;
886 	}
887 #endif
888 
889 	if (priv->pcd.Init.speed == USBD_FS_SPEED) {
890 		return UDC_BUS_SPEED_FS;
891 	}
892 
893 	return UDC_BUS_UNKNOWN;
894 }
895 
896 static const struct udc_api udc_stm32_api = {
897 	.lock = udc_stm32_lock,
898 	.unlock = udc_stm32_unlock,
899 	.init = udc_stm32_init,
900 	.enable = udc_stm32_enable,
901 	.disable = udc_stm32_disable,
902 	.shutdown = udc_stm32_shutdown,
903 	.set_address = udc_stm32_set_address,
904 	.host_wakeup = udc_stm32_host_wakeup,
905 	.ep_try_config = NULL,
906 	.ep_enable = udc_stm32_ep_enable,
907 	.ep_disable = udc_stm32_ep_disable,
908 	.ep_set_halt = udc_stm32_ep_set_halt,
909 	.ep_clear_halt = udc_stm32_ep_clear_halt,
910 	.ep_enqueue = udc_stm32_ep_enqueue,
911 	.ep_dequeue = udc_stm32_ep_dequeue,
912 	.device_speed = udc_stm32_device_speed,
913 };
914 
915 /* ----------------- Instance/Device specific data ----------------- */
916 
917 /*
918  * USB, USB_OTG_FS and USB_DRD_FS are defined in STM32Cube HAL and allows to
919  * distinguish between two kind of USB DC. STM32 F0, F3, L0 and G4 series
920  * support USB device controller. STM32 F4 and F7 series support USB_OTG_FS
921  * device controller. STM32 F1 and L4 series support either USB or USB_OTG_FS
922  * device controller.STM32 G0 series supports USB_DRD_FS device controller.
923  *
924  * WARNING: Don't mix USB defined in STM32Cube HAL and CONFIG_USB_* from Zephyr
925  * Kconfig system.
926  */
927 #define USB_NUM_BIDIR_ENDPOINTS	DT_INST_PROP(0, num_bidir_endpoints)
928 
929 #if defined(USB) || defined(USB_DRD_FS)
930 #define EP0_MPS 64U
931 #define EP_MPS 64U
932 #define USB_BTABLE_SIZE  (8 * USB_NUM_BIDIR_ENDPOINTS)
933 #define USB_RAM_SIZE	DT_INST_PROP(0, ram_size)
934 #else /* USB_OTG_FS */
935 #define EP0_MPS USB_OTG_MAX_EP0_SIZE
936 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs)
937 #define EP_MPS USB_OTG_HS_MAX_PACKET_SIZE
938 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otgfs) || DT_HAS_COMPAT_STATUS_OKAY(st_stm32_usb)
939 #define EP_MPS USB_OTG_FS_MAX_PACKET_SIZE
940 #endif
941 #define USB_RAM_SIZE	DT_INST_PROP(0, ram_size)
942 #define USB_BTABLE_SIZE 0
943 #endif /* USB */
944 
945 #define USB_OTG_HS_EMB_PHY (DT_HAS_COMPAT_STATUS_OKAY(st_stm32_usbphyc) && \
946 			    DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs))
947 
948 #define USB_OTG_HS_ULPI_PHY (DT_HAS_COMPAT_STATUS_OKAY(usb_ulpi_phy) && \
949 			    DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs))
950 
951 static struct udc_stm32_data udc0_priv;
952 
953 static struct udc_data udc0_data = {
954 	.mutex = Z_MUTEX_INITIALIZER(udc0_data.mutex),
955 	.priv = &udc0_priv,
956 };
957 
958 static const struct udc_stm32_config udc0_cfg  = {
959 	.num_endpoints = USB_NUM_BIDIR_ENDPOINTS,
960 	.dram_size = USB_RAM_SIZE,
961 	.pma_offset = USB_BTABLE_SIZE,
962 	.ep0_mps = EP0_MPS,
963 	.ep_mps = EP_MPS,
964 	.speed_idx = DT_ENUM_IDX_OR(DT_DRV_INST(0), maximum_speed, 1),
965 };
966 
967 #if defined(USB_OTG_FS) || defined(USB_OTG_HS)
usb_dc_stm32_get_maximum_speed(void)968 static uint32_t usb_dc_stm32_get_maximum_speed(void)
969 {
970 /*
971  * STM32L4 series USB LL API doesn't provide HIGH and HIGH_IN_FULL speed
972  * defines.
973  */
974 #if defined(CONFIG_SOC_SERIES_STM32L4X)
975 #define USB_OTG_SPEED_HIGH                     0U
976 #define USB_OTG_SPEED_HIGH_IN_FULL             1U
977 #endif /* CONFIG_SOC_SERIES_STM32L4X */
978 /*
979  * If max-speed is not passed via DT, set it to USB controller's
980  * maximum hardware capability.
981  */
982 #if USB_OTG_HS_EMB_PHY || USB_OTG_HS_ULPI_PHY
983 	uint32_t speed = USB_OTG_SPEED_HIGH;
984 #else
985 	uint32_t speed = USB_OTG_SPEED_FULL;
986 #endif
987 
988 #ifdef USB_MAXIMUM_SPEED
989 
990 	if (!strncmp(USB_MAXIMUM_SPEED, "high-speed", 10)) {
991 		speed = USB_OTG_SPEED_HIGH;
992 	} else if (!strncmp(USB_MAXIMUM_SPEED, "full-speed", 10)) {
993 #if defined(CONFIG_SOC_SERIES_STM32H7X) || defined(USB_OTG_HS_EMB_PHY)
994 		speed = USB_OTG_SPEED_HIGH_IN_FULL;
995 #else
996 		speed = USB_OTG_SPEED_FULL;
997 #endif
998 	} else {
999 		LOG_DBG("Unsupported maximum speed defined in device tree. "
1000 			"USB controller will default to its maximum HW "
1001 			"capability");
1002 	}
1003 #endif
1004 
1005 	return speed;
1006 }
1007 #endif /* USB_OTG_FS || USB_OTG_HS */
1008 
priv_pcd_prepare(const struct device * dev)1009 static void priv_pcd_prepare(const struct device *dev)
1010 {
1011 	struct udc_stm32_data *priv = udc_get_private(dev);
1012 	const struct udc_stm32_config *cfg = dev->config;
1013 
1014 	memset(&priv->pcd, 0, sizeof(priv->pcd));
1015 
1016 	/* Default values */
1017 	priv->pcd.Init.dev_endpoints = cfg->num_endpoints;
1018 	priv->pcd.Init.ep0_mps = cfg->ep0_mps;
1019 	priv->pcd.Init.speed = PCD_SPEED_FULL;
1020 
1021 	/* Per controller/Phy values */
1022 #if defined(USB)
1023 	priv->pcd.Instance = USB;
1024 #elif defined(USB_DRD_FS)
1025 	priv->pcd.Instance = USB_DRD_FS;
1026 #elif defined(USB_OTG_FS) || defined(USB_OTG_HS)
1027 	priv->pcd.Init.speed = usb_dc_stm32_get_maximum_speed();
1028 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs)
1029 	priv->pcd.Instance = USB_OTG_HS;
1030 #else
1031 	priv->pcd.Instance = USB_OTG_FS;
1032 #endif
1033 #endif /* USB */
1034 
1035 #if USB_OTG_HS_EMB_PHY
1036 	priv->pcd.Init.phy_itface = USB_OTG_HS_EMBEDDED_PHY;
1037 #elif USB_OTG_HS_ULPI_PHY
1038 	priv->pcd.Init.phy_itface = USB_OTG_ULPI_PHY;
1039 #else
1040 	priv->pcd.Init.phy_itface = PCD_PHY_EMBEDDED;
1041 #endif /* USB_OTG_HS_EMB_PHY */
1042 }
1043 
1044 static const struct stm32_pclken pclken[] = STM32_DT_INST_CLOCKS(0);
1045 
priv_clock_enable(void)1046 static int priv_clock_enable(void)
1047 {
1048 	const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
1049 
1050 	if (!device_is_ready(clk)) {
1051 		LOG_ERR("clock control device not ready");
1052 		return -ENODEV;
1053 	}
1054 
1055 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs) && defined(CONFIG_SOC_SERIES_STM32U5X)
1056 	/* Sequence to enable the power of the OTG HS on a stm32U5 serie : Enable VDDUSB */
1057 	bool pwr_clk = LL_AHB3_GRP1_IsEnabledClock(LL_AHB3_GRP1_PERIPH_PWR);
1058 
1059 	if (!pwr_clk) {
1060 		LL_AHB3_GRP1_EnableClock(LL_AHB3_GRP1_PERIPH_PWR);
1061 	}
1062 
1063 	/* Check that power range is 1 or 2 */
1064 	if (LL_PWR_GetRegulVoltageScaling() < LL_PWR_REGU_VOLTAGE_SCALE2) {
1065 		LOG_ERR("Wrong Power range to use USB OTG HS");
1066 		return -EIO;
1067 	}
1068 
1069 	LL_PWR_EnableVddUSB();
1070 	/* Configure VOSR register of USB HSTransceiverSupply(); */
1071 	LL_PWR_EnableUSBPowerSupply();
1072 	LL_PWR_EnableUSBEPODBooster();
1073 	while (LL_PWR_IsActiveFlag_USBBOOST() != 1) {
1074 		/* Wait for USB EPOD BOOST ready */
1075 	}
1076 
1077 	/* Leave the PWR clock in its initial position */
1078 	if (!pwr_clk) {
1079 		LL_AHB3_GRP1_DisableClock(LL_AHB3_GRP1_PERIPH_PWR);
1080 	}
1081 
1082 	/* Set the OTG PHY reference clock selection (through SYSCFG) block */
1083 	LL_APB3_GRP1_EnableClock(LL_APB3_GRP1_PERIPH_SYSCFG);
1084 	HAL_SYSCFG_SetOTGPHYReferenceClockSelection(SYSCFG_OTG_HS_PHY_CLK_SELECT_1);
1085 	/* Configuring the SYSCFG registers OTG_HS PHY : OTG_HS PHY enable*/
1086 	HAL_SYSCFG_EnableOTGPHY(SYSCFG_OTG_HS_PHY_ENABLE);
1087 #elif defined(PWR_USBSCR_USB33SV) || defined(PWR_SVMCR_USV)
1088 	/*
1089 	 * VDDUSB independent USB supply (PWR clock is on)
1090 	 * with LL_PWR_EnableVDDUSB function (higher case)
1091 	 */
1092 	LL_PWR_EnableVDDUSB();
1093 #endif
1094 
1095 #if defined(CONFIG_SOC_SERIES_STM32H7X)
1096 	LL_PWR_EnableUSBVoltageDetector();
1097 
1098 	/* Per AN2606: USBREGEN not supported when running in FS mode. */
1099 	LL_PWR_DisableUSBReg();
1100 	while (!LL_PWR_IsActiveFlag_USB()) {
1101 		LOG_INF("PWR not active yet");
1102 		k_sleep(K_MSEC(100));
1103 	}
1104 #endif
1105 
1106 	if (DT_INST_NUM_CLOCKS(0) > 1) {
1107 		if (clock_control_configure(clk, (clock_control_subsys_t *)&pclken[1],
1108 									NULL) != 0) {
1109 			LOG_ERR("Could not select USB domain clock");
1110 			return -EIO;
1111 		}
1112 	}
1113 
1114 	if (clock_control_on(clk, (clock_control_subsys_t *)&pclken[0]) != 0) {
1115 		LOG_ERR("Unable to enable USB clock");
1116 		return -EIO;
1117 	}
1118 
1119 	if (IS_ENABLED(CONFIG_UDC_STM32_CLOCK_CHECK)) {
1120 		uint32_t usb_clock_rate;
1121 
1122 		if (clock_control_get_rate(clk,
1123 					   (clock_control_subsys_t *)&pclken[1],
1124 					   &usb_clock_rate) != 0) {
1125 			LOG_ERR("Failed to get USB domain clock rate");
1126 			return -EIO;
1127 		}
1128 
1129 		if (usb_clock_rate != MHZ(48)) {
1130 			LOG_ERR("USB Clock is not 48MHz (%d)", usb_clock_rate);
1131 			return -ENOTSUP;
1132 		}
1133 	}
1134 
1135 	/* Previous check won't work in case of F1/F3. Add build time check */
1136 #if defined(RCC_CFGR_OTGFSPRE) || defined(RCC_CFGR_USBPRE)
1137 
1138 #if (MHZ(48) == CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC) && !defined(STM32_PLL_USBPRE)
1139 	/* PLL output clock is set to 48MHz, it should not be divided */
1140 #warning USBPRE/OTGFSPRE should be set in rcc node
1141 #endif
1142 
1143 #endif /* RCC_CFGR_OTGFSPRE / RCC_CFGR_USBPRE */
1144 
1145 #if USB_OTG_HS_ULPI_PHY
1146 #if defined(CONFIG_SOC_SERIES_STM32H7X)
1147 	LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_USB1OTGHSULPI);
1148 #else
1149 	LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_OTGHSULPI);
1150 #endif
1151 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs) /* USB_OTG_HS_ULPI_PHY */
1152 	/* Disable ULPI interface (for external high-speed PHY) clock in sleep/low-power mode.
1153 	 * It is disabled by default in run power mode, no need to disable it.
1154 	 */
1155 #if defined(CONFIG_SOC_SERIES_STM32H7X)
1156 	LL_AHB1_GRP1_DisableClockSleep(LL_AHB1_GRP1_PERIPH_USB1OTGHSULPI);
1157 #elif defined(CONFIG_SOC_SERIES_STM32U5X)
1158 	LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_USBPHY);
1159 	/* Both OTG HS and USBPHY sleep clock MUST be disabled here at the same time */
1160 	LL_AHB2_GRP1_DisableClockStopSleep(LL_AHB2_GRP1_PERIPH_OTG_HS ||
1161 						LL_AHB2_GRP1_PERIPH_USBPHY);
1162 #else
1163 	LL_AHB1_GRP1_DisableClockLowPower(LL_AHB1_GRP1_PERIPH_OTGHSULPI);
1164 #endif /* defined(CONFIG_SOC_SERIES_STM32H7X) */
1165 
1166 #if USB_OTG_HS_EMB_PHY
1167 	LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_OTGPHYC);
1168 #endif
1169 #elif defined(CONFIG_SOC_SERIES_STM32H7X) && DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otgfs)
1170 	/* The USB2 controller only works in FS mode, but the ULPI clock needs
1171 	 * to be disabled in sleep mode for it to work.
1172 	 */
1173 	LL_AHB1_GRP1_DisableClockSleep(LL_AHB1_GRP1_PERIPH_USB2OTGHSULPI);
1174 #endif /* USB_OTG_HS_ULPI_PHY */
1175 
1176 	return 0;
1177 }
1178 
priv_clock_disable(void)1179 static int priv_clock_disable(void)
1180 {
1181 	const struct device *clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
1182 
1183 	if (clock_control_off(clk, (clock_control_subsys_t *)&pclken[0]) != 0) {
1184 		LOG_ERR("Unable to disable USB clock");
1185 		return -EIO;
1186 	}
1187 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs) && defined(CONFIG_SOC_SERIES_STM32U5X)
1188 	LL_AHB2_GRP1_DisableClock(LL_AHB2_GRP1_PERIPH_USBPHY);
1189 #endif
1190 
1191 	return 0;
1192 }
1193 
1194 static struct udc_ep_config ep_cfg_in[DT_INST_PROP(0, num_bidir_endpoints)];
1195 static struct udc_ep_config ep_cfg_out[DT_INST_PROP(0, num_bidir_endpoints)];
1196 
1197 PINCTRL_DT_INST_DEFINE(0);
1198 static const struct pinctrl_dev_config *usb_pcfg =
1199 					PINCTRL_DT_INST_DEV_CONFIG_GET(0);
1200 
1201 #if USB_OTG_HS_ULPI_PHY
1202 static const struct gpio_dt_spec ulpi_reset =
1203 	GPIO_DT_SPEC_GET_OR(DT_PHANDLE(DT_INST(0, st_stm32_otghs), phys), reset_gpios, {0});
1204 #endif
1205 
1206 static char udc_msgq_buf_0[CONFIG_UDC_STM32_MAX_QMESSAGES * sizeof(struct udc_stm32_msg)];
1207 
1208 K_THREAD_STACK_DEFINE(udc_stm32_stack_0, CONFIG_UDC_STM32_STACK_SIZE);
1209 
udc_stm32_driver_init0(const struct device * dev)1210 static int udc_stm32_driver_init0(const struct device *dev)
1211 {
1212 	struct udc_stm32_data *priv = udc_get_private(dev);
1213 	const struct udc_stm32_config *cfg = dev->config;
1214 	struct udc_data *data = dev->data;
1215 	int err;
1216 
1217 	for (unsigned int i = 0; i < ARRAY_SIZE(ep_cfg_out); i++) {
1218 		ep_cfg_out[i].caps.out = 1;
1219 		if (i == 0) {
1220 			ep_cfg_out[i].caps.control = 1;
1221 			ep_cfg_out[i].caps.mps = cfg->ep0_mps;
1222 		} else {
1223 			ep_cfg_out[i].caps.bulk = 1;
1224 			ep_cfg_out[i].caps.interrupt = 1;
1225 			ep_cfg_out[i].caps.iso = 1;
1226 			ep_cfg_out[i].caps.mps = cfg->ep_mps;
1227 		}
1228 
1229 		ep_cfg_out[i].addr = USB_EP_DIR_OUT | i;
1230 		err = udc_register_ep(dev, &ep_cfg_out[i]);
1231 		if (err != 0) {
1232 			LOG_ERR("Failed to register endpoint");
1233 			return err;
1234 		}
1235 	}
1236 
1237 	for (unsigned int i = 0; i < ARRAY_SIZE(ep_cfg_in); i++) {
1238 		ep_cfg_in[i].caps.in = 1;
1239 		if (i == 0) {
1240 			ep_cfg_in[i].caps.control = 1;
1241 			ep_cfg_in[i].caps.mps = cfg->ep0_mps;
1242 		} else {
1243 			ep_cfg_in[i].caps.bulk = 1;
1244 			ep_cfg_in[i].caps.interrupt = 1;
1245 			ep_cfg_in[i].caps.iso = 1;
1246 			ep_cfg_in[i].caps.mps = 1023;
1247 		}
1248 
1249 		ep_cfg_in[i].addr = USB_EP_DIR_IN | i;
1250 		err = udc_register_ep(dev, &ep_cfg_in[i]);
1251 		if (err != 0) {
1252 			LOG_ERR("Failed to register endpoint");
1253 			return err;
1254 		}
1255 	}
1256 
1257 	data->caps.rwup = true;
1258 	data->caps.out_ack = false;
1259 	data->caps.mps0 = UDC_MPS0_64;
1260 	if (cfg->speed_idx == 2) {
1261 		data->caps.hs = true;
1262 	}
1263 
1264 	priv->dev = dev;
1265 	priv->irq = UDC_STM32_IRQ;
1266 	priv->clk_enable = priv_clock_enable;
1267 	priv->clk_disable = priv_clock_disable;
1268 	priv->pcd_prepare = priv_pcd_prepare;
1269 
1270 	k_msgq_init(&priv->msgq_data, udc_msgq_buf_0, sizeof(struct udc_stm32_msg),
1271 		    CONFIG_UDC_STM32_MAX_QMESSAGES);
1272 
1273 	k_thread_create(&priv->thread_data, udc_stm32_stack_0,
1274 			K_THREAD_STACK_SIZEOF(udc_stm32_stack_0), udc_stm32_thread_handler,
1275 			(void *)dev, NULL, NULL, K_PRIO_COOP(CONFIG_UDC_STM32_THREAD_PRIORITY),
1276 			K_ESSENTIAL, K_NO_WAIT);
1277 	k_thread_name_set(&priv->thread_data, dev->name);
1278 
1279 	IRQ_CONNECT(UDC_STM32_IRQ, UDC_STM32_IRQ_PRI, udc_stm32_irq,
1280 		    DEVICE_DT_INST_GET(0), 0);
1281 
1282 	err = pinctrl_apply_state(usb_pcfg, PINCTRL_STATE_DEFAULT);
1283 	if (err < 0) {
1284 		LOG_ERR("USB pinctrl setup failed (%d)", err);
1285 		return err;
1286 	}
1287 
1288 #ifdef SYSCFG_CFGR1_USB_IT_RMP
1289 	/*
1290 	 * STM32F302/F303: USB IRQ collides with CAN_1 IRQ (§14.1.3, RM0316)
1291 	 * Remap IRQ by default to enable use of both IPs simultaneoulsy
1292 	 * This should be done before calling any HAL function
1293 	 */
1294 	if (LL_APB2_GRP1_IsEnabledClock(LL_APB2_GRP1_PERIPH_SYSCFG)) {
1295 		LL_SYSCFG_EnableRemapIT_USB();
1296 	} else {
1297 		LOG_ERR("System Configuration Controller clock is "
1298 			"disabled. Unable to enable IRQ remapping.");
1299 	}
1300 #endif
1301 
1302 #if USB_OTG_HS_ULPI_PHY
1303 	if (ulpi_reset.port != NULL) {
1304 		if (!gpio_is_ready_dt(&ulpi_reset)) {
1305 			LOG_ERR("Reset GPIO device not ready");
1306 			return -EINVAL;
1307 		}
1308 		if (gpio_pin_configure_dt(&ulpi_reset, GPIO_OUTPUT_INACTIVE)) {
1309 			LOG_ERR("Couldn't configure reset pin");
1310 			return -EIO;
1311 		}
1312 	}
1313 #endif
1314 
1315 	/*cd
1316 	 * Required for at least STM32L4 devices as they electrically
1317 	 * isolate USB features from VDDUSB. It must be enabled before
1318 	 * USB can function. Refer to section 5.1.3 in DM00083560 or
1319 	 * DM00310109.
1320 	 */
1321 #ifdef PWR_CR2_USV
1322 #if defined(LL_APB1_GRP1_PERIPH_PWR)
1323 	if (LL_APB1_GRP1_IsEnabledClock(LL_APB1_GRP1_PERIPH_PWR)) {
1324 		LL_PWR_EnableVddUSB();
1325 	} else {
1326 		LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);
1327 		LL_PWR_EnableVddUSB();
1328 		LL_APB1_GRP1_DisableClock(LL_APB1_GRP1_PERIPH_PWR);
1329 	}
1330 	#else
1331 	LL_PWR_EnableVddUSB();
1332 #endif /* defined(LL_APB1_GRP1_PERIPH_PWR) */
1333 #endif /* PWR_CR2_USV */
1334 
1335 	return 0;
1336 }
1337 
1338 DEVICE_DT_INST_DEFINE(0, udc_stm32_driver_init0, NULL, &udc0_data, &udc0_cfg,
1339 		      POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE,
1340 		      &udc_stm32_api);
1341