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