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