1 /*
2  * Copyright (c) 2017 Christer Weinigel.
3  * Copyright (c) 2017, I-SENSE group of ICCS
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 /**
9  * @file
10  * @brief USB device controller shim driver for STM32 devices
11  *
12  * This driver uses the STM32 Cube low level drivers to talk to the USB
13  * device controller on the STM32 family of devices using the
14  * STM32Cube HAL layer.
15  */
16 
17 #include <soc.h>
18 #include <stm32_ll_bus.h>
19 #include <stm32_ll_pwr.h>
20 #include <stm32_ll_rcc.h>
21 #include <stm32_ll_system.h>
22 #include <string.h>
23 #include <zephyr/usb/usb_device.h>
24 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
25 #include <zephyr/sys/util.h>
26 #include <zephyr/drivers/gpio.h>
27 #include <zephyr/drivers/pinctrl.h>
28 #include "stm32_hsem.h"
29 
30 #define LOG_LEVEL CONFIG_USB_DRIVER_LOG_LEVEL
31 #include <zephyr/logging/log.h>
32 #include <zephyr/irq.h>
33 LOG_MODULE_REGISTER(usb_dc_stm32);
34 
35 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otgfs) && DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs)
36 #error "Only one interface should be enabled at a time, OTG FS or OTG HS"
37 #endif
38 
39 /*
40  * Vbus sensing is determined based on the presence of the hardware detection
41  * pin(s) in the device tree. E.g: pinctrl-0 = <&usb_otg_fs_vbus_pa9 ...>;
42  *
43  * The detection pins are dependent on the enabled USB driver and the physical
44  * interface(s) offered by the hardware. These are mapped to PA9 and/or PB13
45  * (subject to MCU), being the former the most widespread option.
46  */
47 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs)
48 #define DT_DRV_COMPAT    st_stm32_otghs
49 #define USB_IRQ_NAME     otghs
50 #define USB_VBUS_SENSING (DT_NODE_EXISTS(DT_CHILD(DT_NODELABEL(pinctrl), usb_otg_hs_vbus_pa9)) || \
51 			  DT_NODE_EXISTS(DT_CHILD(DT_NODELABEL(pinctrl), usb_otg_hs_vbus_pb13)))
52 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otgfs)
53 #define DT_DRV_COMPAT    st_stm32_otgfs
54 #define USB_IRQ_NAME     otgfs
55 #define USB_VBUS_SENSING DT_NODE_EXISTS(DT_CHILD(DT_NODELABEL(pinctrl), usb_otg_fs_vbus_pa9))
56 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_usb)
57 #define DT_DRV_COMPAT    st_stm32_usb
58 #define USB_IRQ_NAME     usb
59 #define USB_VBUS_SENSING false
60 #endif
61 
62 #define USB_BASE_ADDRESS	DT_INST_REG_ADDR(0)
63 #define USB_IRQ			DT_INST_IRQ_BY_NAME(0, USB_IRQ_NAME, irq)
64 #define USB_IRQ_PRI		DT_INST_IRQ_BY_NAME(0, USB_IRQ_NAME, priority)
65 #define USB_NUM_BIDIR_ENDPOINTS	DT_INST_PROP(0, num_bidir_endpoints)
66 #define USB_RAM_SIZE		DT_INST_PROP(0, ram_size)
67 
68 static const struct stm32_pclken pclken[] = STM32_DT_INST_CLOCKS(0);
69 
70 #if DT_INST_NODE_HAS_PROP(0, maximum_speed)
71 #define USB_MAXIMUM_SPEED	DT_INST_PROP(0, maximum_speed)
72 #endif
73 
74 PINCTRL_DT_INST_DEFINE(0);
75 static const struct pinctrl_dev_config *usb_pcfg =
76 					PINCTRL_DT_INST_DEV_CONFIG_GET(0);
77 
78 #define USB_OTG_HS_EMB_PHY (DT_HAS_COMPAT_STATUS_OKAY(st_stm32_usbphyc) && \
79 			    DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs))
80 
81 #define USB_OTG_HS_ULPI_PHY (DT_HAS_COMPAT_STATUS_OKAY(usb_ulpi_phy) && \
82 			    DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs))
83 
84 #if USB_OTG_HS_ULPI_PHY
85 static const struct gpio_dt_spec ulpi_reset =
86 	GPIO_DT_SPEC_GET_OR(DT_PHANDLE(DT_INST(0, st_stm32_otghs), phys), reset_gpios, {0});
87 #endif
88 
89 /*
90  * USB, USB_OTG_FS and USB_DRD_FS are defined in STM32Cube HAL and allows to
91  * distinguish between two kind of USB DC. STM32 F0, F3, L0 and G4 series
92  * support USB device controller. STM32 F4 and F7 series support USB_OTG_FS
93  * device controller. STM32 F1 and L4 series support either USB or USB_OTG_FS
94  * device controller.STM32 G0 series supports USB_DRD_FS device controller.
95  *
96  * WARNING: Don't mix USB defined in STM32Cube HAL and CONFIG_USB_* from Zephyr
97  * Kconfig system.
98  */
99 #if defined(USB) || defined(USB_DRD_FS)
100 
101 #define EP0_MPS 64U
102 #define EP_MPS 64U
103 
104 /*
105  * USB BTABLE is stored in the PMA. The size of BTABLE is 4 bytes
106  * per endpoint.
107  *
108  */
109 #define USB_BTABLE_SIZE  (8 * USB_NUM_BIDIR_ENDPOINTS)
110 
111 #else /* USB_OTG_FS */
112 
113 /*
114  * STM32L4 series USB LL API doesn't provide HIGH and HIGH_IN_FULL speed
115  * defines.
116  */
117 #if defined(CONFIG_SOC_SERIES_STM32L4X)
118 #define USB_OTG_SPEED_HIGH                     0U
119 #define USB_OTG_SPEED_HIGH_IN_FULL             1U
120 #endif /* CONFIG_SOC_SERIES_STM32L4X */
121 
122 #define EP0_MPS USB_OTG_MAX_EP0_SIZE
123 
124 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs)
125 #define EP_MPS USB_OTG_HS_MAX_PACKET_SIZE
126 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otgfs) || DT_HAS_COMPAT_STATUS_OKAY(st_stm32_usb)
127 #define EP_MPS USB_OTG_FS_MAX_PACKET_SIZE
128 #endif
129 
130 /* We need n TX IN FIFOs */
131 #define TX_FIFO_NUM USB_NUM_BIDIR_ENDPOINTS
132 
133 /* We need a minimum size for RX FIFO - exact number seemingly determined through trial and error */
134 #define RX_FIFO_EP_WORDS 160
135 
136 /* Allocate FIFO memory evenly between the TX FIFOs */
137 /* except the first TX endpoint need only 64 bytes */
138 #define TX_FIFO_EP_0_WORDS 16
139 #define TX_FIFO_WORDS (USB_RAM_SIZE / 4 - RX_FIFO_EP_WORDS - TX_FIFO_EP_0_WORDS)
140 /* Number of words for each remaining TX endpoint FIFO */
141 #define TX_FIFO_EP_WORDS (TX_FIFO_WORDS / (TX_FIFO_NUM - 1))
142 
143 #endif /* USB */
144 
145 /* Size of a USB SETUP packet */
146 #define SETUP_SIZE 8
147 
148 /* Helper macros to make it easier to work with endpoint numbers */
149 #define EP0_IDX 0
150 #define EP0_IN (EP0_IDX | USB_EP_DIR_IN)
151 #define EP0_OUT (EP0_IDX | USB_EP_DIR_OUT)
152 
153 /* Endpoint state */
154 struct usb_dc_stm32_ep_state {
155 	uint16_t ep_mps;		/** Endpoint max packet size */
156 	uint16_t ep_pma_buf_len;	/** Previously allocated buffer size */
157 	uint8_t ep_type;		/** Endpoint type (STM32 HAL enum) */
158 	uint8_t ep_stalled;	/** Endpoint stall flag */
159 	usb_dc_ep_callback cb;	/** Endpoint callback function */
160 	uint32_t read_count;	/** Number of bytes in read buffer  */
161 	uint32_t read_offset;	/** Current offset in read buffer */
162 	struct k_sem write_sem;	/** Write boolean semaphore */
163 };
164 
165 /* Driver state */
166 struct usb_dc_stm32_state {
167 	PCD_HandleTypeDef pcd;	/* Storage for the HAL_PCD api */
168 	usb_dc_status_callback status_cb; /* Status callback */
169 	struct usb_dc_stm32_ep_state out_ep_state[USB_NUM_BIDIR_ENDPOINTS];
170 	struct usb_dc_stm32_ep_state in_ep_state[USB_NUM_BIDIR_ENDPOINTS];
171 	uint8_t ep_buf[USB_NUM_BIDIR_ENDPOINTS][EP_MPS];
172 
173 #if defined(USB) || defined(USB_DRD_FS)
174 	uint32_t pma_offset;
175 #endif /* USB */
176 };
177 
178 static struct usb_dc_stm32_state usb_dc_stm32_state;
179 
180 /* Internal functions */
181 
usb_dc_stm32_get_ep_state(uint8_t ep)182 static struct usb_dc_stm32_ep_state *usb_dc_stm32_get_ep_state(uint8_t ep)
183 {
184 	struct usb_dc_stm32_ep_state *ep_state_base;
185 
186 	if (USB_EP_GET_IDX(ep) >= USB_NUM_BIDIR_ENDPOINTS) {
187 		return NULL;
188 	}
189 
190 	if (USB_EP_DIR_IS_OUT(ep)) {
191 		ep_state_base = usb_dc_stm32_state.out_ep_state;
192 	} else {
193 		ep_state_base = usb_dc_stm32_state.in_ep_state;
194 	}
195 
196 	return ep_state_base + USB_EP_GET_IDX(ep);
197 }
198 
usb_dc_stm32_isr(const void * arg)199 static void usb_dc_stm32_isr(const void *arg)
200 {
201 	HAL_PCD_IRQHandler(&usb_dc_stm32_state.pcd);
202 }
203 
204 #ifdef CONFIG_USB_DEVICE_SOF
HAL_PCD_SOFCallback(PCD_HandleTypeDef * hpcd)205 void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd)
206 {
207 	usb_dc_stm32_state.status_cb(USB_DC_SOF, NULL);
208 }
209 #endif
210 
usb_dc_stm32_clock_enable(void)211 static int usb_dc_stm32_clock_enable(void)
212 {
213 	const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
214 
215 	if (!device_is_ready(clk)) {
216 		LOG_ERR("clock control device not ready");
217 		return -ENODEV;
218 	}
219 
220 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs) && defined(CONFIG_SOC_SERIES_STM32U5X)
221 	/* Sequence to enable the power of the OTG HS on a stm32U5 serie : Enable VDDUSB */
222 	bool pwr_clk = LL_AHB3_GRP1_IsEnabledClock(LL_AHB3_GRP1_PERIPH_PWR);
223 
224 	if (!pwr_clk) {
225 		LL_AHB3_GRP1_EnableClock(LL_AHB3_GRP1_PERIPH_PWR);
226 	}
227 
228 	/* Check that power range is 1 or 2 */
229 	if (LL_PWR_GetRegulVoltageScaling() < LL_PWR_REGU_VOLTAGE_SCALE2) {
230 		LOG_ERR("Wrong Power range to use USB OTG HS");
231 		return -EIO;
232 	}
233 
234 	LL_PWR_EnableVddUSB();
235 	/* Configure VOSR register of USB HSTransceiverSupply(); */
236 	LL_PWR_EnableUSBPowerSupply();
237 	LL_PWR_EnableUSBEPODBooster();
238 	while (LL_PWR_IsActiveFlag_USBBOOST() != 1) {
239 		/* Wait for USB EPOD BOOST ready */
240 	}
241 
242 	/* Leave the PWR clock in its initial position */
243 	if (!pwr_clk) {
244 		LL_AHB3_GRP1_DisableClock(LL_AHB3_GRP1_PERIPH_PWR);
245 	}
246 
247 	/* Set the OTG PHY reference clock selection (through SYSCFG) block */
248 	LL_APB3_GRP1_EnableClock(LL_APB3_GRP1_PERIPH_SYSCFG);
249 	HAL_SYSCFG_SetOTGPHYReferenceClockSelection(SYSCFG_OTG_HS_PHY_CLK_SELECT_1);
250 	/* Configuring the SYSCFG registers OTG_HS PHY : OTG_HS PHY enable*/
251 	HAL_SYSCFG_EnableOTGPHY(SYSCFG_OTG_HS_PHY_ENABLE);
252 #elif defined(PWR_USBSCR_USB33SV) || defined(PWR_SVMCR_USV)
253 	/*
254 	 * VDDUSB independent USB supply (PWR clock is on)
255 	 * with LL_PWR_EnableVDDUSB function (higher case)
256 	 */
257 	LL_PWR_EnableVDDUSB();
258 #endif
259 
260 	if (DT_INST_NUM_CLOCKS(0) > 1) {
261 		if (clock_control_configure(clk, (clock_control_subsys_t)&pclken[1],
262 									NULL) != 0) {
263 			LOG_ERR("Could not select USB domain clock");
264 			return -EIO;
265 		}
266 	}
267 
268 	if (clock_control_on(clk, (clock_control_subsys_t)&pclken[0]) != 0) {
269 		LOG_ERR("Unable to enable USB clock");
270 		return -EIO;
271 	}
272 
273 	if (IS_ENABLED(CONFIG_USB_DC_STM32_CLOCK_CHECK)) {
274 		uint32_t usb_clock_rate;
275 
276 		if (clock_control_get_rate(clk,
277 					   (clock_control_subsys_t)&pclken[1],
278 					   &usb_clock_rate) != 0) {
279 			LOG_ERR("Failed to get USB domain clock rate");
280 			return -EIO;
281 		}
282 
283 		if (usb_clock_rate != MHZ(48)) {
284 			LOG_ERR("USB Clock is not 48MHz (%d)", usb_clock_rate);
285 			return -ENOTSUP;
286 		}
287 	}
288 
289 	/* Previous check won't work in case of F1/F3. Add build time check */
290 #if defined(RCC_CFGR_OTGFSPRE) || defined(RCC_CFGR_USBPRE)
291 
292 #if (MHZ(48) == CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC) && !defined(STM32_PLL_USBPRE)
293 	/* PLL output clock is set to 48MHz, it should not be divided */
294 #warning USBPRE/OTGFSPRE should be set in rcc node
295 #endif
296 
297 #endif /* RCC_CFGR_OTGFSPRE / RCC_CFGR_USBPRE */
298 
299 #if USB_OTG_HS_ULPI_PHY
300 #if defined(CONFIG_SOC_SERIES_STM32H7X)
301 	LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_USB1OTGHSULPI);
302 #else
303 	LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_OTGHSULPI);
304 #endif
305 #elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs) /* USB_OTG_HS_ULPI_PHY */
306 	/* Disable ULPI interface (for external high-speed PHY) clock in sleep/low-power mode.
307 	 * It is disabled by default in run power mode, no need to disable it.
308 	 */
309 #if defined(CONFIG_SOC_SERIES_STM32H7X)
310 	LL_AHB1_GRP1_DisableClockSleep(LL_AHB1_GRP1_PERIPH_USB1OTGHSULPI);
311 #elif defined(CONFIG_SOC_SERIES_STM32U5X)
312 	LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_USBPHY);
313 	/* Both OTG HS and USBPHY sleep clock MUST be disabled here at the same time */
314 	LL_AHB2_GRP1_DisableClockStopSleep(LL_AHB2_GRP1_PERIPH_OTG_HS ||
315 						LL_AHB2_GRP1_PERIPH_USBPHY);
316 #else
317 	LL_AHB1_GRP1_DisableClockLowPower(LL_AHB1_GRP1_PERIPH_OTGHSULPI);
318 #endif
319 
320 #if USB_OTG_HS_EMB_PHY
321 	LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_OTGPHYC);
322 #endif
323 #endif /* USB_OTG_HS_ULPI_PHY */
324 
325 	return 0;
326 }
327 
usb_dc_stm32_clock_disable(void)328 static int usb_dc_stm32_clock_disable(void)
329 {
330 	const struct device *clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
331 
332 	if (clock_control_off(clk, (clock_control_subsys_t)&pclken[0]) != 0) {
333 		LOG_ERR("Unable to disable USB clock");
334 		return -EIO;
335 	}
336 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs) && defined(CONFIG_SOC_SERIES_STM32U5X)
337 	LL_AHB2_GRP1_DisableClock(LL_AHB2_GRP1_PERIPH_USBPHY);
338 #endif
339 
340 	return 0;
341 }
342 
343 #if defined(USB_OTG_FS) || defined(USB_OTG_HS)
usb_dc_stm32_get_maximum_speed(void)344 static uint32_t usb_dc_stm32_get_maximum_speed(void)
345 {
346 	/*
347 	 * If max-speed is not passed via DT, set it to USB controller's
348 	 * maximum hardware capability.
349 	 */
350 #if USB_OTG_HS_EMB_PHY || USB_OTG_HS_ULPI_PHY
351 	uint32_t speed = USB_OTG_SPEED_HIGH;
352 #else
353 	uint32_t speed = USB_OTG_SPEED_FULL;
354 #endif
355 
356 #ifdef USB_MAXIMUM_SPEED
357 
358 	if (!strncmp(USB_MAXIMUM_SPEED, "high-speed", 10)) {
359 		speed = USB_OTG_SPEED_HIGH;
360 	} else if (!strncmp(USB_MAXIMUM_SPEED, "full-speed", 10)) {
361 #if defined(CONFIG_SOC_SERIES_STM32H7X) || defined(USB_OTG_HS_EMB_PHY)
362 		speed = USB_OTG_SPEED_HIGH_IN_FULL;
363 #else
364 		speed = USB_OTG_SPEED_FULL;
365 #endif
366 	} else {
367 		LOG_DBG("Unsupported maximum speed defined in device tree. "
368 			"USB controller will default to its maximum HW "
369 			"capability");
370 	}
371 #endif
372 
373 	return speed;
374 }
375 #endif /* USB_OTG_FS || USB_OTG_HS */
376 
usb_dc_stm32_init(void)377 static int usb_dc_stm32_init(void)
378 {
379 	HAL_StatusTypeDef status;
380 	int ret;
381 	unsigned int i;
382 
383 #if defined(USB) || defined(USB_DRD_FS)
384 #ifdef USB
385 	usb_dc_stm32_state.pcd.Instance = USB;
386 #else
387 	usb_dc_stm32_state.pcd.Instance = USB_DRD_FS;
388 #endif
389 	usb_dc_stm32_state.pcd.Init.speed = PCD_SPEED_FULL;
390 	usb_dc_stm32_state.pcd.Init.dev_endpoints = USB_NUM_BIDIR_ENDPOINTS;
391 	usb_dc_stm32_state.pcd.Init.phy_itface = PCD_PHY_EMBEDDED;
392 	usb_dc_stm32_state.pcd.Init.ep0_mps = PCD_EP0MPS_64;
393 	usb_dc_stm32_state.pcd.Init.low_power_enable = 0;
394 #else /* USB_OTG_FS || USB_OTG_HS */
395 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs)
396 	usb_dc_stm32_state.pcd.Instance = USB_OTG_HS;
397 #else
398 	usb_dc_stm32_state.pcd.Instance = USB_OTG_FS;
399 #endif
400 	usb_dc_stm32_state.pcd.Init.dev_endpoints = USB_NUM_BIDIR_ENDPOINTS;
401 	usb_dc_stm32_state.pcd.Init.speed = usb_dc_stm32_get_maximum_speed();
402 #if USB_OTG_HS_EMB_PHY
403 	usb_dc_stm32_state.pcd.Init.phy_itface = USB_OTG_HS_EMBEDDED_PHY;
404 #elif USB_OTG_HS_ULPI_PHY
405 	usb_dc_stm32_state.pcd.Init.phy_itface = USB_OTG_ULPI_PHY;
406 #else
407 	usb_dc_stm32_state.pcd.Init.phy_itface = PCD_PHY_EMBEDDED;
408 #endif
409 	usb_dc_stm32_state.pcd.Init.ep0_mps = USB_OTG_MAX_EP0_SIZE;
410 	usb_dc_stm32_state.pcd.Init.vbus_sensing_enable = USB_VBUS_SENSING ? ENABLE : DISABLE;
411 
412 #ifndef CONFIG_SOC_SERIES_STM32F1X
413 	usb_dc_stm32_state.pcd.Init.dma_enable = DISABLE;
414 #endif
415 
416 #endif /* USB */
417 
418 #ifdef CONFIG_USB_DEVICE_SOF
419 	usb_dc_stm32_state.pcd.Init.Sof_enable = 1;
420 #endif /* CONFIG_USB_DEVICE_SOF */
421 
422 #if defined(CONFIG_SOC_SERIES_STM32H7X)
423 #if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otgfs)
424 	/* The USB2 controller only works in FS mode, but the ULPI clock needs
425 	 * to be disabled in sleep mode for it to work. For the USB1
426 	 * controller, as it is an HS one, the clock is disabled in the common
427 	 * path.
428 	 */
429 
430 	LL_AHB1_GRP1_DisableClockSleep(LL_AHB1_GRP1_PERIPH_USB2OTGHSULPI);
431 #endif
432 
433 	LL_PWR_EnableUSBVoltageDetector();
434 
435 	/* Per AN2606: USBREGEN not supported when running in FS mode. */
436 	LL_PWR_DisableUSBReg();
437 	while (!LL_PWR_IsActiveFlag_USB()) {
438 		LOG_INF("PWR not active yet");
439 		k_sleep(K_MSEC(100));
440 	}
441 #endif
442 
443 	LOG_DBG("Pinctrl signals configuration");
444 	ret = pinctrl_apply_state(usb_pcfg, PINCTRL_STATE_DEFAULT);
445 	if (ret < 0) {
446 		LOG_ERR("USB pinctrl setup failed (%d)", ret);
447 		return ret;
448 	}
449 
450 	LOG_DBG("HAL_PCD_Init");
451 	status = HAL_PCD_Init(&usb_dc_stm32_state.pcd);
452 	if (status != HAL_OK) {
453 		LOG_ERR("PCD_Init failed, %d", (int)status);
454 		return -EIO;
455 	}
456 
457 	/* On a soft reset force USB to reset first and switch it off
458 	 * so the USB connection can get re-initialized
459 	 */
460 	LOG_DBG("HAL_PCD_Stop");
461 	status = HAL_PCD_Stop(&usb_dc_stm32_state.pcd);
462 	if (status != HAL_OK) {
463 		LOG_ERR("PCD_Stop failed, %d", (int)status);
464 		return -EIO;
465 	}
466 
467 	LOG_DBG("HAL_PCD_Start");
468 	status = HAL_PCD_Start(&usb_dc_stm32_state.pcd);
469 	if (status != HAL_OK) {
470 		LOG_ERR("PCD_Start failed, %d", (int)status);
471 		return -EIO;
472 	}
473 
474 	usb_dc_stm32_state.out_ep_state[EP0_IDX].ep_mps = EP0_MPS;
475 	usb_dc_stm32_state.out_ep_state[EP0_IDX].ep_type = EP_TYPE_CTRL;
476 	usb_dc_stm32_state.in_ep_state[EP0_IDX].ep_mps = EP0_MPS;
477 	usb_dc_stm32_state.in_ep_state[EP0_IDX].ep_type = EP_TYPE_CTRL;
478 
479 #if defined(USB) || defined(USB_DRD_FS)
480 	/* Start PMA configuration for the endpoints after the BTABLE. */
481 	usb_dc_stm32_state.pma_offset = USB_BTABLE_SIZE;
482 
483 	for (i = 0U; i < USB_NUM_BIDIR_ENDPOINTS; i++) {
484 		k_sem_init(&usb_dc_stm32_state.in_ep_state[i].write_sem, 1, 1);
485 	}
486 #else /* USB_OTG_FS */
487 
488 	/* TODO: make this dynamic (depending usage) */
489 	HAL_PCDEx_SetRxFiFo(&usb_dc_stm32_state.pcd, RX_FIFO_EP_WORDS);
490 	for (i = 0U; i < USB_NUM_BIDIR_ENDPOINTS; i++) {
491 		if (i == 0) {
492 			/* first endpoint need only 64 byte for EP_TYPE_CTRL */
493 			HAL_PCDEx_SetTxFiFo(&usb_dc_stm32_state.pcd, i,
494 					TX_FIFO_EP_0_WORDS);
495 		} else {
496 			HAL_PCDEx_SetTxFiFo(&usb_dc_stm32_state.pcd, i,
497 					TX_FIFO_EP_WORDS);
498 		}
499 		k_sem_init(&usb_dc_stm32_state.in_ep_state[i].write_sem, 1, 1);
500 	}
501 #endif /* USB */
502 
503 	IRQ_CONNECT(USB_IRQ, USB_IRQ_PRI,
504 		    usb_dc_stm32_isr, 0, 0);
505 	irq_enable(USB_IRQ);
506 	return 0;
507 }
508 
509 /* Zephyr USB device controller API implementation */
510 
usb_dc_attach(void)511 int usb_dc_attach(void)
512 {
513 	int ret;
514 
515 	LOG_DBG("");
516 
517 #ifdef SYSCFG_CFGR1_USB_IT_RMP
518 	/*
519 	 * STM32F302/F303: USB IRQ collides with CAN_1 IRQ (§14.1.3, RM0316)
520 	 * Remap IRQ by default to enable use of both IPs simultaneoulsy
521 	 * This should be done before calling any HAL function
522 	 */
523 	if (LL_APB2_GRP1_IsEnabledClock(LL_APB2_GRP1_PERIPH_SYSCFG)) {
524 		LL_SYSCFG_EnableRemapIT_USB();
525 	} else {
526 		LOG_ERR("System Configuration Controller clock is "
527 			"disabled. Unable to enable IRQ remapping.");
528 	}
529 #endif
530 
531 #if USB_OTG_HS_ULPI_PHY
532 	if (ulpi_reset.port != NULL) {
533 		if (!gpio_is_ready_dt(&ulpi_reset)) {
534 			LOG_ERR("Reset GPIO device not ready");
535 			return -EINVAL;
536 		}
537 		if (gpio_pin_configure_dt(&ulpi_reset, GPIO_OUTPUT_INACTIVE)) {
538 			LOG_ERR("Couldn't configure reset pin");
539 			return -EIO;
540 		}
541 	}
542 #endif
543 
544 	ret = usb_dc_stm32_clock_enable();
545 	if (ret) {
546 		return ret;
547 	}
548 
549 	ret = usb_dc_stm32_init();
550 	if (ret) {
551 		return ret;
552 	}
553 
554 	/*
555 	 * Required for at least STM32L4 devices as they electrically
556 	 * isolate USB features from VddUSB. It must be enabled before
557 	 * USB can function. Refer to section 5.1.3 in DM00083560 or
558 	 * DM00310109.
559 	 */
560 #ifdef PWR_CR2_USV
561 #if defined(LL_APB1_GRP1_PERIPH_PWR)
562 	if (LL_APB1_GRP1_IsEnabledClock(LL_APB1_GRP1_PERIPH_PWR)) {
563 		LL_PWR_EnableVddUSB();
564 	} else {
565 		LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);
566 		LL_PWR_EnableVddUSB();
567 		LL_APB1_GRP1_DisableClock(LL_APB1_GRP1_PERIPH_PWR);
568 	}
569 #else
570 	LL_PWR_EnableVddUSB();
571 #endif /* defined(LL_APB1_GRP1_PERIPH_PWR) */
572 #endif /* PWR_CR2_USV */
573 
574 	return 0;
575 }
576 
usb_dc_ep_set_callback(const uint8_t ep,const usb_dc_ep_callback cb)577 int usb_dc_ep_set_callback(const uint8_t ep, const usb_dc_ep_callback cb)
578 {
579 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
580 
581 	LOG_DBG("ep 0x%02x", ep);
582 
583 	if (!ep_state) {
584 		return -EINVAL;
585 	}
586 
587 	ep_state->cb = cb;
588 
589 	return 0;
590 }
591 
usb_dc_set_status_callback(const usb_dc_status_callback cb)592 void usb_dc_set_status_callback(const usb_dc_status_callback cb)
593 {
594 	LOG_DBG("");
595 
596 	usb_dc_stm32_state.status_cb = cb;
597 }
598 
usb_dc_set_address(const uint8_t addr)599 int usb_dc_set_address(const uint8_t addr)
600 {
601 	HAL_StatusTypeDef status;
602 
603 	LOG_DBG("addr %u (0x%02x)", addr, addr);
604 
605 	status = HAL_PCD_SetAddress(&usb_dc_stm32_state.pcd, addr);
606 	if (status != HAL_OK) {
607 		LOG_ERR("HAL_PCD_SetAddress failed(0x%02x), %d", addr,
608 			(int)status);
609 		return -EIO;
610 	}
611 
612 	return 0;
613 }
614 
usb_dc_ep_start_read(uint8_t ep,uint8_t * data,uint32_t max_data_len)615 int usb_dc_ep_start_read(uint8_t ep, uint8_t *data, uint32_t max_data_len)
616 {
617 	HAL_StatusTypeDef status;
618 
619 	LOG_DBG("ep 0x%02x, len %u", ep, max_data_len);
620 
621 	/* we flush EP0_IN by doing a 0 length receive on it */
622 	if (!USB_EP_DIR_IS_OUT(ep) && (ep != EP0_IN || max_data_len)) {
623 		LOG_ERR("invalid ep 0x%02x", ep);
624 		return -EINVAL;
625 	}
626 
627 	if (max_data_len > EP_MPS) {
628 		max_data_len = EP_MPS;
629 	}
630 
631 	status = HAL_PCD_EP_Receive(&usb_dc_stm32_state.pcd, ep,
632 				    usb_dc_stm32_state.ep_buf[USB_EP_GET_IDX(ep)],
633 				    max_data_len);
634 	if (status != HAL_OK) {
635 		LOG_ERR("HAL_PCD_EP_Receive failed(0x%02x), %d", ep,
636 			(int)status);
637 		return -EIO;
638 	}
639 
640 	return 0;
641 }
642 
usb_dc_ep_get_read_count(uint8_t ep,uint32_t * read_bytes)643 int usb_dc_ep_get_read_count(uint8_t ep, uint32_t *read_bytes)
644 {
645 	if (!USB_EP_DIR_IS_OUT(ep) || !read_bytes) {
646 		LOG_ERR("invalid ep 0x%02x", ep);
647 		return -EINVAL;
648 	}
649 
650 	*read_bytes = HAL_PCD_EP_GetRxCount(&usb_dc_stm32_state.pcd, ep);
651 
652 	return 0;
653 }
654 
usb_dc_ep_check_cap(const struct usb_dc_ep_cfg_data * const cfg)655 int usb_dc_ep_check_cap(const struct usb_dc_ep_cfg_data * const cfg)
656 {
657 	uint8_t ep_idx = USB_EP_GET_IDX(cfg->ep_addr);
658 
659 	LOG_DBG("ep %x, mps %d, type %d", cfg->ep_addr, cfg->ep_mps,
660 		cfg->ep_type);
661 
662 	if ((cfg->ep_type == USB_DC_EP_CONTROL) && ep_idx) {
663 		LOG_ERR("invalid endpoint configuration");
664 		return -1;
665 	}
666 
667 	if (ep_idx > (USB_NUM_BIDIR_ENDPOINTS - 1)) {
668 		LOG_ERR("endpoint index/address out of range");
669 		return -1;
670 	}
671 
672 	return 0;
673 }
674 
usb_dc_ep_configure(const struct usb_dc_ep_cfg_data * const ep_cfg)675 int usb_dc_ep_configure(const struct usb_dc_ep_cfg_data * const ep_cfg)
676 {
677 	uint8_t ep = ep_cfg->ep_addr;
678 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
679 
680 	if (!ep_state) {
681 		return -EINVAL;
682 	}
683 
684 	LOG_DBG("ep 0x%02x, previous ep_mps %u, ep_mps %u, ep_type %u",
685 		ep_cfg->ep_addr, ep_state->ep_mps, ep_cfg->ep_mps,
686 		ep_cfg->ep_type);
687 #if defined(USB) || defined(USB_DRD_FS)
688 	if (ep_cfg->ep_mps > ep_state->ep_pma_buf_len) {
689 		if (ep_cfg->ep_type == USB_DC_EP_ISOCHRONOUS) {
690 			if (USB_RAM_SIZE <=
691 			   (usb_dc_stm32_state.pma_offset + ep_cfg->ep_mps*2)) {
692 				return -EINVAL;
693 			}
694 		} else if (USB_RAM_SIZE <=
695 			  (usb_dc_stm32_state.pma_offset + ep_cfg->ep_mps)) {
696 			return -EINVAL;
697 		}
698 
699 		if (ep_cfg->ep_type == USB_DC_EP_ISOCHRONOUS) {
700 			HAL_PCDEx_PMAConfig(&usb_dc_stm32_state.pcd, ep, PCD_DBL_BUF,
701 				usb_dc_stm32_state.pma_offset +
702 				((usb_dc_stm32_state.pma_offset + ep_cfg->ep_mps) << 16));
703 			ep_state->ep_pma_buf_len = ep_cfg->ep_mps*2;
704 			usb_dc_stm32_state.pma_offset += ep_cfg->ep_mps*2;
705 		} else {
706 			HAL_PCDEx_PMAConfig(&usb_dc_stm32_state.pcd, ep, PCD_SNG_BUF,
707 				usb_dc_stm32_state.pma_offset);
708 			ep_state->ep_pma_buf_len = ep_cfg->ep_mps;
709 			usb_dc_stm32_state.pma_offset += ep_cfg->ep_mps;
710 		}
711 	}
712 	if (ep_cfg->ep_type == USB_DC_EP_ISOCHRONOUS) {
713 		ep_state->ep_mps = ep_cfg->ep_mps*2;
714 	} else {
715 		ep_state->ep_mps = ep_cfg->ep_mps;
716 	}
717 #else
718 	ep_state->ep_mps = ep_cfg->ep_mps;
719 #endif
720 
721 	switch (ep_cfg->ep_type) {
722 	case USB_DC_EP_CONTROL:
723 		ep_state->ep_type = EP_TYPE_CTRL;
724 		break;
725 	case USB_DC_EP_ISOCHRONOUS:
726 		ep_state->ep_type = EP_TYPE_ISOC;
727 		break;
728 	case USB_DC_EP_BULK:
729 		ep_state->ep_type = EP_TYPE_BULK;
730 		break;
731 	case USB_DC_EP_INTERRUPT:
732 		ep_state->ep_type = EP_TYPE_INTR;
733 		break;
734 	default:
735 		return -EINVAL;
736 	}
737 
738 	return 0;
739 }
740 
usb_dc_ep_set_stall(const uint8_t ep)741 int usb_dc_ep_set_stall(const uint8_t ep)
742 {
743 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
744 	HAL_StatusTypeDef status;
745 
746 	LOG_DBG("ep 0x%02x", ep);
747 
748 	if (!ep_state) {
749 		return -EINVAL;
750 	}
751 
752 	status = HAL_PCD_EP_SetStall(&usb_dc_stm32_state.pcd, ep);
753 	if (status != HAL_OK) {
754 		LOG_ERR("HAL_PCD_EP_SetStall failed(0x%02x), %d", ep,
755 			(int)status);
756 		return -EIO;
757 	}
758 
759 	ep_state->ep_stalled = 1U;
760 
761 	return 0;
762 }
763 
usb_dc_ep_clear_stall(const uint8_t ep)764 int usb_dc_ep_clear_stall(const uint8_t ep)
765 {
766 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
767 	HAL_StatusTypeDef status;
768 
769 	LOG_DBG("ep 0x%02x", ep);
770 
771 	if (!ep_state) {
772 		return -EINVAL;
773 	}
774 
775 	status = HAL_PCD_EP_ClrStall(&usb_dc_stm32_state.pcd, ep);
776 	if (status != HAL_OK) {
777 		LOG_ERR("HAL_PCD_EP_ClrStall failed(0x%02x), %d", ep,
778 			(int)status);
779 		return -EIO;
780 	}
781 
782 	ep_state->ep_stalled = 0U;
783 	ep_state->read_count = 0U;
784 
785 	return 0;
786 }
787 
usb_dc_ep_is_stalled(const uint8_t ep,uint8_t * const stalled)788 int usb_dc_ep_is_stalled(const uint8_t ep, uint8_t *const stalled)
789 {
790 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
791 
792 	LOG_DBG("ep 0x%02x", ep);
793 
794 	if (!ep_state || !stalled) {
795 		return -EINVAL;
796 	}
797 
798 	*stalled = ep_state->ep_stalled;
799 
800 	return 0;
801 }
802 
usb_dc_ep_enable(const uint8_t ep)803 int usb_dc_ep_enable(const uint8_t ep)
804 {
805 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
806 	HAL_StatusTypeDef status;
807 
808 	LOG_DBG("ep 0x%02x", ep);
809 
810 	if (!ep_state) {
811 		return -EINVAL;
812 	}
813 
814 	LOG_DBG("HAL_PCD_EP_Open(0x%02x, %u, %u)", ep, ep_state->ep_mps,
815 		ep_state->ep_type);
816 
817 	status = HAL_PCD_EP_Open(&usb_dc_stm32_state.pcd, ep,
818 				 ep_state->ep_mps, ep_state->ep_type);
819 	if (status != HAL_OK) {
820 		LOG_ERR("HAL_PCD_EP_Open failed(0x%02x), %d", ep,
821 			(int)status);
822 		return -EIO;
823 	}
824 
825 	if (USB_EP_DIR_IS_OUT(ep) && ep != EP0_OUT) {
826 		return usb_dc_ep_start_read(ep,
827 					  usb_dc_stm32_state.ep_buf[USB_EP_GET_IDX(ep)],
828 					  ep_state->ep_mps);
829 	}
830 
831 	return 0;
832 }
833 
usb_dc_ep_disable(const uint8_t ep)834 int usb_dc_ep_disable(const uint8_t ep)
835 {
836 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
837 	HAL_StatusTypeDef status;
838 
839 	LOG_DBG("ep 0x%02x", ep);
840 
841 	if (!ep_state) {
842 		return -EINVAL;
843 	}
844 
845 	status = HAL_PCD_EP_Close(&usb_dc_stm32_state.pcd, ep);
846 	if (status != HAL_OK) {
847 		LOG_ERR("HAL_PCD_EP_Close failed(0x%02x), %d", ep,
848 			(int)status);
849 		return -EIO;
850 	}
851 
852 	return 0;
853 }
854 
usb_dc_ep_write(const uint8_t ep,const uint8_t * const data,const uint32_t data_len,uint32_t * const ret_bytes)855 int usb_dc_ep_write(const uint8_t ep, const uint8_t *const data,
856 		    const uint32_t data_len, uint32_t * const ret_bytes)
857 {
858 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
859 	HAL_StatusTypeDef status;
860 	uint32_t len = data_len;
861 	int ret = 0;
862 
863 	LOG_DBG("ep 0x%02x, len %u", ep, data_len);
864 
865 	if (!ep_state || !USB_EP_DIR_IS_IN(ep)) {
866 		LOG_ERR("invalid ep 0x%02x", ep);
867 		return -EINVAL;
868 	}
869 
870 	ret = k_sem_take(&ep_state->write_sem, K_NO_WAIT);
871 	if (ret) {
872 		LOG_ERR("Unable to get write lock (%d)", ret);
873 		return -EAGAIN;
874 	}
875 
876 	if (!k_is_in_isr()) {
877 		irq_disable(USB_IRQ);
878 	}
879 
880 	if (ep == EP0_IN && len > USB_MAX_CTRL_MPS) {
881 		len = USB_MAX_CTRL_MPS;
882 	}
883 
884 	status = HAL_PCD_EP_Transmit(&usb_dc_stm32_state.pcd, ep,
885 				     (void *)data, len);
886 	if (status != HAL_OK) {
887 		LOG_ERR("HAL_PCD_EP_Transmit failed(0x%02x), %d", ep,
888 			(int)status);
889 		k_sem_give(&ep_state->write_sem);
890 		ret = -EIO;
891 	}
892 
893 	if (!ret && ep == EP0_IN && len > 0) {
894 		/* Wait for an empty package as from the host.
895 		 * This also flushes the TX FIFO to the host.
896 		 */
897 		usb_dc_ep_start_read(ep, NULL, 0);
898 	}
899 
900 	if (!k_is_in_isr()) {
901 		irq_enable(USB_IRQ);
902 	}
903 
904 	if (!ret && ret_bytes) {
905 		*ret_bytes = len;
906 	}
907 
908 	return ret;
909 }
910 
usb_dc_ep_read_wait(uint8_t ep,uint8_t * data,uint32_t max_data_len,uint32_t * read_bytes)911 int usb_dc_ep_read_wait(uint8_t ep, uint8_t *data, uint32_t max_data_len,
912 			uint32_t *read_bytes)
913 {
914 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
915 	uint32_t read_count;
916 
917 	if (!ep_state) {
918 		LOG_ERR("Invalid Endpoint %x", ep);
919 		return -EINVAL;
920 	}
921 
922 	read_count = ep_state->read_count;
923 
924 	LOG_DBG("ep 0x%02x, %u bytes, %u+%u, %p", ep, max_data_len,
925 		ep_state->read_offset, read_count, (void *)data);
926 
927 	if (!USB_EP_DIR_IS_OUT(ep)) { /* check if OUT ep */
928 		LOG_ERR("Wrong endpoint direction: 0x%02x", ep);
929 		return -EINVAL;
930 	}
931 
932 	/* When both buffer and max data to read are zero, just ignore reading
933 	 * and return available data in buffer. Otherwise, return data
934 	 * previously stored in the buffer.
935 	 */
936 	if (data) {
937 		read_count = MIN(read_count, max_data_len);
938 		memcpy(data, usb_dc_stm32_state.ep_buf[USB_EP_GET_IDX(ep)] +
939 		       ep_state->read_offset, read_count);
940 		ep_state->read_count -= read_count;
941 		ep_state->read_offset += read_count;
942 	} else if (max_data_len) {
943 		LOG_ERR("Wrong arguments");
944 	}
945 
946 	if (read_bytes) {
947 		*read_bytes = read_count;
948 	}
949 
950 	return 0;
951 }
952 
usb_dc_ep_read_continue(uint8_t ep)953 int usb_dc_ep_read_continue(uint8_t ep)
954 {
955 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
956 
957 	if (!ep_state || !USB_EP_DIR_IS_OUT(ep)) { /* Check if OUT ep */
958 		LOG_ERR("Not valid endpoint: %02x", ep);
959 		return -EINVAL;
960 	}
961 
962 	/* If no more data in the buffer, start a new read transaction.
963 	 * DataOutStageCallback will called on transaction complete.
964 	 */
965 	if (!ep_state->read_count) {
966 		usb_dc_ep_start_read(ep, usb_dc_stm32_state.ep_buf[USB_EP_GET_IDX(ep)],
967 				     ep_state->ep_mps);
968 	}
969 
970 	return 0;
971 }
972 
usb_dc_ep_read(const uint8_t ep,uint8_t * const data,const uint32_t max_data_len,uint32_t * const read_bytes)973 int usb_dc_ep_read(const uint8_t ep, uint8_t *const data, const uint32_t max_data_len,
974 		   uint32_t * const read_bytes)
975 {
976 	if (usb_dc_ep_read_wait(ep, data, max_data_len, read_bytes) != 0) {
977 		return -EINVAL;
978 	}
979 
980 	if (usb_dc_ep_read_continue(ep) != 0) {
981 		return -EINVAL;
982 	}
983 
984 	return 0;
985 }
986 
usb_dc_ep_halt(const uint8_t ep)987 int usb_dc_ep_halt(const uint8_t ep)
988 {
989 	return usb_dc_ep_set_stall(ep);
990 }
991 
usb_dc_ep_flush(const uint8_t ep)992 int usb_dc_ep_flush(const uint8_t ep)
993 {
994 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
995 
996 	if (!ep_state) {
997 		return -EINVAL;
998 	}
999 
1000 	LOG_ERR("Not implemented");
1001 
1002 	return 0;
1003 }
1004 
usb_dc_ep_mps(const uint8_t ep)1005 int usb_dc_ep_mps(const uint8_t ep)
1006 {
1007 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
1008 
1009 	if (!ep_state) {
1010 		return -EINVAL;
1011 	}
1012 
1013 	return ep_state->ep_mps;
1014 }
1015 
usb_dc_wakeup_request(void)1016 int usb_dc_wakeup_request(void)
1017 {
1018 	HAL_StatusTypeDef status;
1019 
1020 	status = HAL_PCD_ActivateRemoteWakeup(&usb_dc_stm32_state.pcd);
1021 	if (status != HAL_OK) {
1022 		return -EAGAIN;
1023 	}
1024 
1025 	/* Must be active from 1ms to 15ms as per reference manual. */
1026 	k_sleep(K_MSEC(2));
1027 
1028 	status = HAL_PCD_DeActivateRemoteWakeup(&usb_dc_stm32_state.pcd);
1029 	if (status != HAL_OK) {
1030 		return -EAGAIN;
1031 	}
1032 
1033 	return 0;
1034 }
1035 
usb_dc_detach(void)1036 int usb_dc_detach(void)
1037 {
1038 	HAL_StatusTypeDef status;
1039 	int ret;
1040 
1041 	LOG_DBG("HAL_PCD_DeInit");
1042 	status = HAL_PCD_DeInit(&usb_dc_stm32_state.pcd);
1043 	if (status != HAL_OK) {
1044 		LOG_ERR("PCD_DeInit failed, %d", (int)status);
1045 		return -EIO;
1046 	}
1047 
1048 	ret = usb_dc_stm32_clock_disable();
1049 	if (ret) {
1050 		return ret;
1051 	}
1052 
1053 	if (irq_is_enabled(USB_IRQ)) {
1054 		irq_disable(USB_IRQ);
1055 	}
1056 
1057 	return 0;
1058 }
1059 
usb_dc_reset(void)1060 int usb_dc_reset(void)
1061 {
1062 	LOG_ERR("Not implemented");
1063 
1064 	return 0;
1065 }
1066 
1067 /* Callbacks from the STM32 Cube HAL code */
1068 
HAL_PCD_ResetCallback(PCD_HandleTypeDef * hpcd)1069 void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd)
1070 {
1071 	int i;
1072 
1073 	LOG_DBG("");
1074 
1075 	HAL_PCD_EP_Open(&usb_dc_stm32_state.pcd, EP0_IN, EP0_MPS, EP_TYPE_CTRL);
1076 	HAL_PCD_EP_Open(&usb_dc_stm32_state.pcd, EP0_OUT, EP0_MPS,
1077 			EP_TYPE_CTRL);
1078 
1079 	/* The DataInCallback will never be called at this point for any pending
1080 	 * transactions. Reset the IN semaphores to prevent perpetual locked state.
1081 	 * */
1082 	for (i = 0; i < USB_NUM_BIDIR_ENDPOINTS; i++) {
1083 		k_sem_give(&usb_dc_stm32_state.in_ep_state[i].write_sem);
1084 	}
1085 
1086 	if (usb_dc_stm32_state.status_cb) {
1087 		usb_dc_stm32_state.status_cb(USB_DC_RESET, NULL);
1088 	}
1089 }
1090 
HAL_PCD_ConnectCallback(PCD_HandleTypeDef * hpcd)1091 void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd)
1092 {
1093 	LOG_DBG("");
1094 
1095 	if (usb_dc_stm32_state.status_cb) {
1096 		usb_dc_stm32_state.status_cb(USB_DC_CONNECTED, NULL);
1097 	}
1098 }
1099 
HAL_PCD_DisconnectCallback(PCD_HandleTypeDef * hpcd)1100 void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd)
1101 {
1102 	LOG_DBG("");
1103 
1104 	if (usb_dc_stm32_state.status_cb) {
1105 		usb_dc_stm32_state.status_cb(USB_DC_DISCONNECTED, NULL);
1106 	}
1107 }
1108 
HAL_PCD_SuspendCallback(PCD_HandleTypeDef * hpcd)1109 void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd)
1110 {
1111 	LOG_DBG("");
1112 
1113 	if (usb_dc_stm32_state.status_cb) {
1114 		usb_dc_stm32_state.status_cb(USB_DC_SUSPEND, NULL);
1115 	}
1116 }
1117 
HAL_PCD_ResumeCallback(PCD_HandleTypeDef * hpcd)1118 void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd)
1119 {
1120 	LOG_DBG("");
1121 
1122 	if (usb_dc_stm32_state.status_cb) {
1123 		usb_dc_stm32_state.status_cb(USB_DC_RESUME, NULL);
1124 	}
1125 }
1126 
HAL_PCD_SetupStageCallback(PCD_HandleTypeDef * hpcd)1127 void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd)
1128 {
1129 	struct usb_setup_packet *setup = (void *)usb_dc_stm32_state.pcd.Setup;
1130 	struct usb_dc_stm32_ep_state *ep_state;
1131 
1132 	LOG_DBG("");
1133 
1134 	ep_state = usb_dc_stm32_get_ep_state(EP0_OUT); /* can't fail for ep0 */
1135 	__ASSERT(ep_state, "No corresponding ep_state for EP0");
1136 
1137 	ep_state->read_count = SETUP_SIZE;
1138 	ep_state->read_offset = 0U;
1139 	memcpy(&usb_dc_stm32_state.ep_buf[EP0_IDX],
1140 	       usb_dc_stm32_state.pcd.Setup, ep_state->read_count);
1141 
1142 	if (ep_state->cb) {
1143 		ep_state->cb(EP0_OUT, USB_DC_EP_SETUP);
1144 
1145 		if (!(setup->wLength == 0U) &&
1146 		    usb_reqtype_is_to_device(setup)) {
1147 			usb_dc_ep_start_read(EP0_OUT,
1148 					     usb_dc_stm32_state.ep_buf[EP0_IDX],
1149 					     setup->wLength);
1150 		}
1151 	}
1152 }
1153 
HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef * hpcd,uint8_t epnum)1154 void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
1155 {
1156 	uint8_t ep_idx = USB_EP_GET_IDX(epnum);
1157 	uint8_t ep = ep_idx | USB_EP_DIR_OUT;
1158 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
1159 
1160 	LOG_DBG("epnum 0x%02x, rx_count %u", epnum,
1161 		HAL_PCD_EP_GetRxCount(&usb_dc_stm32_state.pcd, epnum));
1162 
1163 	/* Transaction complete, data is now stored in the buffer and ready
1164 	 * for the upper stack (usb_dc_ep_read to retrieve).
1165 	 */
1166 	usb_dc_ep_get_read_count(ep, &ep_state->read_count);
1167 	ep_state->read_offset = 0U;
1168 
1169 	if (ep_state->cb) {
1170 		ep_state->cb(ep, USB_DC_EP_DATA_OUT);
1171 	}
1172 }
1173 
HAL_PCD_DataInStageCallback(PCD_HandleTypeDef * hpcd,uint8_t epnum)1174 void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum)
1175 {
1176 	uint8_t ep_idx = USB_EP_GET_IDX(epnum);
1177 	uint8_t ep = ep_idx | USB_EP_DIR_IN;
1178 	struct usb_dc_stm32_ep_state *ep_state = usb_dc_stm32_get_ep_state(ep);
1179 
1180 	LOG_DBG("epnum 0x%02x", epnum);
1181 
1182 	__ASSERT(ep_state, "No corresponding ep_state for ep");
1183 
1184 	k_sem_give(&ep_state->write_sem);
1185 
1186 	if (ep_state->cb) {
1187 		ep_state->cb(ep, USB_DC_EP_DATA_IN);
1188 	}
1189 }
1190 
1191 #if (defined(USB) || defined(USB_DRD_FS)) && DT_INST_NODE_HAS_PROP(0, disconnect_gpios)
HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef * hpcd,uint8_t state)1192 void HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef *hpcd, uint8_t state)
1193 {
1194 	struct gpio_dt_spec usb_disconnect = GPIO_DT_SPEC_INST_GET(0, disconnect_gpios);
1195 
1196 	gpio_pin_configure_dt(&usb_disconnect,
1197 			   (state ? GPIO_OUTPUT_ACTIVE : GPIO_OUTPUT_INACTIVE));
1198 }
1199 #endif /* USB && DT_INST_NODE_HAS_PROP(0, disconnect_gpios) */
1200