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