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