From cfdab2564fa5735f0a7d5653aa6eb5388456028e Mon Sep 17 00:00:00 2001 From: Alex-Schaefer <81265029+Alex-Schaefer@users.noreply.github.com> Date: Sat, 9 May 2026 09:10:47 +0200 Subject: dwc2: preserve EP0 status completion before SETUP On STM32 DWC2, SETUP phase done and EP0 OUT transfer complete can be reported together. Processing SETUP first can overwrite control state before the previous zero-length OUT status stage is acknowledged, which causes DFU DNLOAD/GETSTATUS traffic to lose the status ACK and stall. Queue the EP0 OUT zero-length transfer completion before queuing the SETUP event when the endpoint has no pending OUT data and total_len is zero. This keeps TinyUSB control-transfer ordering intact for the combined interrupt case. --- src/portable/synopsys/dwc2/dcd_dwc2.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 30e24a9ad..9b8f44df8 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -946,7 +946,17 @@ static void handle_rxflvl_irq(uint8_t rhport) { } static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepint_bm) { + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); + const bool ep0_status_complete_before_setup = (epnum == 0) && doepint_bm.setup_phase_done && + doepint_bm.xfer_complete && + (_dcd_data.ep0_pending[TUSB_DIR_OUT] == 0) && + (xfer->total_len == 0); + if (doepint_bm.setup_phase_done) { + if (ep0_status_complete_before_setup) { + dcd_event_xfer_complete(rhport, epnum, 0, XFER_RESULT_SUCCESS, true); + } + // Cleanup previous pending EP0 IN transfer if any dwc2_dep_t* epin0 = &DWC2_REG(rhport)->epin[0]; if (edpt_is_enabled(epin0)) { @@ -962,7 +972,6 @@ static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doe // Note: even though (xfer_complete + status_phase_rx) is for buffered DMA only, for STM32L47x (dwc2 v3.00a) they // can is set when GRXSTS_PKTSTS_SETUP_RX is popped therefore they can bet set before/together with setup_phase_done if (!doepint_bm.status_phase_rx && !doepint_bm.setup_packet_rx) { - xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); if ((epnum == 0) && _dcd_data.ep0_pending[TUSB_DIR_OUT]) { // EP0 can only handle one packet, Schedule another packet to be received. edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT); @@ -1005,8 +1014,17 @@ static void handle_epin_slave(uint8_t rhport, uint8_t epnum, dwc2_diepint_t diep #if CFG_TUD_DWC2_DMA_ENABLE static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepint_bm) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); + const bool ep0_status_complete_before_setup = (epnum == 0) && doepint_bm.setup_phase_done && + doepint_bm.xfer_complete && + (_dcd_data.ep0_pending[TUSB_DIR_OUT] == 0) && + (xfer->total_len == 0); if (doepint_bm.setup_phase_done) { + if (ep0_status_complete_before_setup) { + dcd_event_xfer_complete(rhport, epnum, 0, XFER_RESULT_SUCCESS, true); + } + // Cleanup previous pending EP0 IN transfer if any dwc2_dep_t* epin0 = &DWC2_REG(rhport)->epin[0]; if (edpt_is_enabled(epin0)) { @@ -1028,7 +1046,6 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT); } else { dwc2_dep_t* epout = &dwc2->epout[epnum]; - xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); // determine actual received bytes const dwc2_ep_tsize_t tsiz = {.value = epout->tsiz}; -- cgit v1.3.1 From 16bc0548dc0793404a5885aa90d78100b604c227 Mon Sep 17 00:00:00 2001 From: Alex-Schaefer <81265029+Alex-Schaefer@users.noreply.github.com> Date: Sat, 9 May 2026 11:14:00 +0200 Subject: dwc2: guard EP0 status completion with armed ZLP state Track when an EP0 OUT zero-length transfer is actually armed and require that state before synthesizing a status-stage completion ahead of a co-reported SETUP event. This preserves the validated status-before-SETUP ordering fix while avoiding stale zero-length state from producing spurious EP0 OUT completions. --- src/portable/synopsys/dwc2/dcd_dwc2.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 9b8f44df8..72beb1b80 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -62,6 +62,7 @@ static xfer_ctl_t xfer_status[DWC2_EP_MAX][2]; typedef struct { // EP0 transfers are limited to 1 packet - larger sizes has to be split uint16_t ep0_pending[2]; // Index determines direction as tusb_dir_t type + bool ep0_out_zlp_armed; // EP0 OUT ZLP transfer is armed and waiting for completion uint16_t dfifo_top; // top free location in DFIFO in words // Number of IN endpoints active @@ -665,6 +666,9 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t to // EP0 can only handle one packet if (epnum == 0) { _dcd_data.ep0_pending[dir] = total_bytes; + if (dir == TUSB_DIR_OUT) { + _dcd_data.ep0_out_zlp_armed = (total_bytes == 0); + } } // Schedule packets to be sent within interrupt @@ -744,6 +748,9 @@ static void handle_bus_reset(uint8_t rhport) { tu_memclr(xfer_status, sizeof(xfer_status)); + _dcd_data.ep0_pending[TUSB_DIR_OUT] = 0; + _dcd_data.ep0_pending[TUSB_DIR_IN] = 0; + _dcd_data.ep0_out_zlp_armed = false; _dcd_data.sof_en = false; _dcd_data.allocated_epin_count = 0; @@ -949,12 +956,16 @@ static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doe xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); const bool ep0_status_complete_before_setup = (epnum == 0) && doepint_bm.setup_phase_done && doepint_bm.xfer_complete && + _dcd_data.ep0_out_zlp_armed && (_dcd_data.ep0_pending[TUSB_DIR_OUT] == 0) && (xfer->total_len == 0); if (doepint_bm.setup_phase_done) { if (ep0_status_complete_before_setup) { + _dcd_data.ep0_out_zlp_armed = false; dcd_event_xfer_complete(rhport, epnum, 0, XFER_RESULT_SUCCESS, true); + } else if (epnum == 0) { + _dcd_data.ep0_out_zlp_armed = false; } // Cleanup previous pending EP0 IN transfer if any @@ -976,6 +987,9 @@ static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doe // EP0 can only handle one packet, Schedule another packet to be received. edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT); } else { + if (epnum == 0) { + _dcd_data.ep0_out_zlp_armed = false; + } dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true); } } @@ -1017,12 +1031,16 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); const bool ep0_status_complete_before_setup = (epnum == 0) && doepint_bm.setup_phase_done && doepint_bm.xfer_complete && + _dcd_data.ep0_out_zlp_armed && (_dcd_data.ep0_pending[TUSB_DIR_OUT] == 0) && (xfer->total_len == 0); if (doepint_bm.setup_phase_done) { if (ep0_status_complete_before_setup) { + _dcd_data.ep0_out_zlp_armed = false; dcd_event_xfer_complete(rhport, epnum, 0, XFER_RESULT_SUCCESS, true); + } else if (epnum == 0) { + _dcd_data.ep0_out_zlp_armed = false; } // Cleanup previous pending EP0 IN transfer if any @@ -1058,6 +1076,9 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi dma_setup_prepare(rhport); } + if (epnum == 0) { + _dcd_data.ep0_out_zlp_armed = false; + } dcd_dcache_invalidate(xfer->buffer, xfer->total_len); dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true); } -- cgit v1.3.1 From 5ea1979e290ed80430a5b65b56534373ecbdd56f Mon Sep 17 00:00:00 2001 From: HiFiPHile Date: Sun, 10 May 2026 01:47:21 +0200 Subject: add stm32c5 support Signed-off-by: HiFiPHile --- .github/workflows/ci_set_matrix.py | 1 + README.rst | 2 +- docs/reference/boards.rst | 1 + docs/reference/dependencies.rst | 4 +- .../device/cdc_msc_throughput/CMakePresets.json | 6 + examples/device/printer_to_cdc/CMakePresets.json | 6 + examples/dual/dynamic_switch/only.txt | 1 + examples/host/bare_api/only.txt | 1 + examples/host/cdc_msc_hid/only.txt | 1 + examples/host/cdc_msc_hid_freertos/only.txt | 1 + examples/host/device_info/only.txt | 1 + examples/host/midi_rx/only.txt | 1 + examples/host/msc_file_explorer/only.txt | 1 + hw/bsp/BoardPresets.json | 22 + hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h | 165 +++++ hw/bsp/stm32c5/boards/stm32c542nucleo/board.cmake | 13 + hw/bsp/stm32c5/boards/stm32c542nucleo/board.h | 83 +++ hw/bsp/stm32c5/boards/stm32c542nucleo/board.mk | 13 + hw/bsp/stm32c5/family.c | 237 +++++++ hw/bsp/stm32c5/family.cmake | 111 ++++ hw/bsp/stm32c5/family.mk | 52 ++ hw/bsp/stm32c5/stm32c5xx_hal_conf.h | 684 +++++++++++++++++++++ src/common/tusb_mcu.h | 6 + src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c | 1 + src/portable/st/stm32_fsdev/fsdev_stm32.h | 8 +- src/tusb_option.h | 1 + tools/get_deps.py | 8 +- 27 files changed, 1427 insertions(+), 4 deletions(-) create mode 100644 examples/device/cdc_msc_throughput/CMakePresets.json create mode 100644 examples/device/printer_to_cdc/CMakePresets.json create mode 100644 hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h create mode 100644 hw/bsp/stm32c5/boards/stm32c542nucleo/board.cmake create mode 100644 hw/bsp/stm32c5/boards/stm32c542nucleo/board.h create mode 100644 hw/bsp/stm32c5/boards/stm32c542nucleo/board.mk create mode 100644 hw/bsp/stm32c5/family.c create mode 100644 hw/bsp/stm32c5/family.cmake create mode 100644 hw/bsp/stm32c5/family.mk create mode 100644 hw/bsp/stm32c5/stm32c5xx_hal_conf.h (limited to 'src') diff --git a/.github/workflows/ci_set_matrix.py b/.github/workflows/ci_set_matrix.py index 1d35f15dd..f4d25fd37 100755 --- a/.github/workflows/ci_set_matrix.py +++ b/.github/workflows/ci_set_matrix.py @@ -68,6 +68,7 @@ family_list = { "samd5x_e5x": ["arm-gcc", "arm-clang"], "samg": ["arm-gcc", "arm-clang"], "stm32c0": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32c5": ["arm-gcc", "arm-clang", "arm-iar"], "stm32f0": ["arm-gcc", "arm-clang", "arm-iar"], "stm32f1": ["arm-gcc", "arm-clang", "arm-iar"], "stm32f2": ["arm-gcc", "arm-clang", "arm-iar"], diff --git a/README.rst b/README.rst index 04998abaa..1c56a6ba0 100644 --- a/README.rst +++ b/README.rst @@ -238,7 +238,7 @@ Supported CPUs | +----+------------------------+--------+------+-----------+------------------------+--------------------+ | | F2, F4, F7, H7, H7RS | ✔ | ✔ | ✔ | dwc2 | | | +-----------------------------+--------+------+-----------+------------------------+--------------------+ -| | C0, G0, H5, U3 | ✔ | ✔ | ✖ | stm32_fsdev | 2KB USB RAM | +| | C0, C5, G0, H5, U3 | ✔ | ✔ | ✖ | stm32_fsdev | 2KB USB RAM | | +-----------------------------+--------+------+-----------+------------------------+--------------------+ | | G4 | ✔ | ✖ | ✖ | stm32_fsdev | 1KB USB RAM | | +----+------------------------+--------+------+-----------+------------------------+--------------------+ diff --git a/docs/reference/boards.rst b/docs/reference/boards.rst index e61c4f98b..b0e8bffaa 100644 --- a/docs/reference/boards.rst +++ b/docs/reference/boards.rst @@ -266,6 +266,7 @@ STMicroelectronics Board Name Family URL Note =================== ================================= ========= ================================================================= ====== stm32c071nucleo STM32C071 Nucleo stm32c0 https://www.st.com/en/evaluation-tools/nucleo-c071rb.html +stm32c542nucleo STM32C542 Nucleo stm32c5 https://www.st.com/en/evaluation-tools/nucleo-c542rc.html stm32f070rbnucleo STM32 F070 Nucleo stm32f0 https://www.st.com/en/evaluation-tools/nucleo-f070rb.html stm32f072disco STM32 F072 Discovery stm32f0 https://www.st.com/en/evaluation-tools/32f072bdiscovery.html stm32f072eval STM32 F072 Eval stm32f0 https://www.st.com/en/evaluation-tools/stm32072b-eval.html diff --git a/docs/reference/dependencies.rst b/docs/reference/dependencies.rst index c5b755577..d281e912a 100644 --- a/docs/reference/dependencies.rst +++ b/docs/reference/dependencies.rst @@ -59,6 +59,7 @@ hw/mcu/st/cmsis_device_l5 https://github.com/STMicroelectronics/ hw/mcu/st/cmsis_device_n6 https://github.com/STMicroelectronics/cmsis-device-n6.git 7bcdc944fbf7cf5928d3c1d14054ca13261d33ec stm32n6 hw/mcu/st/cmsis_device_u5 https://github.com/STMicroelectronics/cmsis_device_u5.git 6e67187dec98035893692ab2923914cb5f4e0117 stm32u5 hw/mcu/st/cmsis_device_wb https://github.com/STMicroelectronics/cmsis_device_wb.git cda2cb9fc4a5232ab18efece0bb06b0b60910083 stm32wb +hw/mcu/st/stm32c5xx-dfp https://github.com/STMicroelectronics/stm32c5xx-dfp.git 6d0940882511d9430f83af9bd3da6bcb77f79239 stm32c5 hw/mcu/st/stm32-mfxstm32l152 https://github.com/STMicroelectronics/stm32-mfxstm32l152.git 7f4389efee9c6a655b55e5df3fceef5586b35f9b stm32h7 hw/mcu/st/stm32-tcpp0203 https://github.com/STMicroelectronics/stm32-tcpp0203.git 9918655bff176ac3046ccf378b5c7bbbc6a38d15 stm32h5 stm32h7rs stm32n6 hw/mcu/st/stm32c0xx_hal_driver https://github.com/STMicroelectronics/stm32c0xx_hal_driver.git c283b143bef6bdaacf64240ee6f15eb61dad6125 stm32c0 @@ -82,13 +83,14 @@ hw/mcu/st/stm32u0xx_hal_driver https://github.com/STMicroelectronics/ hw/mcu/st/stm32u5xx_hal_driver https://github.com/STMicroelectronics/stm32u5xx_hal_driver.git 2c5e2568fbdb1900a13ca3b2901fdd302cac3444 stm32u5 hw/mcu/st/stm32wbaxx_hal_driver https://github.com/STMicroelectronics/stm32wbaxx_hal_driver.git 9442fbb71f855ff2e64fbf662b7726beba511a24 stm32wba hw/mcu/st/stm32wbxx_hal_driver https://github.com/STMicroelectronics/stm32wbxx_hal_driver.git d60dd46996876506f1d2e9abd6b1cc110c8004cd stm32wb +hw/mcu/st/stm32c5xx-drivers https://github.com/STMicroelectronics/stm32c5xx-drivers.git 79b901285a7efeaf87c4c25db81d24cb5d8c9465 stm32c5 hw/mcu/ti https://github.com/hathach/ti_driver.git 083944907e7d08fcb1f614b47598ce45935b8da1 msp430 msp432e4 tm4c hw/mcu/wch/ch32f20x https://github.com/openwch/ch32f20x.git 77c4095087e5ed2c548ec9058e655d0b8757663b ch32f20x hw/mcu/wch/ch32v103 https://github.com/openwch/ch32v103.git 7578cae0b21f86dd053a1f781b2fc6ab99d0ec17 ch32v10x hw/mcu/wch/ch32v20x https://github.com/openwch/ch32v20x.git c4c38f507e258a4e69b059ccc2dc27dde33cea1b ch32v20x hw/mcu/wch/ch32v307 https://github.com/openwch/ch32v307.git 184f21b852cb95eed58e86e901837bc9fff68775 ch32v30x lib/CMSIS_5 https://github.com/ARM-software/CMSIS_5.git 2b7495b8535bdcb306dac29b9ded4cfb679d7e5c kinetis_k kinetis_kl lpc54 rw61x mm32 msp432e4 nrf samd2x_l2x lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 stm32c0 stm32f0 stm32f1 stm32f2 stm32f3 stm32f4 stm32f7 stm32g0 stm32g4 stm32h5 stm32h7 stm32h7rs stm32l0 stm32l1 stm32l4 stm32l5 stm32u0 stm32u5 stm32wb stm32wba sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x samg tm4c -lib/CMSIS_6 https://github.com/ARM-software/CMSIS_6.git 6f0a58d01aa9bd2feba212097f9afe7acd991d52 imxrt kinetis_k32l ra stm32n6 lpc51 lpc55 mcx +lib/CMSIS_6 https://github.com/ARM-software/CMSIS_6.git 6f0a58d01aa9bd2feba212097f9afe7acd991d52 imxrt kinetis_k32l ra stm32n6 lpc51 lpc55 mcx stm32c5 lib/FreeRTOS-Kernel https://github.com/FreeRTOS/FreeRTOS-Kernel.git cc0e0707c0c748713485b870bb980852b210877f all lib/lwip https://github.com/lwip-tcpip/lwip.git 159e31b689577dbf69cf0683bbaffbd71fa5ee10 all lib/sct_neopixel https://github.com/gsteiert/sct_neopixel.git e73e04ca63495672d955f9268e003cffe168fcd8 lpc55 diff --git a/examples/device/cdc_msc_throughput/CMakePresets.json b/examples/device/cdc_msc_throughput/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/cdc_msc_throughput/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/printer_to_cdc/CMakePresets.json b/examples/device/printer_to_cdc/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/printer_to_cdc/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/dual/dynamic_switch/only.txt b/examples/dual/dynamic_switch/only.txt index 70be49b28..e1038f9d4 100644 --- a/examples/dual/dynamic_switch/only.txt +++ b/examples/dual/dynamic_switch/only.txt @@ -2,6 +2,7 @@ family:espressif mcu:LPC43XX mcu:MIMXRT1XXX mcu:STM32C0 +mcu:STM32C5 mcu:STM32G0 mcu:STM32H5 mcu:STM32F2 diff --git a/examples/host/bare_api/only.txt b/examples/host/bare_api/only.txt index 1ddfc2b5c..a2ff93be5 100644 --- a/examples/host/bare_api/only.txt +++ b/examples/host/bare_api/only.txt @@ -20,6 +20,7 @@ mcu:RP2040 mcu:RW61X mcu:RX65X mcu:STM32C0 +mcu:STM32C5 mcu:STM32F4 mcu:STM32F7 mcu:STM32G0 diff --git a/examples/host/cdc_msc_hid/only.txt b/examples/host/cdc_msc_hid/only.txt index 1ddfc2b5c..a2ff93be5 100644 --- a/examples/host/cdc_msc_hid/only.txt +++ b/examples/host/cdc_msc_hid/only.txt @@ -20,6 +20,7 @@ mcu:RP2040 mcu:RW61X mcu:RX65X mcu:STM32C0 +mcu:STM32C5 mcu:STM32F4 mcu:STM32F7 mcu:STM32G0 diff --git a/examples/host/cdc_msc_hid_freertos/only.txt b/examples/host/cdc_msc_hid_freertos/only.txt index 753fa7cd3..4ab8a906e 100644 --- a/examples/host/cdc_msc_hid_freertos/only.txt +++ b/examples/host/cdc_msc_hid_freertos/only.txt @@ -16,6 +16,7 @@ mcu:MSP432E4 mcu:RW61X mcu:RX65X mcu:STM32C0 +mcu:STM32C5 mcu:STM32F4 mcu:STM32F7 mcu:STM32G0 diff --git a/examples/host/device_info/only.txt b/examples/host/device_info/only.txt index 742935dcf..4c2cb0f35 100644 --- a/examples/host/device_info/only.txt +++ b/examples/host/device_info/only.txt @@ -21,6 +21,7 @@ mcu:RP2040 mcu:RW61X mcu:RX65X mcu:STM32C0 +mcu:STM32C5 mcu:STM32F4 mcu:STM32F7 mcu:STM32G0 diff --git a/examples/host/midi_rx/only.txt b/examples/host/midi_rx/only.txt index c71aacd87..65ef8fac9 100644 --- a/examples/host/midi_rx/only.txt +++ b/examples/host/midi_rx/only.txt @@ -23,6 +23,7 @@ mcu:RP2040 mcu:RW61X mcu:RX65X mcu:STM32C0 +mcu:STM32C5 mcu:STM32F4 mcu:STM32F7 mcu:STM32G0 diff --git a/examples/host/msc_file_explorer/only.txt b/examples/host/msc_file_explorer/only.txt index 1ddfc2b5c..a2ff93be5 100644 --- a/examples/host/msc_file_explorer/only.txt +++ b/examples/host/msc_file_explorer/only.txt @@ -20,6 +20,7 @@ mcu:RP2040 mcu:RW61X mcu:RX65X mcu:STM32C0 +mcu:STM32C5 mcu:STM32F4 mcu:STM32F7 mcu:STM32G0 diff --git a/hw/bsp/BoardPresets.json b/hw/bsp/BoardPresets.json index 86609d075..1ff29f99d 100644 --- a/hw/bsp/BoardPresets.json +++ b/hw/bsp/BoardPresets.json @@ -626,6 +626,10 @@ "name": "stm32c071nucleo", "inherits": "default" }, + { + "name": "stm32c542nucleo", + "inherits": "default" + }, { "name": "stm32f070rbnucleo", "inherits": "default" @@ -1762,6 +1766,11 @@ "description": "Build preset for the stm32c071nucleo board", "configurePreset": "stm32c071nucleo" }, + { + "name": "stm32c542nucleo", + "description": "Build preset for the stm32c542nucleo board", + "configurePreset": "stm32c542nucleo" + }, { "name": "stm32f070rbnucleo", "description": "Build preset for the stm32f070rbnucleo board", @@ -4227,6 +4236,19 @@ } ] }, + { + "name": "stm32c542nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32c542nucleo" + }, + { + "type": "build", + "name": "stm32c542nucleo" + } + ] + }, { "name": "stm32f070rbnucleo", "steps": [ diff --git a/hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h b/hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h new file mode 100644 index 000000000..732d9a5cf --- /dev/null +++ b/hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h @@ -0,0 +1,165 @@ +/* + * FreeRTOS Kernel V10.0.0 + * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. If you wish to use our Amazon + * FreeRTOS name, please do so in a fair use way that does not cause confusion. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ + +// skip if included from IAR assembler +#ifndef __IASMARM__ + #include "stm32c5xx.h" +#endif + +/* Cortex M23/M33 port configuration. */ +#define configENABLE_MPU 0 +#define configENABLE_FPU 1 +#define configENABLE_TRUSTZONE 0 +#define configMINIMAL_SECURE_STACK_SIZE (1024) + +#define configUSE_PREEMPTION 1 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 +#define configCPU_CLOCK_HZ SystemCoreClock +#define configTICK_RATE_HZ ( 1000 ) +#define configMAX_PRIORITIES ( 5 ) +#define configMINIMAL_STACK_SIZE ( 200 ) +#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 ) +#define configMAX_TASK_NAME_LEN 16 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_MUTEXES 1 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configQUEUE_REGISTRY_SIZE 4 +#define configUSE_QUEUE_SETS 0 +#define configUSE_TIME_SLICING 0 +#define configUSE_NEWLIB_REENTRANT 0 +#define configENABLE_BACKWARD_COMPATIBILITY 1 +#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 + +#define configSUPPORT_STATIC_ALLOCATION 1 +#define configSUPPORT_DYNAMIC_ALLOCATION 0 + +/* Hook function related definitions. */ +#define configUSE_IDLE_HOOK 0 +#define configUSE_TICK_HOOK 0 +#define configUSE_MALLOC_FAILED_HOOK 0 // cause nested extern warning +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configCHECK_HANDLER_INSTALLATION 0 + +/* Run time and task stats gathering related definitions. */ +#define configGENERATE_RUN_TIME_STATS 0 +#define configRECORD_STACK_HIGH_ADDRESS 1 +#define configUSE_TRACE_FACILITY 1 // legacy trace +#define configUSE_STATS_FORMATTING_FUNCTIONS 0 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES 2 + +/* Software timer related definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES-2) +#define configTIMER_QUEUE_LENGTH 32 +#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE + +/* Optional functions - most linkers will remove unused functions anyway. */ +#define INCLUDE_vTaskPrioritySet 0 +#define INCLUDE_uxTaskPriorityGet 0 +#define INCLUDE_vTaskDelete 0 +#define INCLUDE_vTaskSuspend 1 // required for queue, semaphore, mutex to be blocked indefinitely with portMAX_DELAY +#define INCLUDE_xResumeFromISR 0 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_xTaskGetSchedulerState 0 +#define INCLUDE_xTaskGetCurrentTaskHandle 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 0 +#define INCLUDE_xTaskGetIdleTaskHandle 0 +#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0 +#define INCLUDE_pcTaskGetTaskName 0 +#define INCLUDE_eTaskGetState 0 +#define INCLUDE_xEventGroupSetBitFromISR 0 +#define INCLUDE_xTimerPendFunctionCall 0 + +/* Define to trap errors during development. */ +// Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7 +#if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__) || defined(__ARM_ARCH_8_1M_MAIN__) || \ + defined(__ARM7M__) || defined (__ARM7EM__) || defined(__ARM8M_MAINLINE__) || defined(__ARM8EM_MAINLINE__) + #define configASSERT(_exp) \ + do {\ + if ( !(_exp) ) { \ + volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \ + if ( (*ARM_CM_DHCSR) & 1UL ) { /* Only halt mcu if debugger is attached */ \ + taskDISABLE_INTERRUPTS(); \ + __asm("BKPT #0\n"); \ + }\ + }\ + } while(0) +#endif + +/* FreeRTOS hooks to NVIC vectors */ +#define xPortPendSVHandler PendSV_Handler +#define xPortSysTickHandler SysTick_Handler +#define vPortSVCHandler SVC_Handler + +//--------------------------------------------------------------------+ +// Interrupt nesting behavior configuration. +//--------------------------------------------------------------------+ + +// For Cortex-M specific: __NVIC_PRIO_BITS is defined in mcu header +#define configPRIO_BITS 4 + +/* The lowest interrupt priority that can be used in a call to a "set priority" function. */ +#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1<instance)) +#endif + +//--------------------------------------------------------------------+ +// Forward USB interrupt events to TinyUSB IRQ Handler +//--------------------------------------------------------------------+ +void USB_DRD_FS_IRQHandler(void) { + tusb_int_handler(0, true); +} + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM +//--------------------------------------------------------------------+ +#ifdef UART_ID +static hal_uart_handle_t hUSART; +#endif + +void board_init(void) { + HAL_Init(); + board_clock_init(); + + // Enable peripheral clocks. + HAL_RCC_GPIOA_EnableClock(); + HAL_RCC_GPIOB_EnableClock(); + HAL_RCC_GPIOC_EnableClock(); + HAL_RCC_GPIOD_EnableClock(); + HAL_RCC_USB_EnableClock(); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // Explicitly disable systick to prevent its ISR from running before scheduler start + SysTick->CTRL &= ~1U; + + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB_DRD_FS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); +#endif + + // LED + { + hal_gpio_config_t gpio_config; + gpio_config.mode = HAL_GPIO_MODE_OUTPUT; + gpio_config.speed = HAL_GPIO_SPEED_FREQ_LOW; + gpio_config.pull = HAL_GPIO_PULL_NO; + gpio_config.output_type = HAL_GPIO_OUTPUT_PUSHPULL; + gpio_config.init_state = HAL_GPIO_PIN_RESET; + + HAL_GPIO_Init(LED_PORT, LED_PIN, &gpio_config); + } + + // Button + { + hal_gpio_config_t gpio_config; + gpio_config.mode = HAL_GPIO_MODE_INPUT; + gpio_config.speed = HAL_GPIO_SPEED_FREQ_LOW; + gpio_config.pull = BUTTON_STATE_ACTIVE ? HAL_GPIO_PULL_DOWN : HAL_GPIO_PULL_UP; + HAL_GPIO_Init(BUTTON_PORT, BUTTON_PIN, &gpio_config); + } + +#ifdef UART_ID + UARTn_CLK_ENABLE(); + // UART + { + hal_gpio_config_t gpio_config; + gpio_config.mode = HAL_GPIO_MODE_ALTERNATE; + gpio_config.output_type = HAL_GPIO_OUTPUT_PUSHPULL; + gpio_config.pull = HAL_GPIO_PULL_NO; + gpio_config.speed = HAL_GPIO_SPEED_FREQ_LOW; + gpio_config.alternate = UART_GPIO_AF; + HAL_GPIO_Init(UART_GPIO_PORT, UART_TX_PIN | UART_RX_PIN, &gpio_config); + } + + hal_uart_config_t uart_config; + HAL_UART_Init(&hUSART, UARTn); + uart_config.baud_rate = 115200; + uart_config.clock_prescaler = HAL_UART_PRESCALER_DIV1; + uart_config.word_length = HAL_UART_WORD_LENGTH_8_BIT; + uart_config.stop_bits = HAL_UART_STOP_BIT_1; + uart_config.parity = HAL_UART_PARITY_NONE; + uart_config.direction = HAL_UART_DIRECTION_TX_RX; + uart_config.hw_flow_ctl = HAL_UART_HW_CONTROL_NONE; + uart_config.oversampling = HAL_UART_OVERSAMPLING_16; + uart_config.one_bit_sampling = HAL_UART_ONE_BIT_SAMPLE_DISABLE; + + HAL_UART_SetConfig(&hUSART, &uart_config); + + /* Fifo configuration */ + HAL_UART_SetTxFifoThreshold(&hUSART, HAL_UART_FIFO_THRESHOLD_1_8); + HAL_UART_SetRxFifoThreshold(&hUSART, HAL_UART_FIFO_THRESHOLD_1_8); + HAL_UART_EnableFifoMode(&hUSART); + + LL_USART_Enable(UART_GET_INSTANCE(&hUSART)); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) { + hal_gpio_pin_state_t pin_state = state ? HAL_GPIO_PIN_SET : HAL_GPIO_PIN_RESET; + HAL_GPIO_WritePin(LED_PORT, LED_PIN, pin_state); +} + +uint32_t board_button_read(void) { + return BUTTON_STATE_ACTIVE == HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN); +} + +size_t board_get_unique_id(uint8_t id[], size_t max_len) { + (void) max_len; + volatile uint32_t * stm32_uuid = (volatile uint32_t *) UID_BASE; + uint32_t* id32 = (uint32_t*) (uintptr_t) id; + uint8_t const len = 12; + + id32[0] = stm32_uuid[0]; + id32[1] = stm32_uuid[1]; + id32[2] = stm32_uuid[2]; + + return len; +} + +int board_uart_read(uint8_t *buf, int len) { +#ifdef UART_ID + int count = 0; + while (count < len) { + if (LL_USART_IsActiveFlag_RXNE_RXFNE(UART_GET_INSTANCE(&hUSART))) { + buf[count] = (uint8_t) UART_GET_INSTANCE(&hUSART)->RDR; + count++; + } else { + break; + } + } + return count; +#else + (void) buf; (void) len; + return -1; +#endif +} + +int board_uart_write(void const *buf, int len) { +#ifdef UART_ID + const uint8_t *p = (const uint8_t *) buf; + int count = 0; + while (count < len) { + if (LL_USART_IsActiveFlag_TXE_TXFNF(UART_GET_INSTANCE(&hUSART))) { + UART_GET_INSTANCE(&hUSART)->TDR = p[count]; + count++; + } else { + break; + } + } + return count; +#else + (void) buf; (void) len; + return 0; +#endif +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; + +void SysTick_Handler(void) { + system_ticks++; + HAL_IncTick(); +} + +uint32_t tusb_time_millis_api(void) { + return system_ticks; +} +#endif + +void HardFault_Handler(void) { + __asm("BKPT #0\n"); +} + +#ifndef __ICCARM__ +// Implement _start() since we use linker flag '-nostartfiles'. +extern int main(void); +TU_ATTR_UNUSED void _start(void) { + // called by startup code + main(); + while (1) {} +} +#endif + +// Required by __libc_init_array in startup code if we are compiling using +// -nostdlib/-nostartfiles. +void _init(void) { + +} diff --git a/hw/bsp/stm32c5/family.cmake b/hw/bsp/stm32c5/family.cmake new file mode 100644 index 000000000..5b63b1ce4 --- /dev/null +++ b/hw/bsp/stm32c5/family.cmake @@ -0,0 +1,111 @@ +include_guard() + +set(ST_FAMILY c5) +set(ST_PREFIX stm32${ST_FAMILY}xx) + +set(ST_DRIVER ${TOP}/hw/mcu/st/stm32${ST_FAMILY}xx-drivers) +set(ST_CMSIS ${TOP}/hw/mcu/st/stm32${ST_FAMILY}xx-dfp) +set(CMSIS_6 ${TOP}/lib/CMSIS_6) + +# include board specific +include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) + +# toolchain set up +set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") +set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) + +set(FAMILY_MCUS STM32C5 CACHE INTERNAL "") +set(OPENOCD_OPTION "-f interface/stlink.cfg -f target/stm32c5x.cfg") + +#------------------------------------ +# Startup & Linker script +#------------------------------------ +set(STARTUP_FILE ${ST_CMSIS}/Source/startup_${MCU_VARIANT}.c) +set(LD_FILE_Clang ${LD_FILE_GNU}) + +#------------------------------------ +# BOARD_TARGET +#------------------------------------ +function(family_add_board BOARD_TARGET) + add_library(${BOARD_TARGET} STATIC + ${ST_CMSIS}/Source/Templates/system_${ST_PREFIX}.c + ${ST_DRIVER}/hal/${ST_PREFIX}_hal.c + ${ST_DRIVER}/hal/${ST_PREFIX}_hal_cortex.c + ${ST_DRIVER}/hal/${ST_PREFIX}_hal_flash_itf.c + ${ST_DRIVER}/hal/${ST_PREFIX}_hal_pwr.c + ${ST_DRIVER}/hal/${ST_PREFIX}_hal_rcc.c + ${ST_DRIVER}/hal/${ST_PREFIX}_hal_gpio.c + ${ST_DRIVER}/hal/${ST_PREFIX}_hal_uart.c + ${ST_DRIVER}/hal/${ST_PREFIX}_hal_dma.c + ) + target_include_directories(${BOARD_TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${CMSIS_6}/CMSIS/Core/Include + ${ST_CMSIS}/Include + ${ST_DRIVER}/hal + ${ST_DRIVER}/ll + ) + target_compile_definitions(${BOARD_TARGET} PUBLIC + ) + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_compile_options(${BOARD_TARGET} PUBLIC -Wno-redundant-decls) + endif () + + if(CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_compile_definitions(${BOARD_TARGET} PUBLIC + __STACK_LIMIT=__StackLimit + __INITIAL_SP=__StackTop + ) + endif () + + update_board(${BOARD_TARGET}) +endfunction() + +#------------------------------------ +# Functions +#------------------------------------ +function(family_configure_example TARGET RTOS) + family_configure_common(${TARGET} ${RTOS}) + family_add_tinyusb(${TARGET} OPT_MCU_STM32C5) + + target_sources(${TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c + ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c + ${TOP}/src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c + ${TOP}/src/portable/st/stm32_fsdev/fsdev_common.c + ${STARTUP_FILE} + ) + target_include_directories(${TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} + ) + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU") + target_link_options(${TARGET} PUBLIC + "LINKER:--script=${LD_FILE_GNU}" + -nostartfiles + --specs=nosys.specs --specs=nano.specs + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_link_options(${TARGET} PUBLIC + "LINKER:--script=${LD_FILE_Clang}" + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") + target_link_options(${TARGET} PUBLIC + "LINKER:--config=${LD_FILE_IAR}" + ) + endif () + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") + set_source_files_properties(${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c PROPERTIES COMPILE_FLAGS "-Wno-missing-prototypes") + endif () + + # Flashing + family_add_bin_hex(${TARGET}) + family_flash_jlink(${TARGET}) + family_flash_stlink(${TARGET}) + #family_flash_openocd(${TARGET}) +endfunction() diff --git a/hw/bsp/stm32c5/family.mk b/hw/bsp/stm32c5/family.mk new file mode 100644 index 000000000..165ad4ad5 --- /dev/null +++ b/hw/bsp/stm32c5/family.mk @@ -0,0 +1,52 @@ +ST_FAMILY = c5 +ST_CMSIS = hw/mcu/st/stm32$(ST_FAMILY)xx-dfp +ST_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx-drivers + +include $(TOP)/$(BOARD_PATH)/board.mk +CPU_CORE ?= cortex-m33 + +# -------------- +# Compiler Flags +# -------------- +CFLAGS += \ + -DCFG_TUSB_MCU=OPT_MCU_STM32C5 \ + +# GCC Flags +CFLAGS += \ + -flto \ + +# suppress warnings caused by vendor mcu driver +CFLAGS += -Wno-error=cast-align -Wno-error=unused-parameter -Wno-error=redundant-decls + +LDFLAGS += \ + -nostdlib -nostartfiles \ + --specs=nosys.specs --specs=nano.specs + +# ----------------- +# Sources & Include +# ----------------- + +SRC_C += \ + src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c \ + src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c \ + src/portable/st/stm32_fsdev/fsdev_common.c \ + $(ST_CMSIS)/Source/Templates/system_stm32$(ST_FAMILY)xx.c \ + $(ST_CMSIS)/Source/startup_$(MCU_VARIANT).c \ + $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal.c \ + $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_cortex.c \ + $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_flash_itf.c \ + $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_pwr.c \ + $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_rcc.c \ + $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_gpio.c \ + $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_uart.c \ + $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_dma.c + +INC += \ + $(TOP)/$(BOARD_PATH) \ + $(TOP)/lib/CMSIS_6/CMSIS/Core/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_DRIVER)/hal \ + $(TOP)/$(ST_DRIVER)/ll + +# flash target using on-board stlink +flash: flash-stlink diff --git a/hw/bsp/stm32c5/stm32c5xx_hal_conf.h b/hw/bsp/stm32c5/stm32c5xx_hal_conf.h new file mode 100644 index 000000000..0833fa3dd --- /dev/null +++ b/hw/bsp/stm32c5/stm32c5xx_hal_conf.h @@ -0,0 +1,684 @@ +/** + ****************************************************************************** + * @file stm32c5xx_hal_conf.h + * @brief HAL configuration file. + ****************************************************************************** + * @attention + * + * Copyright (c) 2026 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the mx_stm32c5xx_hal_drivers_license.md file + * in the same directory as the generated code. + * If no mx_stm32c5xx_hal_drivers_license.md file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32C5XX_HAL_CONF_H +#define STM32C5XX_HAL_CONF_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup HAL_Conf_How_To_Use HAL Conf How to Use + * @{ + - The STM32 HAL configuration file, stm32tnxx_hal_conf.h, is designed to customize the behaviour of the HAL modules. + - The users can utilize the provided file as-is, where all HAL modules are enabled with their default settings. + - Alternatively, users have the flexibility to customize the file based on their application's requirements. + - For example, they can enable only the necessary HAL modules or modify the predefined settings to achieve + the desired functionality. + */ + +/** + * @} + */ + +/** @defgroup HAL_Conf_Exported_Constants HAL Conf Constants + * @{ + */ + +/** @defgroup HAL_System_Configuration HAL System Configuration + * @{ + */ + +/* ########################### System Configuration ############################# */ +/** + * @brief This is the HAL system configuration section + */ +#define USE_HAL_TICK_INT_PRIORITY 15U /*!< tick interrupt priority */ +#define USE_HAL_FLASH_PREFETCH 1U /*!< Enable FLASH prefetch */ +/** + * @} + */ + +/** @defgroup HAL_MUTEX_Usage_Activation HAL MUTEX Usage Activation + * @{ + */ +/* ########################## HAL MUTEX usage activation ####################### */ +/** + * @brief Used by the HAL PPP Acquire/Release APIs when the define USE_HAL_MUTEX is set to 1 + */ +#define USE_HAL_MUTEX 0U +/** + * @} + */ + +/** @defgroup HAL_API_Parameters_Check HAL API Parameters Check + * @{ + */ +/* ########################## HAL API parameters check ##################### */ +/** + * @brief Run time parameter check activation + */ +#define USE_HAL_CHECK_PARAM 0U +#define USE_HAL_SECURE_CHECK_PARAM 0U +/** + * @} + */ + +/** @defgroup HAL_State_Transition HAL State Transition + * @{ + */ +/* ########################## State transition ################################ */ +/** + * @brief Enable protection of state transition in thread safe + */ +#define USE_HAL_CHECK_PROCESS_STATE 0U +/** + * @} + */ + +/* ########################## Peripheral configuration ######################### */ + +/** @defgroup HAL_ADC_Config HAL ADC Configuration + * @{ + */ +/* ########################## HAL_ADC Config #################################### */ +#define USE_HAL_ADC_MODULE 0U +#define USE_HAL_ADC_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_ADC_REGISTER_CALLBACKS 0U +#define USE_HAL_ADC_USER_DATA 0U +#define USE_HAL_ADC_GET_LAST_ERRORS 0U +#define USE_HAL_ADC_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_AES_Config HAL AES Configuration + * @{ + */ +/* ########################## HAL_AES Config #################################### */ +#define USE_HAL_AES_MODULE 0U +#define USE_HAL_AES_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_AES_REGISTER_CALLBACKS 0U +#define USE_HAL_AES_USER_DATA 0U +#define USE_HAL_AES_GET_LAST_ERRORS 0U +#define USE_HAL_AES_DMA 0U +#define USE_HAL_AES_ECB_CBC_ALGO 0U +#define USE_HAL_AES_CTR_ALGO 0U +#define USE_HAL_AES_GCM_GMAC_ALGO 0U +#define USE_HAL_AES_CCM_ALGO 0U +#define USE_HAL_AES_SUSPEND_RESUME 0U +/** + * @} + */ + +/** @defgroup HAL_CCB_Config HAL CCB Configuration + * @{ + */ +/* ########################## HAL_CCB Config #################################### */ +#define USE_HAL_CCB_MODULE 0U +#define USE_HAL_CCB_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_CCB_USER_DATA 0U +#define USE_HAL_CCB_GET_LAST_ERRORS 0U +/** + * @} + */ + +/** @defgroup HAL_COMP_Config HAL COMP Configuration + * @{ + */ +/* ########################## HAL_COMP Config ################################### */ +#define USE_HAL_COMP_MODULE 0U +#define USE_HAL_COMP_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_COMP_REGISTER_CALLBACKS 0U +#define USE_HAL_COMP_USER_DATA 0U +/* Use comparator with EXTI (needed to generate system wake-up event and CPU event) */ +#define USE_HAL_COMP_EXTI 0U +/* Use comparators window mode feature */ +#define USE_HAL_COMP_WINDOW_MODE 0U +/** + * @} + */ + +/** @defgroup HAL_CORDIC_Config HAL CORDIC Configuration + * @{ + */ +/* ########################## HAL_CORDIC Config ################################# */ +#define USE_HAL_CORDIC_MODULE 0U +#define USE_HAL_CORDIC_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_CORDIC_REGISTER_CALLBACKS 0U +#define USE_HAL_CORDIC_USER_DATA 0U +#define USE_HAL_CORDIC_GET_LAST_ERRORS 0U +#define USE_HAL_CORDIC_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_CORTEX_Config HAL CORTEX Configuration + * @{ + */ +/* ########################## HAL_CORTEX Config ################################# */ +#define USE_HAL_CORTEX_MODULE 1U +/** + * @} + */ + +/** @defgroup HAL_CRC_Config HAL CRC Configuration + * @{ + */ +/* ########################## HAL_CRC Config #################################### */ +#define USE_HAL_CRC_MODULE 0U +#define USE_HAL_CRC_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_CRC_USER_DATA 0U +/** + * @} + */ + +/** @defgroup HAL_CRS_Config HAL CRS Configuration + * @{ + */ +/* ########################## HAL_CRS Config #################################### */ +#define USE_HAL_CRS_MODULE 0U +#define USE_HAL_CRS_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_CRS_REGISTER_CALLBACKS 0U +#define USE_HAL_CRS_USER_DATA 0U +#define USE_HAL_CRS_GET_LAST_ERRORS 0U +/** + * @} + */ + +/** @defgroup HAL_DAC_Config HAL DAC Configuration + * @{ + */ +/* ########################## HAL_DAC Config #################################### */ +#define USE_HAL_DAC_MODULE 0U +#define USE_HAL_DAC_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_DAC_REGISTER_CALLBACKS 0U +#define USE_HAL_DAC_USER_DATA 0U +#define USE_HAL_DAC_GET_LAST_ERRORS 0U +#define USE_HAL_DAC_DMA 0U +#define USE_HAL_DAC_DUAL_CHANNEL 0U +/** + * @} + */ + +/** @defgroup HAL_DBGMCU_Config HAL DBGMCU Configuration + * @{ + */ +/* ########################## HAL_DBGMCU Config ################################# */ +#define USE_HAL_DBGMCU_MODULE 0U +/** + * @} + */ + +/** @defgroup HAL_DMA_Config HAL DMA Configuration + * @{ + */ +/* ########################## HAL_DMA Config #################################### */ +#define USE_HAL_DMA_MODULE 1U +#define USE_HAL_DMA_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_DMA_USER_DATA 0U +#define USE_HAL_DMA_GET_LAST_ERRORS 0U +#define USE_HAL_DMA_LINKEDLIST 0U +/** + * @} + */ + +/** @defgroup HAL_ETH_Config HAL ETH Configuration + * @{ + */ +/* ########################## HAL_ETH Config #################################### */ +#define USE_HAL_ETH_MODULE 0U +#define USE_HAL_ETH_REGISTER_CALLBACKS 0U +#define USE_HAL_ETH_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_ETH_USER_DATA 0U +#define USE_HAL_ETH_GET_LAST_ERRORS 0U +#define USE_HAL_ETH_ATOMIC_CHANNEL_LOCK 0U +#define USE_HAL_ETH_MAX_TX_CH_NB 1U +#define USE_HAL_ETH_MAX_RX_CH_NB 1U +/** + * @} + */ + +/** @defgroup HAL_EXTI_Config HAL EXTI Configuration + * @{ + */ +/* ########################## HAL_EXTI Config ################################### */ +#define USE_HAL_EXTI_MODULE 0U +#define USE_HAL_EXTI_REGISTER_CALLBACKS 0U +#define USE_HAL_EXTI_USER_DATA 0U +/** + * @} + */ + +/** @defgroup HAL_FDCAN_Config HAL FDCAN Configuration + * @{ + */ +/* ########################## HAL_FDCAN Config ################################## */ +#define USE_HAL_FDCAN_MODULE 0U +#define USE_HAL_FDCAN_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_FDCAN_REGISTER_CALLBACKS 0U +#define USE_HAL_FDCAN_USER_DATA 0U +#define USE_HAL_FDCAN_GET_LAST_ERRORS 0U +/** + * @} + */ + +/** @defgroup HAL_FLASH_Config HAL FLASH Configuration + * @{ + */ +/* ########################## HAL_FLASH Config ################################## */ +#define USE_HAL_FLASH_MODULE 1U +#define USE_HAL_FLASH_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_FLASH_REGISTER_CALLBACKS 0U +#define USE_HAL_FLASH_USER_DATA 0U +#define USE_HAL_FLASH_GET_LAST_ERRORS 0U +/* Use the FLASH program by address feature */ +#define USE_HAL_FLASH_PROGRAM_BY_ADDR 0U +/* Use the FLASH erase by address feature */ +#define USE_HAL_FLASH_ERASE_BY_ADDR 0U +/* Use the FLASH erase by PAGE feature */ +#define USE_HAL_FLASH_ERASE_PAGE 0U +/* Use the FLASH bank erase feature */ +#define USE_HAL_FLASH_ERASE_BANK 0U +/* Use the FLASH mass erase feature */ +#define USE_HAL_FLASH_MASS_ERASE 0U +/* Use ECC errors handling APIs */ +#define USE_HAL_FLASH_ECC 0U +/* Use FLASH HAL API for EDATA */ +#define USE_HAL_FLASH_OB_EDATA 0U +/** + * @} + */ + +/** @defgroup HAL_GPIO_Config HAL GPIO Configuration + * @{ + */ +/* ########################## HAL_GPIO Config ################################### */ +#define USE_HAL_GPIO_MODULE 1U +#define USE_HAL_GPIO_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +/** + * @} + */ + +/** @defgroup HAL_HASH_Config HAL HASH Configuration + * @{ + */ +/* ########################## HAL_HASH Config ################################### */ +#define USE_HAL_HASH_MODULE 0U +#define USE_HAL_HASH_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_HASH_REGISTER_CALLBACKS 0U +#define USE_HAL_HASH_USER_DATA 0U +#define USE_HAL_HASH_GET_LAST_ERRORS 0U +#define USE_HAL_HASH_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_HCD_Config HAL HCD Configuration + * @{ + */ +/* ########################## HAL_HCD Config #################################### */ +#define USE_HAL_HCD_MODULE 0U +#define USE_HAL_HCD_REGISTER_CALLBACKS 0U +#define USE_HAL_HCD_USER_DATA 0U +#define USE_HAL_HCD_GET_LAST_ERRORS 0U +#define USE_HAL_HCD_USB_DOUBLE_BUFFER 0U +#define USE_HAL_HCD_USB_EP_TYPE_ISOC 0U +#define USE_HAL_HCD_MAX_CHANNEL_NB 16U +/** + * @} + */ + +/** @defgroup HAL_I2C_Config HAL I2C Configuration + * @{ + */ +/* ########################## HAL_I2C Config #################################### */ +#define USE_HAL_I2C_MODULE 0U +#define USE_HAL_I2C_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_I2C_REGISTER_CALLBACKS 0U +#define USE_HAL_I2C_USER_DATA 0U +#define USE_HAL_I2C_GET_LAST_ERRORS 0U +#define USE_HAL_I2C_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_I3C_Config HAL I3C Configuration + * @{ + */ +/* ########################## HAL_I3C Config #################################### */ +#define USE_HAL_I3C_MODULE 0U +#define USE_HAL_I3C_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_I3C_REGISTER_CALLBACKS 0U +#define USE_HAL_I3C_USER_DATA 0U +#define USE_HAL_I3C_GET_LAST_ERRORS 0U +#define USE_HAL_I3C_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_I2S_Config HAL I2S Configuration + * @{ + */ +/* ########################## HAL_I2S Config #################################### */ +#define USE_HAL_I2S_MODULE 0U +#define USE_HAL_I2S_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_I2S_REGISTER_CALLBACKS 0U +#define USE_HAL_I2S_USER_DATA 0U +#define USE_HAL_I2S_GET_LAST_ERRORS 0U +#define USE_HAL_I2S_OVR_UDR_ERRORS 0U +#define USE_HAL_I2S_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_ICACHE_Config HAL ICACHE Configuration + * @{ + */ +/* ########################## HAL_ICACHE Config ################################# */ +#define USE_HAL_ICACHE_MODULE 1U +#define USE_HAL_ICACHE_REGISTER_CALLBACKS 0U +#define USE_HAL_ICACHE_USER_DATA 0U +#define USE_HAL_ICACHE_GET_LAST_ERRORS 0U +/** + * @} + */ + +/** @defgroup HAL_IWDG_Config HAL IWDG Configuration + * @{ + */ +/* ########################## HAL_IWDG Config ################################### */ +#define USE_HAL_IWDG_MODULE 0U +#define USE_HAL_IWDG_REGISTER_CALLBACKS 0U +#define USE_HAL_IWDG_USER_DATA 0U +/* IWDG time unit configuration */ +#define USE_HAL_IWDG_TIME_UNIT HAL_IWDG_TIME_UNIT_MS +/* IWDG hardware start configuration + warning: In case of starting IWDG in Hardware mode, make sure that + USE_HAL_IWDG_HARDWARE_START is aligned with OB activated set for IWDG */ +#define USE_HAL_IWDG_HARDWARE_START 0U +/* User can choose the value of the LSI frequency with the USE_HAL_IWDG_LSI_FREQ define: + - 0U : Dynamic LSI to be computed and set by the user. + - LSI_VALUE : LSI value of 32KHz. + - (LSI_VALUE / 128U): LSI value of 250Hz */ +#define USE_HAL_IWDG_LSI_FREQ LSI_VALUE +/** + * @} + */ + +/** @defgroup HAL_LPTIM_Config HAL LPTIM Configuration + * @{ + */ +/* ########################## HAL_LPTIM Config ################################## */ +#define USE_HAL_LPTIM_MODULE 0U +#define USE_HAL_LPTIM_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0U +#define USE_HAL_LPTIM_USER_DATA 0U +#define USE_HAL_LPTIM_GET_LAST_ERRORS 0U +#define USE_HAL_LPTIM_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_OPAMP_Config HAL OPAMP Configuration + * @{ + */ +/* ########################## HAL_OPAMP Config ################################## */ +#define USE_HAL_OPAMP_MODULE 0U +#define USE_HAL_OPAMP_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_OPAMP_USER_DATA 0U +/** + * @} + */ + +/** @defgroup HAL_PCD_Config HAL PCD Configuration + * @{ + */ +/* ########################## HAL_PCD Config #################################### */ +#define USE_HAL_PCD_MODULE 1U +#define USE_HAL_PCD_REGISTER_CALLBACKS 0U +#define USE_HAL_PCD_USER_DATA 0U +#define USE_HAL_PCD_GET_LAST_ERRORS 0U +#define USE_HAL_PCD_USB_DOUBLE_BUFFER 0U +#define USE_HAL_PCD_USB_LPM 0U +#define USE_HAL_PCD_USB_BCD 0U +#define USE_HAL_PCD_USB_EP_TYPE_ISOC 0U +#define USE_HAL_PCD_MAX_ENDPOINT_NB 8U +/** + * @} + */ + +/** @defgroup HAL_PKA_Config HAL PKA Configuration + * @{ + */ +/* ########################## HAL_PKA Config #################################### */ +#define USE_HAL_PKA_MODULE 0U +#define USE_HAL_PKA_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_PKA_REGISTER_CALLBACKS 0U +#define USE_HAL_PKA_USER_DATA 0U +#define USE_HAL_PKA_GET_LAST_ERRORS 0U +/** + * @} + */ + +/** @defgroup HAL_PWR_Config HAL PWR Configuration + * @{ + */ +/* ########################## HAL_PWR Config #################################### */ +#define USE_HAL_PWR_MODULE 1U +/** + * @} + */ + +/** @defgroup HAL_RAMCFG_Config HAL RAMCFG Configuration + * @{ + */ +/* ########################## HAL_RAMCFG Config ################################# */ +#define USE_HAL_RAMCFG_MODULE 0U +/** + * @} + */ + +/** @defgroup HAL_RCC_Config HAL RCC Configuration + * @{ + */ +/* ########################## HAL_RCC Config #################################### */ +#define USE_HAL_RCC_MODULE 1U +/* Use RCC HAL API for Reset function */ +#define USE_HAL_RCC_RESET_PERIPH_CLOCK_MANAGEMENT 0U +#define USE_HAL_RCC_RESET_RTC_DOMAIN 0U +/** + * @} + */ + +/** @defgroup HAL_RNG_Config HAL RNG Configuration + * @{ + */ +/* ########################## HAL_RNG Config #################################### */ +#define USE_HAL_RNG_MODULE 0U +#define USE_HAL_RNG_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_RNG_REGISTER_CALLBACKS 0U +#define USE_HAL_RNG_USER_DATA 0U +#define USE_HAL_RNG_GET_LAST_ERRORS 0U +/** + * @} + */ + +/** @defgroup HAL_RTC_Config HAL RTC Configuration + * @{ + */ +/* ########################## HAL_RTC Config #################################### */ +#define USE_HAL_RTC_MODULE 0U +/** + * @} + */ + +/** @defgroup HAL_SBS_Config HAL SBS Configuration + * @{ + */ +/* ########################## HAL_SBS Config #################################### */ +#define USE_HAL_SBS_MODULE 0U +/** + * @} + */ + +/** @defgroup HAL_SMARTCARD_Config HAL SMARTCARD Configuration + * @{ + */ +/* ########################## HAL_SMARTCARD Config ############################## */ +#define USE_HAL_SMARTCARD_MODULE 0U +#define USE_HAL_SMARTCARD_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U +#define USE_HAL_SMARTCARD_USER_DATA 0U +#define USE_HAL_SMARTCARD_GET_LAST_ERRORS 0U +#define USE_HAL_SMARTCARD_DMA 0U +/* #################### SMARTCARD FIFO configuration ######################## */ +#define USE_HAL_SMARTCARD_FIFO 0U +/** + * @} + */ + +/** @defgroup HAL_SMBUS_Config HAL SMBUS Configuration + * @{ + */ +/* ########################## HAL_SMBUS Config ################################## */ +#define USE_HAL_SMBUS_MODULE 0U +#define USE_HAL_SMBUS_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U +#define USE_HAL_SMBUS_USER_DATA 0U +#define USE_HAL_SMBUS_GET_LAST_ERRORS 0U +/** + * @} + */ + +/** @defgroup HAL_SPI_Config HAL SPI Configuration + * @{ + */ +/* ########################## HAL_SPI Config #################################### */ +#define USE_HAL_SPI_MODULE 0U +#define USE_HAL_SPI_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_SPI_REGISTER_CALLBACKS 0U +#define USE_HAL_SPI_USER_DATA 0U +#define USE_HAL_SPI_GET_LAST_ERRORS 0U +#define USE_HAL_SPI_DMA 0U +/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver + * Activated: CRC code is present inside driver + * Deactivated: CRC code cleaned from driver + */ +#define USE_HAL_SPI_CRC 0U +/** + * @} + */ + +/** @defgroup HAL_TAMP_Config HAL TAMP Configuration + * @{ + */ +/* ########################## HAL_TAMP Config ################################### */ +#define USE_HAL_TAMP_MODULE 0U +/** + * @} + */ + +/** @defgroup HAL_TIM_Config HAL TIM Configuration + * @{ + */ +/* ########################## HAL_TIM Config #################################### */ +#define USE_HAL_TIM_MODULE 0U +#define USE_HAL_TIM_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_TIM_REGISTER_CALLBACKS 0U +#define USE_HAL_TIM_USER_DATA 0U +#define USE_HAL_TIM_GET_LAST_ERRORS 0U +#define USE_HAL_TIM_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_UART_Config HAL UART Configuration + * @{ + */ +/* ########################## HAL_UART Config ################################### */ +#define USE_HAL_UART_MODULE 1U +#define USE_HAL_UART_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_UART_REGISTER_CALLBACKS 0U +#define USE_HAL_UART_USER_DATA 0U +#define USE_HAL_UART_GET_LAST_ERRORS 0U +#define USE_HAL_UART_DMA 0U +/** + * @} + */ + +/** @defgroup HAL_USART_Config HAL USART Configuration + * @{ + */ +/* ########################## HAL_USART Config ################################## */ +#define USE_HAL_USART_MODULE 0U +#define USE_HAL_USART_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_USART_REGISTER_CALLBACKS 0U +#define USE_HAL_USART_USER_DATA 0U +#define USE_HAL_USART_GET_LAST_ERRORS 0U +#define USE_HAL_USART_DMA 0U +#define USE_HAL_USART_FIFO 0U +/** + * @} + */ + +/** @defgroup HAL_WWDG_Config HAL WWDG Configuration + * @{ + */ +/* ########################## HAL_WWDG Config ################################### */ +#define USE_HAL_WWDG_MODULE 0U +#define USE_HAL_WWDG_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U +#define USE_HAL_WWDG_USER_DATA 0U +/* WWDG time unit configuration */ +#define USE_HAL_WWDG_TIME_UNIT HAL_WWDG_TIME_UNIT_MS +/* WWDG hardware start configuration + warning: In case of starting WWDG in Hardware mode, make sure that + USE_HAL_WWDG_HARDWARE_START is aligned with OB activated set for WWDG */ +#define USE_HAL_WWDG_HARDWARE_START 0U +/** + * @} + */ + +/** @defgroup HAL_XSPI_Config HAL XSPI Configuration + * @{ + */ +/* ########################## HAL_XSPI Config ################################### */ +#define USE_HAL_XSPI_MODULE 0U +#define USE_HAL_XSPI_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO +#define USE_HAL_XSPI_REGISTER_CALLBACKS 0U +#define USE_HAL_XSPI_USER_DATA 0U +#define USE_HAL_XSPI_GET_LAST_ERRORS 0U +#define USE_HAL_XSPI_DMA 0U +#define USE_HAL_XSPI_HYPERBUS 0U +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* STM32C5XX_HAL_CONF_H */ diff --git a/src/common/tusb_mcu.h b/src/common/tusb_mcu.h index c85ade4d0..cd9b3dc27 100644 --- a/src/common/tusb_mcu.h +++ b/src/common/tusb_mcu.h @@ -206,6 +206,12 @@ #define TUP_USBIP_FSDEV_DRD #define CFG_TUSB_FSDEV_PMA_SIZE 2048u +#elif TU_CHECK_MCU(OPT_MCU_STM32C5) + #define TUP_USBIP_FSDEV + #define TUP_USBIP_FSDEV_STM32 + #define TUP_USBIP_FSDEV_DRD + #define CFG_TUSB_FSDEV_PMA_SIZE 2048u + #elif TU_CHECK_MCU(OPT_MCU_STM32F0) #define TUP_USBIP_FSDEV #define TUP_USBIP_FSDEV_STM32 diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index 41da3ddd0..4dfd04fb4 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -41,6 +41,7 @@ * F302xB/C, F303xB/C, F373 512 byte buffer; no internal D+ pull-up * F302x6/8, F302xD/E2, F303xD/E 1024 byte buffer; no internal D+ pull-up * C0 2048 byte buffer; 32-bit bus; host mode + * C5 2048 byte buffer; 32-bit bus; host mode * G0 2048 byte buffer; 32-bit bus; host mode * G4 1024 byte buffer * H5 2048 byte buffer; 32-bit bus; host mode diff --git a/src/portable/st/stm32_fsdev/fsdev_stm32.h b/src/portable/st/stm32_fsdev/fsdev_stm32.h index 070aa00ec..74cc9d0a4 100644 --- a/src/portable/st/stm32_fsdev/fsdev_stm32.h +++ b/src/portable/st/stm32_fsdev/fsdev_stm32.h @@ -36,6 +36,10 @@ #include "stm32c0xx.h" #define FSDEV_HAS_SBUF_ISO 1 +#elif CFG_TUSB_MCU == OPT_MCU_STM32C5 + #include "stm32c5xx.h" + #define FSDEV_HAS_SBUF_ISO 1 + #elif CFG_TUSB_MCU == OPT_MCU_STM32F0 #include "stm32f0xx.h" #define FSDEV_HAS_SBUF_ISO 0 @@ -177,7 +181,7 @@ static const IRQn_Type fsdev_irq[] = { USB_IRQn, #elif TU_CHECK_MCU(OPT_MCU_STM32L5, OPT_MCU_STM32U3) USB_FS_IRQn, - #elif TU_CHECK_MCU(OPT_MCU_STM32C0, OPT_MCU_STM32H5, OPT_MCU_STM32U0) + #elif TU_CHECK_MCU(OPT_MCU_STM32C0, OPT_MCU_STM32C5, OPT_MCU_STM32H5, OPT_MCU_STM32U0) USB_DRD_FS_IRQn, #elif CFG_TUSB_MCU == OPT_MCU_STM32G0 #ifdef STM32G0B0xx @@ -276,6 +280,8 @@ TU_ATTR_ALWAYS_INLINE static inline void fsdev_int_disable(uint8_t rhport) { #define FSDEV_STM32_CPU_MHZ 64U #elif CFG_TUSB_MCU == OPT_MCU_STM32C0 #define FSDEV_STM32_CPU_MHZ 48U +#elif CFG_TUSB_MCU == OPT_MCU_STM32C5 + #define FSDEV_STM32_CPU_MHZ 144U #endif #ifndef CFG_TUSB_FSDEV_BTABLE_FS_DELAY_COUNT diff --git a/src/tusb_option.h b/src/tusb_option.h index 154f8e2a4..83b6d3e51 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -98,6 +98,7 @@ #define OPT_MCU_STM32N6 319 ///< ST N6 #define OPT_MCU_STM32WBA 320 ///< ST WBA #define OPT_MCU_STM32U3 321 ///< ST U3 +#define OPT_MCU_STM32C5 322 ///< ST C5 // Sony #define OPT_MCU_CXD56 400 ///< SONY CXD56 diff --git a/tools/get_deps.py b/tools/get_deps.py index eb87abf6e..50497fc71 100755 --- a/tools/get_deps.py +++ b/tools/get_deps.py @@ -163,6 +163,9 @@ deps_optional = { 'hw/mcu/st/cmsis-device-wba': ['https://github.com/STMicroelectronics/cmsis-device-wba.git', '647d8522e5fd15049e9a1cc30ed19d85e5911eaf', 'stm32wba'], + 'hw/mcu/st/stm32c5xx-dfp': ['https://github.com/STMicroelectronics/stm32c5xx-dfp.git', + '6d0940882511d9430f83af9bd3da6bcb77f79239', + 'stm32c5'], 'hw/mcu/st/stm32-mfxstm32l152': ['https://github.com/STMicroelectronics/stm32-mfxstm32l152.git', '7f4389efee9c6a655b55e5df3fceef5586b35f9b', 'stm32h7'], @@ -232,6 +235,9 @@ deps_optional = { 'hw/mcu/st/stm32wbaxx_hal_driver': ['https://github.com/STMicroelectronics/stm32wbaxx_hal_driver.git', '9442fbb71f855ff2e64fbf662b7726beba511a24', 'stm32wba'], + 'hw/mcu/st/stm32c5xx-drivers': ['https://github.com/STMicroelectronics/stm32c5xx-drivers.git', + '79b901285a7efeaf87c4c25db81d24cb5d8c9465', + 'stm32c5'], 'hw/mcu/ti': ['https://github.com/hathach/ti_driver.git', '083944907e7d08fcb1f614b47598ce45935b8da1', 'msp430 msp432e4 tm4c'], @@ -284,7 +290,7 @@ deps_optional = { 'tm4c '], 'lib/CMSIS_6': ['https://github.com/ARM-software/CMSIS_6.git', '6f0a58d01aa9bd2feba212097f9afe7acd991d52', - 'imxrt kinetis_k32l ra stm32n6 lpc51 lpc55 mcx'], + 'imxrt kinetis_k32l ra stm32n6 lpc51 lpc55 mcx stm32c5'], 'lib/sct_neopixel': ['https://github.com/gsteiert/sct_neopixel.git', 'e73e04ca63495672d955f9268e003cffe168fcd8', 'lpc55'], -- cgit v1.3.1 From c4cd6c85e94d94345bf356f4779d7b67fb73b14b Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Thu, 14 May 2026 19:33:47 +0200 Subject: dcd/musb: defer EP0 SETUP during DATA_IN/STATUS race Handle cases where a new SETUP arrives before the previous control transfer fully completes by buffering the SETUP and replaying it after status completion. Split EP0 DATA state into DATA_IN/DATA_OUT and finalize pending status-out completion before processing deferred SETUP. Signed-off-by: HiFiPhile --- src/portable/mentor/musb/dcd_musb.c | 102 ++++++++++++++++++++++++++-------- src/portable/mentor/musb/musb_max32.h | 2 +- src/portable/mentor/musb/musb_ti.h | 2 +- 3 files changed, 80 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 56429ac1f..e00585068 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -82,7 +82,8 @@ typedef struct { enum { PIPE0_STATE_IDLE = 0, // no active control transfer - PIPE0_STATE_DATA, // DATA stage (IN or OUT — direction implied by CSR/dir) + PIPE0_STATE_DATA_IN, // DATA IN stage + PIPE0_STATE_DATA_OUT, // DATA OUT stage PIPE0_STATE_STATUS_IN, // STATUS IN — device sends IN-ZLP; awaits send-ACK IRQ PIPE0_STATE_STATUS_OUT, // post-DATAEND, neither edpt0_xfer(STATUS OUT) nor confirmation IRQ has happened yet PIPE0_STATE_STATUS_OUT_PENDING, // one of {edpt0_xfer(STATUS OUT), confirmation IRQ} has happened; the other fires xfer_complete @@ -95,12 +96,41 @@ typedef struct { uint16_t remain_wlength; // bytes remaining in the control transfer's DATA stage uint8_t state; uint8_t pending_addr; // new USB address latched by dcd_set_address; applied when STATUS IN completes + tusb_control_request_t deferred_setup; + bool deferred_setup_valid; } pipe0; pipe_state_t pipe[MUSB_PIPE_COUNT]; } dcd_data_t; static dcd_data_t _dcd; +static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, + tusb_control_request_t const* req, bool is_isr) { + _dcd.pipe0.remain_wlength = req->wLength; + + if (req->wLength == 0) { + _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; + } else { + if (req->bmRequestType & TUSB_DIR_IN_MASK) { + _dcd.pipe0.state = PIPE0_STATE_DATA_IN; + ep_csr->csr0l = MUSB_CSRL0_RXRDYC; + } else { + _dcd.pipe0.state = PIPE0_STATE_DATA_OUT; + } + } + + dcd_event_setup_received(rhport, (const uint8_t *) req, is_isr); +} + +static void pipe0_process_deferred_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, bool is_isr) { + if (!_dcd.pipe0.deferred_setup_valid) { + return; + } + + _dcd.pipe0.deferred_setup_valid = false; + pipe0_start_setup(rhport, ep_csr, &_dcd.pipe0.deferred_setup, is_isr); +} + // EP0 must not call this — it has its own scalars in dcd_data_t. TU_ATTR_ALWAYS_INLINE static inline pipe_state_t* pipe_get(uint8_t epnum, tusb_dir_t epdir) { size_t idx = epnum - 1u; @@ -323,7 +353,7 @@ static void process_epout(uint8_t rhport, musb_regs_t *musb_regs, uint8_t epnum, static bool edpt_n_xfer(uint8_t rhport, uint8_t ep_addr, void *buffer, uint16_t total_bytes, bool use_fifo, bool is_isr) { const uint8_t epnum = tu_edpt_number(ep_addr); - const unsigned dir_in = tu_edpt_dir(ep_addr); + const tusb_dir_t dir_in = tu_edpt_dir(ep_addr); pipe_state_t *pipe = pipe_get(epnum, dir_in); if (use_fifo) { @@ -361,7 +391,8 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ const unsigned dir_in = tu_edpt_dir(ep_addr); switch (_dcd.pipe0.state) { - case PIPE0_STATE_DATA: { + case PIPE0_STATE_DATA_IN: + case PIPE0_STATE_DATA_OUT: { _dcd.pipe0.xact_len = total_bytes; if (dir_in) { // DATA IN: load FIFO, set TXRDY. Add DATAEND on the last chunk @@ -396,6 +427,7 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ // Second event — IRQ already arrived, fire complete now. _dcd.pipe0.state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, ep_addr, 0, XFER_RESULT_SUCCESS, is_isr); + pipe0_process_deferred_setup(rhport, ep_csr, is_isr); break; default: break; @@ -410,9 +442,14 @@ static void process_ep0(uint8_t rhport) { musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0); uint_fast8_t csrl = ep_csr->csr0l; + if (csrl & MUSB_CSRL0_DATAEND) { + return; + } + if (csrl & MUSB_CSRL0_STALLED) { ep_csr->csr0l = 0; _dcd.pipe0.state = PIPE0_STATE_IDLE; + _dcd.pipe0.deferred_setup_valid = false; return; } @@ -421,6 +458,7 @@ static void process_ep0(uint8_t rhport) { // do nothing, it is probably another setup packet, usbd will reset its state. ep_csr->csr0l = MUSB_CSRL0_SETENDC; _dcd.pipe0.state = PIPE0_STATE_IDLE; + _dcd.pipe0.deferred_setup_valid = false; if (!(csrl & MUSB_CSRL0_RXRDY)) { return; /* no SETUP waiting behind it */ } @@ -430,7 +468,7 @@ static void process_ep0(uint8_t rhport) { if (csrl & MUSB_CSRL0_RXRDY) { const uint16_t count0 = ep_csr->count0; switch (_dcd.pipe0.state) { - case PIPE0_STATE_IDLE: + case PIPE0_STATE_IDLE: { TU_ASSERT(sizeof(tusb_control_request_t) == count0, ); union { tusb_control_request_t req; @@ -438,22 +476,11 @@ static void process_ep0(uint8_t rhport) { } setup_packet; setup_packet.u32[0] = musb_regs->fifo[0]; setup_packet.u32[1] = musb_regs->fifo[0]; - - _dcd.pipe0.remain_wlength = setup_packet.req.wLength; - - if (setup_packet.req.wLength == 0) { - _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; - } else { - _dcd.pipe0.state = PIPE0_STATE_DATA; - // If OUT (rx) direction, let edpt0_xfer() clear RXRDY when it's ready to receive data. - if (setup_packet.req.bmRequestType & TUSB_DIR_IN_MASK) { - ep_csr->csr0l = MUSB_CSRL0_RXRDYC; - } - } - dcd_event_setup_received(rhport, (const uint8_t *)&setup_packet.req, true); + pipe0_start_setup(rhport, ep_csr, &setup_packet.req, true); break; + } - case PIPE0_STATE_DATA: { + case PIPE0_STATE_DATA_OUT: { // EP0 OUT is single-packet (TU_ASSERT total_bytes <= EP0_SIZE in edpt0_xfer) // so the whole packet drains in one shot. if (count0) { @@ -463,31 +490,54 @@ static void process_ep0(uint8_t rhport) { if (_dcd.pipe0.remain_wlength == 0) { // last packet: change state and leave RXRDY for edpt0_xfer(STATUS IN) to ack _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; - } else { - ep_csr->csr0l = MUSB_CSRL0_RXRDYC; } dcd_event_xfer_complete(rhport, TU_EP0_OUT, count0, XFER_RESULT_SUCCESS, true); break; } - default: break; + // New SETUP packet arrived while old control transfer is not finished yet. This could happen in following scenarios: + // - Status IN/OUT finished, IRQ and new setup packet IRQ arrive at the same time. + // - Data IN finished and status OUT is received, both IRQs and new setup packet IRQ arrive at the same time. + // could happen when CPU load is high, save the new setup packet for later processing after current status stage complete. + case PIPE0_STATE_STATUS_OUT: + case PIPE0_STATE_STATUS_OUT_PENDING: + case PIPE0_STATE_STATUS_IN: + case PIPE0_STATE_DATA_IN: { + TU_ASSERT(sizeof(tusb_control_request_t) == count0, ); + union { + tusb_control_request_t req; + uint32_t u32[2]; + } setup_packet; + setup_packet.u32[0] = musb_regs->fifo[0]; + setup_packet.u32[1] = musb_regs->fifo[0]; + + _dcd.pipe0.deferred_setup = setup_packet.req; + _dcd.pipe0.deferred_setup_valid = true; + goto process_status; + } } return; } +process_status: /* When CSRL0 is zero, it means that either * - completion of sending any length packet TxPktRdy clear * - or status stage is complete (ZLP) after DataEnd is set */ switch (_dcd.pipe0.state) { - case PIPE0_STATE_DATA: + case PIPE0_STATE_DATA_IN: // csrl == 0 in DATA state = TXRDY just cleared, i.e. a DATA IN packet was successfully sent. If the just-sent // packet was the last (DATAEND was set when ep0_remain_datalen hit zero), transition // to STATUS_OUT to await the host's STATUS-OUT ZLP confirmation IRQ. if (_dcd.pipe0.remain_wlength == 0) { _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT; + // If a new SETUP was deferred then STATUS OUT IRQ is missed, manually transition to STATUS_OUT_PENDING to allow ep0_xfer(STATUS OUT) to fire complete immediately. + if (_dcd.pipe0.deferred_setup_valid) { + _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING; + } } dcd_event_xfer_complete(rhport, TU_EP0_IN, _dcd.pipe0.xact_len, XFER_RESULT_SUCCESS, true); + break; case PIPE0_STATE_STATUS_OUT: @@ -499,6 +549,7 @@ static void process_ep0(uint8_t rhport) { // Second event — edpt0_xfer(STATUS OUT) already called, fire complete now. _dcd.pipe0.state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); + pipe0_process_deferred_setup(rhport, ep_csr, true); break; case PIPE0_STATE_STATUS_IN: @@ -508,6 +559,7 @@ static void process_ep0(uint8_t rhport) { } _dcd.pipe0.state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, TU_EP0_IN, 0, XFER_RESULT_SUCCESS, true); + pipe0_process_deferred_setup(rhport, ep_csr, true); break; default: break; @@ -527,6 +579,7 @@ static void process_bus_reset(uint8_t rhport) { _dcd.pipe0.buf = NULL; _dcd.pipe0.xact_len = 0; _dcd.pipe0.remain_wlength = 0; + _dcd.pipe0.deferred_setup_valid = false; musb->intr_txen = 1; /* Enable only EP0 */ musb->intr_rxen = 0; @@ -646,7 +699,7 @@ void dcd_sof_enable(uint8_t rhport, bool en) bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) { const unsigned ep_addr = ep_desc->bEndpointAddress; const unsigned epn = tu_edpt_number(ep_addr); - const unsigned epdir = tu_edpt_dir(ep_addr); + const tusb_dir_t epdir = tu_edpt_dir(ep_addr); const unsigned mps = tu_edpt_packet_size(ep_desc); pipe_state_t *pipe = pipe_get(epn, epdir); @@ -689,7 +742,7 @@ bool dcd_edpt_iso_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t largest_packet bool dcd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const *ep_desc ) { const unsigned ep_addr = ep_desc->bEndpointAddress; const unsigned epn = tu_edpt_number(ep_addr); - const unsigned dir_in = tu_edpt_dir(ep_addr); + const tusb_dir_t dir_in = tu_edpt_dir(ep_addr); const unsigned mps = tu_edpt_packet_size(ep_desc); unsigned const ie = musb_dcd_get_int_enable(rhport); @@ -804,6 +857,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { if (ep_addr == TU_EP0_OUT) { /* Ignore EP0 OUT */ _dcd.pipe0.state = PIPE0_STATE_IDLE; _dcd.pipe0.buf = NULL; + _dcd.pipe0.deferred_setup_valid = false; ep_csr->csr0l = MUSB_CSRL0_STALL; } } else { diff --git a/src/portable/mentor/musb/musb_max32.h b/src/portable/mentor/musb/musb_max32.h index 599de2ca1..134b47122 100644 --- a/src/portable/mentor/musb/musb_max32.h +++ b/src/portable/mentor/musb/musb_max32.h @@ -47,7 +47,7 @@ extern "C" { #define MUSB_CFG_SHARED_FIFO 1 // shared FIFO for TX and RX endpoints #define MUSB_CFG_DYNAMIC_FIFO 0 // dynamic EP FIFO sizing -const uintptr_t MUSB_BASES[] = { MXC_BASE_USBHS }; +static const uintptr_t MUSB_BASES[] = { MXC_BASE_USBHS }; #if CFG_TUD_ENABLED #define USBHS_M31_CLOCK_RECOVERY diff --git a/src/portable/mentor/musb/musb_ti.h b/src/portable/mentor/musb/musb_ti.h index 68e89d77d..deaea8017 100644 --- a/src/portable/mentor/musb/musb_ti.h +++ b/src/portable/mentor/musb/musb_ti.h @@ -49,7 +49,7 @@ #define MUSB_CFG_DYNAMIC_FIFO 1 #define MUSB_CFG_DYNAMIC_FIFO_SIZE 4096 -const uintptr_t MUSB_BASES[] = { USB0_BASE }; +static const uintptr_t MUSB_BASES[] = { USB0_BASE }; // Header supports both device and host modes. Only include what's necessary #if CFG_TUD_ENABLED -- cgit v1.3.1 From 650e8a194fcfaa4b91203e9aedfecd614ea70105 Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Wed, 20 May 2026 23:22:02 +0200 Subject: dwc2: handle EP0 status OUT in RXFLVL interrupt Signed-off-by: HiFiPhile --- src/portable/synopsys/dwc2/dcd_dwc2.c | 65 +++++++++++++---------------------- 1 file changed, 24 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 72beb1b80..bdab49f1b 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -62,7 +62,6 @@ static xfer_ctl_t xfer_status[DWC2_EP_MAX][2]; typedef struct { // EP0 transfers are limited to 1 packet - larger sizes has to be split uint16_t ep0_pending[2]; // Index determines direction as tusb_dir_t type - bool ep0_out_zlp_armed; // EP0 OUT ZLP transfer is armed and waiting for completion uint16_t dfifo_top; // top free location in DFIFO in words // Number of IN endpoints active @@ -70,6 +69,9 @@ typedef struct { // SOF enabling flag - required for SOF to not get disabled in ISR when SOF was enabled by bool sof_en; + + // EP0 status OUT flag + bool ep0_status_out; } dcd_data_t; static dcd_data_t _dcd_data; @@ -667,7 +669,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t to if (epnum == 0) { _dcd_data.ep0_pending[dir] = total_bytes; if (dir == TUSB_DIR_OUT) { - _dcd_data.ep0_out_zlp_armed = (total_bytes == 0); + _dcd_data.ep0_status_out = (total_bytes == 0); } } @@ -748,11 +750,9 @@ static void handle_bus_reset(uint8_t rhport) { tu_memclr(xfer_status, sizeof(xfer_status)); - _dcd_data.ep0_pending[TUSB_DIR_OUT] = 0; - _dcd_data.ep0_pending[TUSB_DIR_IN] = 0; - _dcd_data.ep0_out_zlp_armed = false; _dcd_data.sof_en = false; _dcd_data.allocated_epin_count = 0; + _dcd_data.ep0_status_out = false; // 1. NAK for all OUT endpoints for (uint8_t n = 0; n < ep_count; n++) { @@ -907,6 +907,9 @@ static void handle_rxflvl_irq(uint8_t rhport) { // We can receive up to three setup packets in succession, but only the last one is valid. setup[0] = (*rx_fifo); setup[1] = (*rx_fifo); + + // Clear previous pending EP0 OUT if any + _dcd_data.ep0_status_out = false; break; } @@ -946,6 +949,12 @@ static void handle_rxflvl_irq(uint8_t rhport) { // Out packet done // After this entry is popped from the receive FIFO, dwc2 asserts a Transfer Completed interrupt on // the specified OUT endpoint which will be handled by handle_epout_irq() + + // EP0 status OUT is complete + if (epnum == 0 && _dcd_data.ep0_status_out) { + _dcd_data.ep0_status_out = false; + dcd_event_xfer_complete(rhport, epnum, 0, XFER_RESULT_SUCCESS, true); + } break; default: break; // nothing to do @@ -953,21 +962,7 @@ static void handle_rxflvl_irq(uint8_t rhport) { } static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepint_bm) { - xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); - const bool ep0_status_complete_before_setup = (epnum == 0) && doepint_bm.setup_phase_done && - doepint_bm.xfer_complete && - _dcd_data.ep0_out_zlp_armed && - (_dcd_data.ep0_pending[TUSB_DIR_OUT] == 0) && - (xfer->total_len == 0); - if (doepint_bm.setup_phase_done) { - if (ep0_status_complete_before_setup) { - _dcd_data.ep0_out_zlp_armed = false; - dcd_event_xfer_complete(rhport, epnum, 0, XFER_RESULT_SUCCESS, true); - } else if (epnum == 0) { - _dcd_data.ep0_out_zlp_armed = false; - } - // Cleanup previous pending EP0 IN transfer if any dwc2_dep_t* epin0 = &DWC2_REG(rhport)->epin[0]; if (edpt_is_enabled(epin0)) { @@ -983,13 +978,16 @@ static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doe // Note: even though (xfer_complete + status_phase_rx) is for buffered DMA only, for STM32L47x (dwc2 v3.00a) they // can is set when GRXSTS_PKTSTS_SETUP_RX is popped therefore they can bet set before/together with setup_phase_done if (!doepint_bm.status_phase_rx && !doepint_bm.setup_packet_rx) { - if ((epnum == 0) && _dcd_data.ep0_pending[TUSB_DIR_OUT]) { - // EP0 can only handle one packet, Schedule another packet to be received. - edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT); - } else { - if (epnum == 0) { - _dcd_data.ep0_out_zlp_armed = false; + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); + if (epnum == 0) { + if (_dcd_data.ep0_pending[TUSB_DIR_OUT]) { + // EP0 can only handle one packet, Schedule another packet to be received. + edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT); + } else if (xfer->total_len > 0) { + // EP0 status out is handled in handle_rxflvl_irq + dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true); } + } else { dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true); } } @@ -1028,21 +1026,8 @@ static void handle_epin_slave(uint8_t rhport, uint8_t epnum, dwc2_diepint_t diep #if CFG_TUD_DWC2_DMA_ENABLE static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepint_bm) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); - xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); - const bool ep0_status_complete_before_setup = (epnum == 0) && doepint_bm.setup_phase_done && - doepint_bm.xfer_complete && - _dcd_data.ep0_out_zlp_armed && - (_dcd_data.ep0_pending[TUSB_DIR_OUT] == 0) && - (xfer->total_len == 0); if (doepint_bm.setup_phase_done) { - if (ep0_status_complete_before_setup) { - _dcd_data.ep0_out_zlp_armed = false; - dcd_event_xfer_complete(rhport, epnum, 0, XFER_RESULT_SUCCESS, true); - } else if (epnum == 0) { - _dcd_data.ep0_out_zlp_armed = false; - } - // Cleanup previous pending EP0 IN transfer if any dwc2_dep_t* epin0 = &DWC2_REG(rhport)->epin[0]; if (edpt_is_enabled(epin0)) { @@ -1064,6 +1049,7 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT); } else { dwc2_dep_t* epout = &dwc2->epout[epnum]; + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); // determine actual received bytes const dwc2_ep_tsize_t tsiz = {.value = epout->tsiz}; @@ -1076,9 +1062,6 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi dma_setup_prepare(rhport); } - if (epnum == 0) { - _dcd_data.ep0_out_zlp_armed = false; - } dcd_dcache_invalidate(xfer->buffer, xfer->total_len); dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true); } -- cgit v1.3.1 From f52d9c7b27dc0234fb4738762a8a6da01817e2bf Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Mon, 25 May 2026 22:28:39 +0200 Subject: optimize interrupt handling time Signed-off-by: HiFiPhile --- src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c | 2 +- src/portable/st/stm32_fsdev/fsdev_stm32.h | 33 +++++++++++++++++++-------- 2 files changed, 24 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index 4dfd04fb4..6f7f490a8 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -343,7 +343,7 @@ void dcd_int_handler(uint8_t rhport) { uint32_t int_status = FSDEV_REG->ISTR; /* Put SOF flag at the beginning of ISR in case to get least amount of jitter if it is used for timing purposes */ - if (int_status & U_ISTR_SOF) { + if ((int_status & U_ISTR_SOF) && (FSDEV_REG->CNTR & U_CNTR_SOFM)) { FSDEV_REG->ISTR = (fsdev_bus_t)~U_ISTR_SOF; dcd_event_sof(0, FSDEV_REG->FNR & U_FNR_FN, true); } diff --git a/src/portable/st/stm32_fsdev/fsdev_stm32.h b/src/portable/st/stm32_fsdev/fsdev_stm32.h index 74cc9d0a4..b15c95302 100644 --- a/src/portable/st/stm32_fsdev/fsdev_stm32.h +++ b/src/portable/st/stm32_fsdev/fsdev_stm32.h @@ -266,32 +266,45 @@ TU_ATTR_ALWAYS_INLINE static inline void fsdev_int_disable(uint8_t rhport) { * * CTR may trigger before final PMA SRAM accesses complete on OUT transfers. * Insert delay before reading PMA count/data. - * Max CPU frequency in MHz, used to derive conservative FSDEV PMA delay defaults. + * Max CPU frequency in Hz, used to derive conservative FSDEV PMA delay defaults. */ #if CFG_TUSB_MCU == OPT_MCU_STM32H5 - #define FSDEV_STM32_CPU_MHZ 250U + #define FSDEV_STM32_CPU_HZ 250000000U #elif CFG_TUSB_MCU == OPT_MCU_STM32U5 - #define FSDEV_STM32_CPU_MHZ 160U + #define FSDEV_STM32_CPU_HZ 160000000U #elif CFG_TUSB_MCU == OPT_MCU_STM32U3 - #define FSDEV_STM32_CPU_MHZ 96U + #define FSDEV_STM32_CPU_HZ 96000000U #elif CFG_TUSB_MCU == OPT_MCU_STM32U0 - #define FSDEV_STM32_CPU_MHZ 56U + #define FSDEV_STM32_CPU_HZ 56000000U #elif CFG_TUSB_MCU == OPT_MCU_STM32G0 - #define FSDEV_STM32_CPU_MHZ 64U + #define FSDEV_STM32_CPU_HZ 64000000U #elif CFG_TUSB_MCU == OPT_MCU_STM32C0 - #define FSDEV_STM32_CPU_MHZ 48U + #define FSDEV_STM32_CPU_HZ 48000000U #elif CFG_TUSB_MCU == OPT_MCU_STM32C5 - #define FSDEV_STM32_CPU_MHZ 144U + #define FSDEV_STM32_CPU_HZ 144000000U #endif +// 11 cycles / 800ns = ~13750000 cycles per second, used to derive conservative FSDEV PMA delay defaults #ifndef CFG_TUSB_FSDEV_BTABLE_FS_DELAY_COUNT - #define CFG_TUSB_FSDEV_BTABLE_FS_DELAY_COUNT (FSDEV_STM32_CPU_MHZ / 4U) + #define CFG_TUSB_FSDEV_BTABLE_FS_DELAY_COUNT (FSDEV_STM32_CPU_HZ / 13750000U) #endif +// 11 cycles / 6.4us = ~1718750 cycles per second, used to derive conservative FSDEV PMA delay defaults #ifndef CFG_TUSB_FSDEV_BTABLE_LS_DELAY_COUNT - #define CFG_TUSB_FSDEV_BTABLE_LS_DELAY_COUNT (FSDEV_STM32_CPU_MHZ * 2U) + #define CFG_TUSB_FSDEV_BTABLE_LS_DELAY_COUNT (FSDEV_STM32_CPU_HZ / 1718750U) #endif +/** + * LDR from SP-relative: 2 cycles + * SUBS: 1 cycle + * STR to SP-relative: 2 cycles + * LDR from SP-relative: 2 cycles + * CMP: 1 cycle + * BNE: + * taken: 3 cycles total (often shown as 1 + pipeline refill) + * not taken: 1 cycle + * Total cycles if delay is needed: 11 cycles + */ TU_ATTR_ALWAYS_INLINE static inline void fsdev_btable_workaround_delay(bool low_speed) { volatile uint32_t cycle_count = low_speed ? CFG_TUSB_FSDEV_BTABLE_LS_DELAY_COUNT : CFG_TUSB_FSDEV_BTABLE_FS_DELAY_COUNT; while (cycle_count > 0U) { -- cgit v1.3.1 From d63a45509fd283f5ffccc29cd8569e6efd075c59 Mon Sep 17 00:00:00 2001 From: Jie Feng Date: Thu, 21 May 2026 14:52:38 +0800 Subject: ch32_usbhs: fix endpoint stall length index and clear-stall response Fix issue in the stall handling: - dcd_edpt_stall() for an IN endpoint cleared EP_TX_LEN(0) instead of EP_TX_LEN(ep_num), clobbering endpoint 0's transmit length register when stalling any other IN endpoint. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/portable/wch/dcd_ch32_usbhs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/portable/wch/dcd_ch32_usbhs.c b/src/portable/wch/dcd_ch32_usbhs.c index a6dd5bb79..ea3b052ad 100644 --- a/src/portable/wch/dcd_ch32_usbhs.c +++ b/src/portable/wch/dcd_ch32_usbhs.c @@ -354,7 +354,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { if (dir == TUSB_DIR_OUT) { EP_RX_CTRL(ep_num) = USBHS_EP_R_RES_STALL; } else { - EP_TX_LEN(0) = 0; + EP_TX_LEN(ep_num) = 0; EP_TX_CTRL(ep_num) = USBHS_EP_T_RES_STALL; } } -- cgit v1.3.1 From e520cff090e5da57e38ef3c7af250aab6d57a186 Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Wed, 27 May 2026 00:19:42 +0200 Subject: dwc2: simplify EP0 ZLP handling Signed-off-by: HiFiPhile --- src/portable/synopsys/dwc2/dcd_dwc2.c | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 8997394dd..23fe671d4 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -69,9 +69,6 @@ typedef struct { // SOF enabling flag - required for SOF to not get disabled in ISR when SOF was enabled by bool sof_en; - - // EP0 status OUT flag - bool ep0_status_out; } dcd_data_t; static dcd_data_t _dcd_data; @@ -668,9 +665,6 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t to // EP0 can only handle one packet if (epnum == 0) { _dcd_data.ep0_pending[dir] = total_bytes; - if (dir == TUSB_DIR_OUT) { - _dcd_data.ep0_status_out = (total_bytes == 0); - } } // Schedule packets to be sent within interrupt @@ -752,7 +746,6 @@ static void handle_bus_reset(uint8_t rhport) { _dcd_data.sof_en = false; _dcd_data.allocated_epin_count = 0; - _dcd_data.ep0_status_out = false; // 1. NAK for all OUT endpoints for (uint8_t n = 0; n < ep_count; n++) { @@ -907,9 +900,6 @@ static void handle_rxflvl_irq(uint8_t rhport) { // We can receive up to three setup packets in succession, but only the last one is valid. setup[0] = (*rx_fifo); setup[1] = (*rx_fifo); - - // Clear previous pending EP0 OUT if any - _dcd_data.ep0_status_out = false; break; } @@ -940,6 +930,10 @@ static void handle_rxflvl_irq(uint8_t rhport) { xfer->total_len -= tsiz.xfer_size; if (epnum == 0) { _dcd_data.ep0_pending[TUSB_DIR_OUT] = 0; + // Handle EP0 STATUS OUT (or ZLP) here to avoid mix with next SETUP packet received IRQ + if (xfer->total_len == 0) { + dcd_event_xfer_complete(rhport, 0, 0, XFER_RESULT_SUCCESS, true); + } } } break; @@ -949,12 +943,6 @@ static void handle_rxflvl_irq(uint8_t rhport) { // Out packet done // After this entry is popped from the receive FIFO, dwc2 asserts a Transfer Completed interrupt on // the specified OUT endpoint which will be handled by handle_epout_irq() - - // EP0 status OUT is complete - if (epnum == 0 && _dcd_data.ep0_status_out) { - _dcd_data.ep0_status_out = false; - dcd_event_xfer_complete(rhport, epnum, 0, XFER_RESULT_SUCCESS, true); - } break; default: break; // nothing to do @@ -984,7 +972,7 @@ static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doe // EP0 can only handle one packet, Schedule another packet to be received. edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT); } else if (xfer->total_len > 0) { - // EP0 status out is handled in handle_rxflvl_irq + // EP0 STATUS OUT (or ZLP) is handled in handle_rxflvl_irq() dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true); } } else { -- cgit v1.3.1 From a560281051022473c844bdb258be452da52ce5c3 Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Fri, 22 May 2026 13:42:08 +0200 Subject: dwc2: fix EP0 DMA setup race condition Signed-off-by: HiFiPhile --- src/portable/synopsys/dwc2/dcd_dwc2.c | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 23fe671d4..1c119eef4 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -73,8 +73,9 @@ typedef struct { static dcd_data_t _dcd_data; -CFG_TUD_MEM_SECTION static struct { - TUD_EPBUF_DEF(setup_packet, 8); +CFG_TUD_MEM_SECTION static union { + TUD_EPBUF_DEF(setup_buffer, 8); + tusb_control_request_t setup_packet; } _dcd_usbbuf; static tud_configure_dwc2_t _tud_cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; @@ -138,7 +139,7 @@ static void dma_setup_prepare(uint8_t rhport) { // Receive only 1 packet dwc2->epout[0].doeptsiz = (1 << DOEPTSIZ_STUPCNT_Pos) | (1 << DOEPTSIZ_PKTCNT_Pos) | (8 << DOEPTSIZ_XFRSIZ_Pos); - dwc2->epout[0].doepdma = (uintptr_t) _dcd_usbbuf.setup_packet; + dwc2->epout[0].doepdma = (uintptr_t) _dcd_usbbuf.setup_buffer; dwc2->epout[0].doepctl |= DOEPCTL_EPENA | DOEPCTL_USBAEP; } @@ -896,7 +897,7 @@ static void handle_rxflvl_irq(uint8_t rhport) { case GRXSTS_PKTSTS_SETUP_RX: { // Setup packet received - uint32_t* setup = (uint32_t*)(uintptr_t) _dcd_usbbuf.setup_packet; + uint32_t* setup = (uint32_t*)(uintptr_t) _dcd_usbbuf.setup_buffer; // We can receive up to three setup packets in succession, but only the last one is valid. setup[0] = (*rx_fifo); setup[1] = (*rx_fifo); @@ -956,7 +957,7 @@ static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doe if (edpt_is_enabled(epin0)) { edpt_disable(rhport, 0x80, false); } - dcd_event_setup_received(rhport, _dcd_usbbuf.setup_packet, true); + dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); return; } @@ -1021,9 +1022,13 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi if (edpt_is_enabled(epin0)) { edpt_disable(rhport, 0x80, false); } - dma_setup_prepare(rhport); - dcd_dcache_invalidate(_dcd_usbbuf.setup_packet, 8); - dcd_event_setup_received(rhport, _dcd_usbbuf.setup_packet, true); + dcd_dcache_invalidate(_dcd_usbbuf.setup_buffer, 8); + dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); + + // Prepare EP0 for next setup if this setup has no data stage + if (_dcd_usbbuf.setup_packet.wLength == 0) { + dma_setup_prepare(rhport); + } return; } @@ -1044,9 +1049,8 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi const uint16_t remain = tsiz.xfer_size; xfer->total_len -= remain; - // this is ZLP, so prepare EP0 for next setup - // TODO use status phase rx - if(epnum == 0 && xfer->total_len == 0) { + // prepare EP0 for next setup + if(epnum == 0) { dma_setup_prepare(rhport); } @@ -1065,9 +1069,6 @@ static void handle_epin_dma(uint8_t rhport, uint8_t epnum, dwc2_diepint_t diepin // EP0 can only handle one packet. Schedule another packet to be transmitted. edpt_schedule_packets(rhport, epnum, TUSB_DIR_IN); } else { - if(epnum == 0) { - dma_setup_prepare(rhport); - } dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xfer->total_len, XFER_RESULT_SUCCESS, true); } } -- cgit v1.3.1 From 616acfa7328b1a05ea0370a3628fc6a07f4caf57 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 27 May 2026 19:20:58 +0700 Subject: osal add osal_task_get_current_handle() --- src/osal/osal.h | 47 +++++++++++++++++++++++++---------------------- src/osal/osal_freertos.h | 7 +++++++ src/osal/osal_mynewt.h | 6 ++++++ src/osal/osal_none.h | 16 ++++++++++++++++ src/osal/osal_pico.h | 7 +++++++ src/osal/osal_rtthread.h | 6 ++++++ src/osal/osal_rtx4.h | 6 ++++++ src/osal/osal_threadx.h | 5 +++++ src/osal/osal_zephyr.h | 6 ++++++ 9 files changed, 84 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/osal/osal.h b/src/osal/osal.h index 4840463f3..69cb356d4 100644 --- a/src/osal/osal.h +++ b/src/osal/osal.h @@ -76,28 +76,31 @@ typedef void (*osal_task_func_t)(void* param); /*-------------------------------------------------------------------- OSAL Porting API Should be implemented as static inline function in osal_port.h header - uint32_t osal_time_millis(void); - - void osal_spin_init(osal_spinlock_t *ctx); - void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) - void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr); - - osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef); - bool osal_semaphore_delete(osal_semaphore_t semd_hdl); - bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr); - bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec); - void osal_semaphore_reset(osal_semaphore_t sem_hdl); - - osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef); - bool osal_mutex_delete(osal_mutex_t mutex_hdl) - bool osal_mutex_lock (osal_mutex_t sem_hdl, uint32_t msec); - bool osal_mutex_unlock(osal_mutex_t mutex_hdl); - - osal_queue_t osal_queue_create(osal_queue_def_t* qdef); - bool osal_queue_delete(osal_queue_t qhdl); - bool osal_queue_receive(osal_queue_t qhdl, void* data, uint32_t msec); - bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr); - bool osal_queue_empty(osal_queue_t qhdl); + uint32_t osal_time_millis(void); + + void osal_task_delay(uint32_t msec); + osal_task_handle_t osal_task_get_current_handle(void); + + void osal_spin_init(osal_spinlock_t *ctx); + void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) + void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr); + + osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef); + bool osal_semaphore_delete(osal_semaphore_t semd_hdl); + bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr); + bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec); + void osal_semaphore_reset(osal_semaphore_t sem_hdl); + + osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef); + bool osal_mutex_delete(osal_mutex_t mutex_hdl) + bool osal_mutex_lock (osal_mutex_t sem_hdl, uint32_t msec); + bool osal_mutex_unlock(osal_mutex_t mutex_hdl); + + osal_queue_t osal_queue_create(osal_queue_def_t* qdef); + bool osal_queue_delete(osal_queue_t qhdl); + bool osal_queue_receive(osal_queue_t qhdl, void* data, uint32_t msec); + bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr); + bool osal_queue_empty(osal_queue_t qhdl); --------------------------------------------------------------------------*/ diff --git a/src/osal/osal_freertos.h b/src/osal/osal_freertos.h index 898edd4ed..9b12b5c0e 100644 --- a/src/osal/osal_freertos.h +++ b/src/osal/osal_freertos.h @@ -83,6 +83,13 @@ typedef struct { //--------------------------------------------------------------------+ // TASK API //--------------------------------------------------------------------+ +typedef TaskHandle_t osal_task_handle_t; + +// Requires INCLUDE_xTaskGetCurrentTaskHandle == 1 in FreeRTOSConfig.h. +TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { + return xTaskGetCurrentTaskHandle(); +} + TU_ATTR_ALWAYS_INLINE static inline uint32_t _osal_ms2tick(uint32_t msec) { if (msec == OSAL_TIMEOUT_WAIT_FOREVER) { return portMAX_DELAY; } if (msec == 0) { return 0; } diff --git a/src/osal/osal_mynewt.h b/src/osal/osal_mynewt.h index 335d53491..d1fa77ecb 100644 --- a/src/osal/osal_mynewt.h +++ b/src/osal/osal_mynewt.h @@ -36,6 +36,12 @@ //--------------------------------------------------------------------+ // TASK API //--------------------------------------------------------------------+ +typedef struct os_task* osal_task_handle_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { + return os_sched_get_current_task(); +} + TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { os_time_delay( os_time_ms_to_ticks32(msec) ); } diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h index 7bf6029d6..e174d3518 100644 --- a/src/osal/osal_none.h +++ b/src/osal/osal_none.h @@ -33,6 +33,22 @@ extern "C" { // osal_time_millis() is not provided, tusb_time_millis_api() must be implemented by user application +//--------------------------------------------------------------------+ +// TASK API +//--------------------------------------------------------------------+ +// Bare-metal single context: return a non-NULL sentinel so equality compares true. +typedef void* osal_task_handle_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { + return (osal_task_handle_t) 1; +} + +// Bare-metal has no scheduler to yield to; this is dead code in practice because +// callers gate it on running outside the host task, which can't happen here. +TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { + (void) msec; +} + //--------------------------------------------------------------------+ // Spinlock API //--------------------------------------------------------------------+ diff --git a/src/osal/osal_pico.h b/src/osal/osal_pico.h index 6a0a21bb3..364c38b01 100644 --- a/src/osal/osal_pico.h +++ b/src/osal/osal_pico.h @@ -39,6 +39,13 @@ extern "C" { //--------------------------------------------------------------------+ // TASK API //--------------------------------------------------------------------+ +// Bare-metal single context: return a non-NULL sentinel so equality compares true. +typedef void* osal_task_handle_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { + return (osal_task_handle_t) 1; +} + TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { sleep_ms(msec); } diff --git a/src/osal/osal_rtthread.h b/src/osal/osal_rtthread.h index f560281c5..a151a7d70 100644 --- a/src/osal/osal_rtthread.h +++ b/src/osal/osal_rtthread.h @@ -38,6 +38,12 @@ extern "C" { //--------------------------------------------------------------------+ // TASK API //--------------------------------------------------------------------+ +typedef rt_thread_t osal_task_handle_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { + return rt_thread_self(); +} + TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { rt_thread_mdelay(msec); } diff --git a/src/osal/osal_rtx4.h b/src/osal/osal_rtx4.h index e1930c96c..e5b708a2c 100644 --- a/src/osal/osal_rtx4.h +++ b/src/osal/osal_rtx4.h @@ -37,6 +37,12 @@ extern "C" { //--------------------------------------------------------------------+ // TASK API //--------------------------------------------------------------------+ +typedef OS_TID osal_task_handle_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { + return os_tsk_self(); +} + TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { uint16_t hi = msec >> 16; uint16_t lo = msec; diff --git a/src/osal/osal_threadx.h b/src/osal/osal_threadx.h index 6bcf9c5ab..cca4eb487 100644 --- a/src/osal/osal_threadx.h +++ b/src/osal/osal_threadx.h @@ -37,6 +37,11 @@ extern "C" { //--------------------------------------------------------------------+ // TASK API //--------------------------------------------------------------------+ +typedef TX_THREAD* osal_task_handle_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { + return tx_thread_identify(); +} TU_ATTR_ALWAYS_INLINE static inline uint32_t _osal_ms2tick(uint32_t msec) { if ( msec == TX_WAIT_FOREVER ) { diff --git a/src/osal/osal_zephyr.h b/src/osal/osal_zephyr.h index 900ac786c..6ea45131e 100644 --- a/src/osal/osal_zephyr.h +++ b/src/osal/osal_zephyr.h @@ -31,6 +31,12 @@ //--------------------------------------------------------------------+ // TASK API //--------------------------------------------------------------------+ +typedef k_tid_t osal_task_handle_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { + return k_current_get(); +} + TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { k_msleep(msec); } -- cgit v1.3.1 From c5676382c7d5cad7b6cfe5dc185d9891b89241f2 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 28 May 2026 18:23:46 +0700 Subject: abstract OS logic with `CFG_TUSB_OS_HAS_SCHEDULER` to simplify conditional checks --- examples/device/msc_dual_lun/src/main.c | 2 +- examples/dual/host_info_to_device_cdc/src/main.c | 6 +++--- src/tusb_option.h | 12 ++++++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/examples/device/msc_dual_lun/src/main.c b/examples/device/msc_dual_lun/src/main.c index a4ade6f9b..1d764f12c 100644 --- a/examples/device/msc_dual_lun/src/main.c +++ b/examples/device/msc_dual_lun/src/main.c @@ -71,7 +71,7 @@ static void usb_device_init(void) { board_init_after_tusb(); } -#if CFG_TUSB_OS != OPT_OS_NONE && CFG_TUSB_OS != OPT_OS_PICO +#if CFG_TUSB_OS_HAS_SCHEDULER static void usb_device_task(RTOS_PARAM param) { (void) param; usb_device_init(); diff --git a/examples/dual/host_info_to_device_cdc/src/main.c b/examples/dual/host_info_to_device_cdc/src/main.c index cf3430464..5186f91dc 100644 --- a/examples/dual/host_info_to_device_cdc/src/main.c +++ b/examples/dual/host_info_to_device_cdc/src/main.c @@ -130,7 +130,7 @@ static void main_task(void* param) { led_blinking_task(); // preempted RTOS run device/host stack in its own task -#if CFG_TUSB_OS == OPT_OS_NONE || CFG_TUSB_OS == OPT_OS_PICO +#if CFG_TUSB_OS_HAS_SCHEDULER == 0 tud_task(); // tinyusb device task tuh_task(); // tinyusb host task #endif @@ -140,7 +140,7 @@ static void main_task(void* param) { int main(void) { board_init(); -#if CFG_TUSB_OS == OPT_OS_NONE || CFG_TUSB_OS == OPT_OS_PICO +#if CFG_TUSB_OS_HAS_SCHEDULER == 0 printf("TinyUSB Host Information -> Device CDC Example\r\n"); usb_device_init(); @@ -156,7 +156,7 @@ int main(void) { return 0; } -#if CFG_TUSB_OS != OPT_OS_NONE && CFG_TUSB_OS != OPT_OS_PICO +#if CFG_TUSB_OS_HAS_SCHEDULER // USB Device Driver task for RTOS static void usb_device_task(void *param) { (void) param; diff --git a/src/tusb_option.h b/src/tusb_option.h index 74eb8cc06..dcf0646cf 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -535,6 +535,18 @@ #define CFG_TUSB_OS OPT_OS_NONE #endif +// 1 when CFG_TUSB_OS provides a preemptive scheduler with distinct tasks +// (FreeRTOS, Zephyr, ThreadX, etc.); 0 when the application is single-context +// (bare-metal OS_NONE or Pico SDK). Sync host control xfers from the host +// task are forbidden when this is 1. +#ifndef CFG_TUSB_OS_HAS_SCHEDULER + #if CFG_TUSB_OS == OPT_OS_NONE || CFG_TUSB_OS == OPT_OS_PICO + #define CFG_TUSB_OS_HAS_SCHEDULER 0 + #else + #define CFG_TUSB_OS_HAS_SCHEDULER 1 + #endif +#endif + #ifndef CFG_TUSB_OS_INC_PATH #ifndef CFG_TUSB_OS_INC_PATH_DEFAULT #define CFG_TUSB_OS_INC_PATH_DEFAULT -- cgit v1.3.1 From dafdc5c54f34f88c963f7efc0062d0e992074b8f Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Fri, 29 May 2026 00:05:44 +0200 Subject: dwc2: move OUT transfer management into RXFLVL IRQ - GRXSTSP register has internal FIFO, receiving events won't mix up (STATUS OUT & next SETUP) - Improve efficiency, remove 2nd IRQ overhead Signed-off-by: HiFiPhile --- src/portable/synopsys/dwc2/dcd_dwc2.c | 71 ++++++++++++++--------------------- 1 file changed, 28 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 1c119eef4..233840e8b 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -794,13 +794,15 @@ static void handle_bus_reset(uint8_t rhport) { xfer_status[0][TUSB_DIR_OUT].max_size = CFG_TUD_ENDPOINT0_SIZE; xfer_status[0][TUSB_DIR_IN].max_size = CFG_TUD_ENDPOINT0_SIZE; + uint32_t oepmsk = 0; if(dma_device_enabled(dwc2)) { + oepmsk = GINTMSK_OEPINT; dma_setup_prepare(rhport); } else { dwc2->epout[0].doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); } - dwc2->gintmsk |= GINTMSK_OTGINT | GINTMSK_OEPINT | GINTMSK_IEPINT | GINTMSK_IISOIXFRM; + dwc2->gintmsk |= GINTMSK_OTGINT | oepmsk | GINTMSK_IEPINT | GINTMSK_IISOIXFRM; } static void handle_enum_done(uint8_t rhport) { @@ -901,13 +903,27 @@ static void handle_rxflvl_irq(uint8_t rhport) { // We can receive up to three setup packets in succession, but only the last one is valid. setup[0] = (*rx_fifo); setup[1] = (*rx_fifo); + + dwc2_dep_t* epin0 = &dwc2->epin[0]; + if (edpt_is_enabled(epin0)) { + edpt_disable(rhport, 0x80, false); + } + + // (GenID < 3.00a) Must wait SETUP_DONE before next OUT transfer, otherwise OUT data may be corrupted. + // (GenID >= 3.00a) On the other hand STUPCNT is auto reloaded and SETUP_DONE is only triggered once after bus reset. + if (dwc2->gsnpsid >= DWC2_CORE_REV_3_00a) { + dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); + } break; } case GRXSTS_PKTSTS_SETUP_DONE: // Setup packet done: - // After popping this out, dwc2 asserts a DOEPINT_SETUP interrupt which is handled by handle_epout_irq() epout->doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); + + if (dwc2->gsnpsid < DWC2_CORE_REV_3_00a) { + dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); + } break; case GRXSTS_PKTSTS_RX_DATA: { @@ -931,55 +947,24 @@ static void handle_rxflvl_irq(uint8_t rhport) { xfer->total_len -= tsiz.xfer_size; if (epnum == 0) { _dcd_data.ep0_pending[TUSB_DIR_OUT] = 0; - // Handle EP0 STATUS OUT (or ZLP) here to avoid mix with next SETUP packet received IRQ - if (xfer->total_len == 0) { - dcd_event_xfer_complete(rhport, 0, 0, XFER_RESULT_SUCCESS, true); - } } } break; } - case GRXSTS_PKTSTS_RX_COMPLETE: + case GRXSTS_PKTSTS_RX_COMPLETE: { // Out packet done - // After this entry is popped from the receive FIFO, dwc2 asserts a Transfer Completed interrupt on - // the specified OUT endpoint which will be handled by handle_epout_irq() - break; - - default: break; // nothing to do - } -} - -static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepint_bm) { - if (doepint_bm.setup_phase_done) { - // Cleanup previous pending EP0 IN transfer if any - dwc2_dep_t* epin0 = &DWC2_REG(rhport)->epin[0]; - if (edpt_is_enabled(epin0)) { - edpt_disable(rhport, 0x80, false); - } - dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); - return; - } - - // Normal OUT transfer complete - if (doepint_bm.xfer_complete) { - // only handle data skip if it is setup or status related - // Note: even though (xfer_complete + status_phase_rx) is for buffered DMA only, for STM32L47x (dwc2 v3.00a) they - // can is set when GRXSTS_PKTSTS_SETUP_RX is popped therefore they can bet set before/together with setup_phase_done - if (!doepint_bm.status_phase_rx && !doepint_bm.setup_packet_rx) { xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); - if (epnum == 0) { - if (_dcd_data.ep0_pending[TUSB_DIR_OUT]) { - // EP0 can only handle one packet, Schedule another packet to be received. - edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT); - } else if (xfer->total_len > 0) { - // EP0 STATUS OUT (or ZLP) is handled in handle_rxflvl_irq() - dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true); - } + if (epnum == 0 && _dcd_data.ep0_pending[TUSB_DIR_OUT] > 0) { + // EP0 can only handle one packet, schedule another packet to be received. + edpt_schedule_packets(rhport, 0, TUSB_DIR_OUT); } else { dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true); } + break; } + + default: break; // nothing to do } } @@ -1108,8 +1093,6 @@ static void handle_ep_irq(uint8_t rhport, uint8_t dir) { #if CFG_TUD_DWC2_SLAVE_ENABLE if (dir == TUSB_DIR_IN) { handle_epin_slave(rhport, epnum, intr.diepint_bm); - } else { - handle_epout_slave(rhport, epnum, intr.doepint_bm); } #endif } @@ -1217,7 +1200,7 @@ void dcd_int_handler(uint8_t rhport) { dwc2->gotgint = otg_int; } - if(gintsts & GINTSTS_SOF) { + if(gintsts & GINTSTS_SOF && dwc2->gintmsk & GINTMSK_SOFM) { dwc2->gintsts = GINTSTS_SOF; dwc2->gintmsk |= GINTMSK_USBSUSPM; const uint32_t frame = (dwc2->dsts & DSTS_FNSOF) >> DSTS_FNSOF_Pos; @@ -1244,11 +1227,13 @@ void dcd_int_handler(uint8_t rhport) { } #endif +#if CFG_TUD_DWC2_DMA_ENABLE // OUT endpoint interrupt handling. if (gintsts & GINTSTS_OEPINT) { // OEPINT is read-only, clear using DOEPINTn handle_ep_irq(rhport, TUSB_DIR_OUT); } +#endif // IN endpoint interrupt handling. if (gintsts & GINTSTS_IEPINT) { -- cgit v1.3.1 From d754c0697cbd29874c56254bd97561349fb9a229 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 29 May 2026 16:16:21 +0700 Subject: Implement asynchronous control transfer queuing for USB host stack - Added a pending FIFO queue for asynchronous control transfers when the active slot is busy. - Introduced `control_xfer_dispatch_pending` to handle queued transfers on slot availability. - Improved synchronization for blocking and non-blocking transfer modes, preventing deadlocks in RTOS. - Refactored and renamed related functions for clarity and consistency. - Enhanced error handling and callback invocation for failed or stale transfers. --- src/common/tusb_types.h | 1 + src/host/usbh.c | 332 ++++++++++++++++++++++++++++++++++++----------- src/osal/osal_freertos.h | 8 +- 3 files changed, 263 insertions(+), 78 deletions(-) (limited to 'src') diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 959fc129a..cb06b89bb 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -282,6 +282,7 @@ typedef enum { XFER_RESULT_FAILED, XFER_RESULT_STALLED, XFER_RESULT_TIMEOUT, + XFER_RESULT_ABORTED, XFER_RESULT_INVALID } xfer_result_t; diff --git a/src/host/usbh.c b/src/host/usbh.c index 2e3c93c5e..05e03245f 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -40,6 +40,10 @@ #define CFG_TUH_TASK_QUEUE_SZ 16 #endif +#ifndef CFG_TUH_CONTROL_PENDING_QUEUE_SZ + #define CFG_TUH_CONTROL_PENDING_QUEUE_SZ 4 +#endif + #ifndef CFG_TUH_INTERFACE_MAX #define CFG_TUH_INTERFACE_MAX 8 #endif @@ -175,11 +179,11 @@ static OSAL_SPINLOCK_DEF(_usbh_spin, usbh_int_set); OSAL_QUEUE_DEF(usbh_int_set, _usbh_qdef, CFG_TUH_TASK_QUEUE_SZ, hcd_event_t); static osal_queue_t _usbh_q; - #if CFG_TUH_HUB +#if CFG_TUH_HUB // Deferred attachment queue, only needed when using hub OSAL_QUEUE_DEF(usbh_int_set, _usbh_daqdef, CFG_TUH_HUB, hcd_event_t); static osal_queue_t _usbh_daq; - #endif +#endif // Control transfers: since most controllers do not support multiple control transfers // on multiple devices concurrently and control transfers are not used much except for @@ -189,9 +193,9 @@ typedef struct { tuh_xfer_cb_t complete_cb; uintptr_t user_data; + volatile uint16_t actual_len; volatile uint8_t stage; uint8_t daddr; - volatile uint16_t actual_len; uint8_t failed_count; } usbh_ctrl_xfer_info_t; @@ -202,17 +206,32 @@ typedef struct { } usbh_call_after_t; typedef struct { - uint8_t controller_id; // controller ID + tusb_control_request_t setup; + uint8_t* buffer; + tuh_xfer_cb_t complete_cb; + uintptr_t user_data; + uint8_t daddr; + uint8_t daddr_gen; +} usbh_pending_ctrl_t; + +// FIFO for pending async control transfers since we only execute 1 control transfer at a time +TU_FIFO_DEF(_usbh_pending_ctrl_q, CFG_TUH_CONTROL_PENDING_QUEUE_SZ * sizeof(usbh_pending_ctrl_t), false); + +typedef struct { uint8_t enumerating_daddr; // device address of the device being enumerated uint8_t attach_debouncing_bm; // bitmask for roothub port attach debouncing tuh_bus_info_t dev0_bus; // bus info for dev0 in enumeration usbh_ctrl_xfer_info_t ctrl_xfer_info; // control transfer usbh_call_after_t call_after; + // Per-daddr generation counter — bumped on usbh_device_close() to identify stale pending control transfer + uint8_t daddr_gen[TOTAL_DEVICES + 1]; +#if CFG_TUSB_OS_HAS_SCHEDULER + osal_task_handle_t task_hdl; // host task handle, lazy-captured on first tuh_task_ext() +#endif } usbh_data_t; -static usbh_data_t _usbh_data = { - .controller_id = TUSB_INDEX_INVALID_8, -}; +static uint8_t _usbh_controller_id = TUSB_INDEX_INVALID_8; +static usbh_data_t _usbh_data; typedef struct { TUH_EPBUF_TYPE_DEF(tusb_control_request_t, request); @@ -346,8 +365,11 @@ static void enum_new_device(hcd_event_t* event); static void enum_delay_async(uintptr_t state); static void process_remove_event(hcd_event_t *event); static void remove_device_tree(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port); + static bool usbh_edpt_control_open(uint8_t dev_addr, uint8_t max_packet_size); static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); +static void control_xfer_dispatch_pending(void); +static void control_xfer_complete(uint8_t daddr, xfer_result_t result); TU_ATTR_ALWAYS_INLINE static inline usbh_device_t* get_device(uint8_t dev_addr) { TU_VERIFY(dev_addr > 0 && dev_addr <= TOTAL_DEVICES, NULL); @@ -364,7 +386,7 @@ TU_ATTR_ALWAYS_INLINE static inline bool queue_event(hcd_event_t const * event, return true; } -TU_ATTR_ALWAYS_INLINE static inline void _control_set_xfer_stage(uint8_t stage) { +TU_ATTR_ALWAYS_INLINE static inline void control_xfer_set_stage(uint8_t stage) { if (_usbh_data.ctrl_xfer_info.stage != stage) { (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); _usbh_data.ctrl_xfer_info.stage = stage; @@ -372,15 +394,6 @@ TU_ATTR_ALWAYS_INLINE static inline void _control_set_xfer_stage(uint8_t stage) } } -TU_ATTR_ALWAYS_INLINE static inline bool usbh_setup_send(uint8_t daddr, const uint8_t setup_packet[8]) { - const uint8_t rhport = usbh_get_rhport(daddr); - const bool ret = hcd_setup_send(rhport, daddr, setup_packet); - if (!ret) { - _control_set_xfer_stage(CONTROL_STAGE_IDLE); - } - return ret; -} - bool usbh_defer_func_ms_async(uint32_t ms, tusb_defer_func_t func, uintptr_t param) { TU_ASSERT(_usbh_data.call_after.func == NULL); TU_LOG_USBH("USBH schedule function after %u ms\r\n", (unsigned int)ms); @@ -394,9 +407,16 @@ bool usbh_defer_func_ms_async(uint32_t ms, tusb_defer_func_t func, uintptr_t par TU_ATTR_ALWAYS_INLINE static inline void usbh_device_close(uint8_t rhport, uint8_t daddr) { hcd_device_close(rhport, daddr); - // abort any ongoing control transfer - if (daddr == _usbh_data.ctrl_xfer_info.daddr) { - _control_set_xfer_stage(CONTROL_STAGE_IDLE); + // Bump the generation under the mutex so a concurrent producer in + // tuh_control_xfer stamps a value that is strictly monotonic w.r.t. close. + (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); + _usbh_data.daddr_gen[daddr]++; + (void) osal_mutex_unlock(_usbh_mutex); + + // If this device has in-flight control xfer, complete as FAILED + usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; + if (daddr == ctrl_info->daddr && ctrl_info->stage != CONTROL_STAGE_IDLE) { + control_xfer_complete(daddr, XFER_RESULT_FAILED); } // invalidate if enumerating @@ -458,7 +478,7 @@ tusb_speed_t tuh_speed_get(uint8_t daddr) { } bool tuh_rhport_is_active(uint8_t rhport) { - return _usbh_data.controller_id == rhport; + return _usbh_controller_id == rhport; } bool tuh_rhport_reset_bus(uint8_t rhport, bool active) { @@ -485,7 +505,7 @@ static void clear_device(usbh_device_t* dev) { } bool tuh_inited(void) { - return _usbh_data.controller_id != TUSB_INDEX_INVALID_8; + return _usbh_controller_id != TUSB_INDEX_INVALID_8; } bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { @@ -547,7 +567,7 @@ bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { tu_memclr(_usbh_devices, sizeof(_usbh_devices)); tu_memclr(&_usbh_data, sizeof(_usbh_data)); - _usbh_data.controller_id = TUSB_INDEX_INVALID_8; + _usbh_controller_id = TUSB_INDEX_INVALID_8; _usbh_data.enumerating_daddr = TUSB_INDEX_INVALID_8; for (uint8_t i = 0; i < TOTAL_DEVICES; i++) { @@ -565,7 +585,7 @@ bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { } // Init host controller - _usbh_data.controller_id = rhport; + _usbh_controller_id = rhport; TU_ASSERT(hcd_init(rhport, rh_init)); hcd_int_enable(rhport); @@ -580,7 +600,7 @@ bool tuh_deinit(uint8_t rhport) { // deinit host controller hcd_int_disable(rhport); TU_ASSERT(hcd_deinit(rhport)); - _usbh_data.controller_id = TUSB_INDEX_INVALID_8; + _usbh_controller_id = TUSB_INDEX_INVALID_8; // remove all devices on this rhport (hub_addr = 0, hub_port = 0) remove_device_tree(rhport, 0, 0); @@ -604,6 +624,25 @@ bool tuh_deinit(uint8_t rhport) { _usbh_daq = NULL; #endif + // Fire FAILED cb for any queued async control xfer so callers aren't stranded. + usbh_pending_ctrl_t pending; + while (tu_fifo_read_n(&_usbh_pending_ctrl_q, &pending, sizeof(pending)) == sizeof(pending)) { + if (pending.complete_cb) { + tuh_xfer_t x = { + .daddr = pending.daddr, + .ep_addr = 0, + .result = XFER_RESULT_FAILED, + .actual_len = 0, + .setup = &pending.setup, + .buffer = pending.buffer, + .complete_cb = pending.complete_cb, + .user_data = pending.user_data, + }; + pending.complete_cb(&x); + } + } + tu_fifo_clear(&_usbh_pending_ctrl_q); + #if OSAL_MUTEX_REQUIRED // TODO make sure there is no task waiting on this mutex osal_mutex_delete(_usbh_mutex); @@ -629,6 +668,12 @@ bool tuh_task_event_ready(void) { } #endif + // Pending control xfer waiting for an idle slot + if (_usbh_data.ctrl_xfer_info.stage == CONTROL_STAGE_IDLE && + !tu_fifo_empty(&_usbh_pending_ctrl_q)) { + return true; + } + if (_usbh_data.call_after.func) { int32_t remain_ms = (int32_t)(_usbh_data.call_after.at_ms - tusb_time_millis_api()); if (remain_ms <= 0) { @@ -663,6 +708,13 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { (void) in_isr; // not implemented yet +#if CFG_TUSB_OS_HAS_SCHEDULER + // Save task handle on 1st run + if (_usbh_data.task_hdl == NULL) { + _usbh_data.task_hdl = osal_task_get_current_handle(); + } +#endif + // Loop until there are no more events in the queue or CFG_TUH_TASK_EVENTS_PER_RUN is reached for (unsigned epr = 0;; epr++) { #if CFG_TUH_TASK_EVENTS_PER_RUN > 0 @@ -695,6 +747,16 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { } } + // Drain pending async control xfers. Slot transitions and dispatch are + // decoupled: completion / abort / device_close set stage = IDLE via + // control_xfer_set_stage() and the actual FIFO drain happens here in the + // event loop. The check is a fast non-mutex sanity gate; the dispatcher + // itself re-checks under the mutex. + if (_usbh_data.ctrl_xfer_info.stage == CONTROL_STAGE_IDLE && + !tu_fifo_empty(&_usbh_pending_ctrl_q)) { + control_xfer_dispatch_pending(); + } + hcd_event_t event; #if CFG_TUH_HUB @@ -818,73 +880,179 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { // Control transfer //--------------------------------------------------------------------+ -static void _control_blocking_complete_cb(tuh_xfer_t* xfer) { - // update result - *((xfer_result_t*) xfer->user_data) = xfer->result; +// Carries both fields the sync waiter cares about — capturing from xfer_temp +// (snapshot taken before release_slot resets ctrl_info for the next pending +// entry) so the waiter sees this xfer's data, not the next dispatched one's. +typedef struct { + volatile xfer_result_t result; + volatile uint32_t actual_len; +} control_xfer_sync_param_t; + +static void control_xfer_sync_complete(tuh_xfer_t* xfer) { + control_xfer_sync_param_t* s = (control_xfer_sync_param_t*) xfer->user_data; + s->actual_len = xfer->actual_len; + s->result = xfer->result; } // TODO timeout_ms is not supported yet bool tuh_control_xfer (tuh_xfer_t* xfer) { - TU_VERIFY(xfer->ep_addr == 0 && xfer->setup); // EP0 with setup packet const uint8_t daddr = xfer->daddr; - TU_VERIFY(tuh_connected(daddr)); - + TU_VERIFY(daddr <= TOTAL_DEVICES && xfer->ep_addr == 0 && xfer->setup); // EP0 with setup packet usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; - TU_VERIFY(ctrl_info->stage == CONTROL_STAGE_IDLE); // pre-check to help reducing mutex lock - (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); - bool const is_idle = (ctrl_info->stage == CONTROL_STAGE_IDLE); - if (is_idle) { - ctrl_info->stage = CONTROL_STAGE_SETUP; - ctrl_info->daddr = daddr; - ctrl_info->actual_len = 0; - ctrl_info->failed_count = 0; - - ctrl_info->buffer = xfer->buffer; - ctrl_info->complete_cb = xfer->complete_cb; - ctrl_info->user_data = xfer->user_data; - _usbh_epbuf.request = (*xfer->setup); - } - (void) osal_mutex_unlock(_usbh_mutex); +#if CFG_TUSB_OS_HAS_SCHEDULER + // Sync (complete_cb == NULL) from a host-stack callback is forbidden on + // RTOS targets — the event-loop driver can't block on its own pending xfer + // (deadlock if other control xfers are queued behind). Use async with a + // chained cb instead. OS_NONE / OS_PICO are exempt: they have a single + // execution context and the recursive-drive path is the only way to wait. + TU_ASSERT(!(xfer->complete_cb == NULL && + osal_task_get_current_handle() == _usbh_data.task_hdl)); +#endif - TU_VERIFY(is_idle); + // Slot is single-threaded — when busy, sync callers block until it frees + // (blocking semantics require the result); async callers get queued in the + // pending FIFO and submitted by control_xfer_complete() when the slot + // drains. The test-and-{claim|enqueue} is one critical section so a slot + // that becomes IDLE between the check and the enqueue can't strand an async + // request in a queue nothing else drains. + const bool is_nonblocking = (xfer->complete_cb != NULL); + while (true) { + TU_VERIFY(tuh_connected(daddr)); + bool claimed = false; + bool is_queued = false; + (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); + if (ctrl_info->stage == CONTROL_STAGE_IDLE) { + ctrl_info->stage = CONTROL_STAGE_SETUP; + ctrl_info->daddr = daddr; + ctrl_info->actual_len = 0; + ctrl_info->failed_count = 0; + + ctrl_info->buffer = xfer->buffer; + ctrl_info->complete_cb = xfer->complete_cb; + ctrl_info->user_data = xfer->user_data; + _usbh_epbuf.request = (*xfer->setup); + claimed = true; + } else if (is_nonblocking) { + // Async + busy: queue the transfer. + const usbh_pending_ctrl_t entry = { + .setup = *xfer->setup, + .buffer = xfer->buffer, + .complete_cb = xfer->complete_cb, + .user_data = xfer->user_data, + .daddr = daddr, + .daddr_gen = _usbh_data.daddr_gen[daddr] + }; + is_queued = tu_fifo_write_n(&_usbh_pending_ctrl_q, &entry, sizeof(entry)) == sizeof(entry); + } + + (void) osal_mutex_unlock(_usbh_mutex); + + if (claimed) { + break; + } + + if (is_nonblocking) { + return is_queued; + } + + // - OS_HAS_SCHEDULER: delay 1 ms + // - Otherwise: single execution context; drive the loop ourselves to progress the in-flight transfer. +#if CFG_TUSB_OS_HAS_SCHEDULER + osal_task_delay(1); +#else + tuh_task_ext(0, false); +#endif + } TU_LOG_USBH("[%u:%u] %s: ", usbh_get_rhport(daddr), daddr, (xfer->setup->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && xfer->setup->bRequest <= TUSB_REQ_SYNCH_FRAME) ? tu_str_std_request[xfer->setup->bRequest] : "Class Request"); TU_LOG_BUF_USBH(xfer->setup, 8); - if (xfer->complete_cb != NULL) { - TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) &_usbh_epbuf.request)); - }else { - // blocking if complete callback is not provided - // change callback to internal blocking, and result as user argument - volatile xfer_result_t result = XFER_RESULT_INVALID; - - // use user_data to point to xfer_result_t - ctrl_info->user_data = (uintptr_t) &result; - ctrl_info->complete_cb = _control_blocking_complete_cb; + // Sync: wire control_xfer_sync_complete BEFORE submit so a fast completion + // event has the cb in place. control_xfer_complete() captures both result + // and actual_len through this cb before release_slot overwrites ctrl_info. + volatile control_xfer_sync_param_t sync_state; + if (!is_nonblocking) { + sync_state.result = XFER_RESULT_INVALID; + sync_state.actual_len = 0; + ctrl_info->user_data = (uintptr_t) &sync_state; + ctrl_info->complete_cb = control_xfer_sync_complete; + } - TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) &_usbh_epbuf.request)); + if (!hcd_setup_send(usbh_get_rhport(daddr), daddr, (uint8_t const *) &_usbh_epbuf.request)) { + control_xfer_set_stage(CONTROL_STAGE_IDLE); + return false; + } - while (result == XFER_RESULT_INVALID) { - // Note: this can be called within an callback ie. part of tuh_task() - // therefore even with RTOS tuh_task_ext() still need to be invoked + if (!is_nonblocking) { + // No tuh_connected() escape needed: usbh_device_close() routes through + // control_xfer_complete(daddr, FAILED) on disconnect, which fires + // sync_complete and unblocks this poll. + while (sync_state.result == XFER_RESULT_INVALID) { +#if CFG_TUSB_OS_HAS_SCHEDULER + osal_task_delay(1); +#else tuh_task_ext(0, false); - // TODO probably some timeout to prevent hanged +#endif } - // update transfer result, user_data is expected to point to xfer_result_t + // Forward to caller (xfer->user_data, if set, is a xfer_result_t pointer). if (xfer->user_data != 0) { - *((xfer_result_t*) xfer->user_data) = result; + *((xfer_result_t*) xfer->user_data) = sync_state.result; } - xfer->result = result; - xfer->actual_len = ctrl_info->actual_len; + xfer->result = sync_state.result; + xfer->actual_len = sync_state.actual_len; } return true; } -static void _control_xfer_complete(uint8_t daddr, xfer_result_t result) { +// Start control transfer from pending fifo +static void control_xfer_dispatch_pending(void) { + usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; + + while (true) { + usbh_pending_ctrl_t xfer; + bool has_xfer = false; + + (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); + if (ctrl_info->stage == CONTROL_STAGE_IDLE && + tu_fifo_read_n(&_usbh_pending_ctrl_q, &xfer, sizeof(xfer)) == sizeof(xfer)) { + ctrl_info->stage = CONTROL_STAGE_SETUP; + ctrl_info->daddr = xfer.daddr; + ctrl_info->actual_len = 0; + ctrl_info->failed_count = 0; + ctrl_info->buffer = xfer.buffer; + ctrl_info->complete_cb = xfer.complete_cb; + ctrl_info->user_data = xfer.user_data; + _usbh_epbuf.request = xfer.setup; + has_xfer = true; + } + (void) osal_mutex_unlock(_usbh_mutex); + + if (!has_xfer) { + return; // nothing to do + } + + // mismatched daddr_gen means pending transfer is stale due to the device got disconnected while in the FIFO + // Note: the address can be re-allocated to another device at this point. + if (xfer.daddr_gen == _usbh_data.daddr_gen[xfer.daddr]) { + TU_LOG_USBH("[%u:%u] %s: ", usbh_get_rhport(xfer.daddr), xfer.daddr, + (xfer.setup.bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && xfer.setup.bRequest <= TUSB_REQ_SYNCH_FRAME) ? + tu_str_std_request[xfer.setup.bRequest] : "Class Request"); + TU_LOG_BUF_USBH(&xfer.setup, 8); + if (hcd_setup_send(usbh_get_rhport(xfer.daddr), xfer.daddr, (uint8_t const *) &_usbh_epbuf.request)) { + return; // transfer kicked-off, we are done + } + } + + // complete callback as FAILED and continue with next pending xfer + control_xfer_complete(xfer.daddr, XFER_RESULT_FAILED); + } +} + +static void control_xfer_complete(uint8_t daddr, xfer_result_t result) { TU_LOG_USBH("\r\n"); usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; @@ -901,7 +1069,8 @@ static void _control_xfer_complete(uint8_t daddr, xfer_result_t result) { .user_data = ctrl_info->user_data }; - _control_set_xfer_stage(CONTROL_STAGE_IDLE); + // set to IDLE before callback since cb can invoke another transfer + control_xfer_set_stage(CONTROL_STAGE_IDLE); if (xfer_temp.complete_cb != NULL) { xfer_temp.complete_cb(&xfer_temp); @@ -915,11 +1084,17 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t tusb_control_request_t const * request = &_usbh_epbuf.request; usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; + // Drop stale completions: slot already released (abort/close fired its cb) + // or now owns a different device's xfer (a pending entry was dispatched). + if (ctrl_info->stage == CONTROL_STAGE_IDLE || ctrl_info->daddr != daddr) { + return true; + } + switch (result) { case XFER_RESULT_STALLED: TU_LOG_USBH("[%u:%u] Control STALLED, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, xferred_bytes); TU_LOG_BUF_USBH(request, 8); - _control_xfer_complete(daddr, result); + control_xfer_complete(daddr, result); break; case XFER_RESULT_FAILED: @@ -931,11 +1106,14 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t ctrl_info->actual_len = 0; // reset actual_len (void) osal_mutex_unlock(_usbh_mutex); - TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) request)); + if (!hcd_setup_send(rhport, daddr, (uint8_t const *) request)) { + control_xfer_complete(daddr, XFER_RESULT_FAILED); + return false; + } } else { TU_LOG_USBH("[%u:%u] Control FAILED, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, xferred_bytes); TU_LOG_BUF_USBH(request, 8); - _control_xfer_complete(daddr, result); + control_xfer_complete(daddr, result); } break; @@ -944,7 +1122,7 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t case CONTROL_STAGE_SETUP: if (request->wLength > 0) { // DATA stage: initial data toggle is always 1 - _control_set_xfer_stage(CONTROL_STAGE_DATA); + control_xfer_set_stage(CONTROL_STAGE_DATA); const uint8_t ep_data = tu_edpt_addr(0, request->bmRequestType_bit.direction); TU_ASSERT(hcd_edpt_xfer(rhport, daddr, ep_data, ctrl_info->buffer, request->wLength)); return true; @@ -959,7 +1137,7 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t ctrl_info->actual_len = (uint16_t) xferred_bytes; // ACK stage: toggle is always 1 - _control_set_xfer_stage(CONTROL_STAGE_ACK); + control_xfer_set_stage(CONTROL_STAGE_ACK); const uint8_t ep_status = tu_edpt_addr(0, 1 - request->bmRequestType_bit.direction); TU_ASSERT(hcd_edpt_xfer(rhport, daddr, ep_status, NULL, 0)); break; @@ -976,7 +1154,7 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t } } - _control_xfer_complete(daddr, result); + control_xfer_complete(daddr, result); break; } @@ -1023,7 +1201,7 @@ bool tuh_edpt_abort_xfer(uint8_t daddr, uint8_t ep_addr) { const usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; TU_VERIFY(daddr == ctrl_info->daddr && ctrl_info->stage != CONTROL_STAGE_IDLE); hcd_edpt_abort_xfer(rhport, daddr, ep_addr); - _control_set_xfer_stage(CONTROL_STAGE_IDLE); // reset control transfer state to idle + control_xfer_complete(daddr, XFER_RESULT_ABORTED); } else { usbh_device_t* dev = get_device(daddr); TU_VERIFY(dev); @@ -1055,9 +1233,9 @@ uint8_t *usbh_get_enum_buf(void) { void usbh_int_set(bool enabled) { // TODO all host controller if multiple are used since they shared the same event queue if (enabled) { - hcd_int_enable(_usbh_data.controller_id); + hcd_int_enable(_usbh_controller_id); } else { - hcd_int_disable(_usbh_data.controller_id); + hcd_int_disable(_usbh_controller_id); } } diff --git a/src/osal/osal_freertos.h b/src/osal/osal_freertos.h index 9b12b5c0e..2f36aa9e8 100644 --- a/src/osal/osal_freertos.h +++ b/src/osal/osal_freertos.h @@ -85,7 +85,13 @@ typedef struct { //--------------------------------------------------------------------+ typedef TaskHandle_t osal_task_handle_t; -// Requires INCLUDE_xTaskGetCurrentTaskHandle == 1 in FreeRTOSConfig.h. +// Requires INCLUDE_xTaskGetCurrentTaskHandle == 1 in FreeRTOSConfig.h. FreeRTOS +// also exposes the symbol when configUSE_MUTEXES == 1, so accept either. +#if !defined(INCLUDE_xTaskGetCurrentTaskHandle) || (INCLUDE_xTaskGetCurrentTaskHandle == 0) + #if !defined(configUSE_MUTEXES) || (configUSE_MUTEXES == 0) + #error "TinyUSB host stack requires INCLUDE_xTaskGetCurrentTaskHandle or configUSE_MUTEXES to be enabled in FreeRTOSConfig.h" + #endif +#endif TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) { return xTaskGetCurrentTaskHandle(); } -- cgit v1.3.1 From 84e3347badc7f9f5146b5f5eb129900f2fc59389 Mon Sep 17 00:00:00 2001 From: Wojciech Klimek Date: Thu, 28 May 2026 21:27:11 +0200 Subject: Handle OUT transfer completion in MTP Handle OUT transfer differently from IN to not prematurely change MTP phase when host sends short packet that is not end of MTP data phase. Only reaching container length or ZLP should change phase. --- src/class/mtp/mtp_device.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/class/mtp/mtp_device.c b/src/class/mtp/mtp_device.c index 0da984f4a..fd06b4601 100644 --- a/src/class/mtp/mtp_device.c +++ b/src/class/mtp/mtp_device.c @@ -441,9 +441,19 @@ bool mtpd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t threshold = CFG_TUD_MTP_EP_BUFSIZE; } - // Check completion: ZLP, short packet, or total length reached - const bool is_complete = - (xferred_bytes == 0 || xferred_bytes < threshold || p_mtp->xferred_len >= p_mtp->total_len); + // Check completion for IN and OUT separately + bool is_complete; + + if (is_data_in) + { + // IN completion: short packet, ZLP, or reaching total_len + is_complete = (xferred_bytes == 0 || xferred_bytes < threshold || p_mtp->xferred_len >= p_mtp->total_len); + } + else + { + // OUT completion: reaching total_len or ZLP + is_complete = (p_mtp->xferred_len >= p_mtp->total_len) || ((xferred_bytes == 0 && p_mtp->xferred_len > 0)); + } TU_LOG_DRV(" MTP Data %s CB: xferred_bytes=%lu, xferred_len/total_len=%lu/%lu, is_complete=%d\r\n", is_data_in ? "IN" : "OUT", xferred_bytes, p_mtp->xferred_len, p_mtp->total_len, is_complete ? 1 : 0); -- cgit v1.3.1 From b4e7c25c1b57a69e4c04e41d0f2203abf0d8d358 Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Fri, 29 May 2026 11:42:47 +0200 Subject: dwc2: process IN EP before OUT To avoid STATUS IN completion of previous control transfer treated as next DATA IN when IRQ latency is high. Signed-off-by: HiFiPhile --- src/portable/synopsys/dwc2/dcd_dwc2.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 233840e8b..c90429a15 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -1213,6 +1213,12 @@ void dcd_int_handler(uint8_t rhport) { dcd_event_sof(rhport, frame, true); } + // IN endpoint interrupt handling. + if (gintsts & GINTSTS_IEPINT) { + // IEPINT bit read-only, clear using DIEPINTn + handle_ep_irq(rhport, TUSB_DIR_IN); + } + #if CFG_TUD_DWC2_SLAVE_ENABLE // RxFIFO non-empty interrupt handling. if (gintsts & GINTSTS_RXFLVL) { @@ -1235,12 +1241,6 @@ void dcd_int_handler(uint8_t rhport) { } #endif - // IN endpoint interrupt handling. - if (gintsts & GINTSTS_IEPINT) { - // IEPINT bit read-only, clear using DIEPINTn - handle_ep_irq(rhport, TUSB_DIR_IN); - } - // Incomplete isochronous IN transfer interrupt handling. if (gintsts & GINTSTS_IISOIXFR) { dwc2->gintsts = GINTSTS_IISOIXFR; -- cgit v1.3.1 From 7e0fcaa41ee9330274808d88e5211bdbe37511a4 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 1 Jun 2026 10:05:17 +0700 Subject: ultrareview nits: keep xfer_result table in sync, hoist blinky loop - src/tusb.c: extend tu_str_xfer_result[] with "ABORTED" and "INVALID" to match the new enum size. Not reachable today (no HCD posts those values through hcd_event_xfer_complete), but keeps the enum/table invariant intact so future HCDs that surface ABORTED don't index OOB. - examples/dual/dynamic_switch/src/main.c: apply the same while(1) hoist already done for cdc_task / print_devinfo_task to led_blinking_task. On OS_NONE the loop returned mid-iteration, which on first call could fire multiple back-to-back toggles while start_ms (initially 0) caught up to uptime. Co-Authored-By: Claude Opus 4.7 --- examples/dual/dynamic_switch/src/main.c | 17 ++++++++++------- src/tusb.c | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/examples/dual/dynamic_switch/src/main.c b/examples/dual/dynamic_switch/src/main.c index ac5126e56..f67cd885c 100644 --- a/examples/dual/dynamic_switch/src/main.c +++ b/examples/dual/dynamic_switch/src/main.c @@ -483,16 +483,19 @@ void led_blinking_task(void *param) { (void) param; static uint32_t start_ms = 0; static bool led_state = false; - while (1) { #if CFG_TUSB_OS == OPT_OS_FREERTOS + while (1) { vTaskDelay(pdMS_TO_TICKS(blink_interval_ms)); -#else - if (tusb_time_millis_api() - start_ms < blink_interval_ms) { - return; // not enough time - } -#endif start_ms += blink_interval_ms; board_led_write(led_state); - led_state = 1 - led_state; // toggle + led_state = 1 - led_state; + } +#else + if (tusb_time_millis_api() - start_ms < blink_interval_ms) { + return; // not enough time } + start_ms += blink_interval_ms; + board_led_write(led_state); + led_state = 1 - led_state; +#endif } diff --git a/src/tusb.c b/src/tusb.c index 5d656fb8c..634cbc10b 100644 --- a/src/tusb.c +++ b/src/tusb.c @@ -497,7 +497,7 @@ char const* const tu_str_std_request[] = { }; char const* const tu_str_xfer_result[] = { - "OK", "FAILED", "STALLED", "TIMEOUT" + "OK", "FAILED", "STALLED", "TIMEOUT", "ABORTED", "INVALID" }; #endif -- cgit v1.3.1 From 17185428df755d7229407e6ac87c124e522877dc Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 1 Jun 2026 10:58:36 +0700 Subject: CFG_TUH_CONTROL_PENDING_QUEUE_SZ defefault to 4 if hub is eanbled, 2 if not --- src/host/usbh.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/host/usbh.c b/src/host/usbh.c index 05e03245f..9d159985e 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -41,7 +41,11 @@ #endif #ifndef CFG_TUH_CONTROL_PENDING_QUEUE_SZ - #define CFG_TUH_CONTROL_PENDING_QUEUE_SZ 4 + #if CFG_TUH_HUB + #define CFG_TUH_CONTROL_PENDING_QUEUE_SZ 4 + #else + #define CFG_TUH_CONTROL_PENDING_QUEUE_SZ 2 + #endif #endif #ifndef CFG_TUH_INTERFACE_MAX -- cgit v1.3.1 From cc979da5163d0d407e27d90411a6d4b1a0092779 Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Tue, 2 Jun 2026 22:38:57 +0200 Subject: dcd/dwc2: fix back-to-back SETUP reception in DMA mode Signed-off-by: HiFiPhile --- src/portable/synopsys/dwc2/dcd_dwc2.c | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index c90429a15..e6d7dc08e 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -73,9 +73,8 @@ typedef struct { static dcd_data_t _dcd_data; -CFG_TUD_MEM_SECTION static union { - TUD_EPBUF_DEF(setup_buffer, 8); - tusb_control_request_t setup_packet; +CFG_TUD_MEM_SECTION static struct { + TUD_EPBUF_DEF(setup_buffer, 24); } _dcd_usbbuf; static tud_configure_dwc2_t _tud_cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; @@ -137,8 +136,8 @@ static void dma_setup_prepare(uint8_t rhport) { } } - // Receive only 1 packet - dwc2->epout[0].doeptsiz = (1 << DOEPTSIZ_STUPCNT_Pos) | (1 << DOEPTSIZ_PKTCNT_Pos) | (8 << DOEPTSIZ_XFRSIZ_Pos); + // Receive back-to-back setup packets + dwc2->epout[0].doeptsiz = (3 << DOEPTSIZ_STUPCNT_Pos); dwc2->epout[0].doepdma = (uintptr_t) _dcd_usbbuf.setup_buffer; dwc2->epout[0].doepctl |= DOEPCTL_EPENA | DOEPCTL_USBAEP; } @@ -1003,15 +1002,19 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi if (doepint_bm.setup_phase_done) { // Cleanup previous pending EP0 IN transfer if any - dwc2_dep_t* epin0 = &DWC2_REG(rhport)->epin[0]; + dwc2_dep_t* epin0 = &dwc2->epin[0]; + dwc2_dep_t* epout0 = &dwc2->epout[0]; if (edpt_is_enabled(epin0)) { edpt_disable(rhport, 0x80, false); } - dcd_dcache_invalidate(_dcd_usbbuf.setup_buffer, 8); - dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); + + dcd_dcache_invalidate(_dcd_usbbuf.setup_buffer, sizeof(_dcd_usbbuf.setup_buffer)); + + tusb_control_request_t *setup_packet = (tusb_control_request_t *) (epout0->doepdma - 8); + dcd_event_setup_received(rhport, (uint8_t*)setup_packet, true); // Prepare EP0 for next setup if this setup has no data stage - if (_dcd_usbbuf.setup_packet.wLength == 0) { + if (setup_packet->wLength == 0) { dma_setup_prepare(rhport); } return; -- cgit v1.3.1 From 73af6494cd5defc296b91da80e2f59b8af4efa70 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 3 Jun 2026 21:44:19 +0700 Subject: dwc2: submit setup packet on SETUP_DONE and drop spurious EP0 RX_COMPLETE on core v3.10a (STM32L476) DWC2 core rev 3.10a pushes an extra EP0 RX_COMPLETE (RXFLVL PKTSTS 0x3) that is not a real OUT data completion, in two cases flagged on DOEPINT: - STPKTRX (Setup Packet Received): between SETUP_RX and SETUP_DONE - STSPHSRX (Status Phase Received, control write): after the OUT data stage when the host starts the IN status phase --- src/portable/synopsys/dwc2/dcd_dwc2.c | 64 +++++++++++++++++++++++------------ 1 file changed, 42 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index c90429a15..447e64479 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -794,15 +794,15 @@ static void handle_bus_reset(uint8_t rhport) { xfer_status[0][TUSB_DIR_OUT].max_size = CFG_TUD_ENDPOINT0_SIZE; xfer_status[0][TUSB_DIR_IN].max_size = CFG_TUD_ENDPOINT0_SIZE; - uint32_t oepmsk = 0; + uint32_t gintmsk = GINTMSK_OTGINT | GINTMSK_IEPINT | GINTMSK_IISOIXFRM; if(dma_device_enabled(dwc2)) { - oepmsk = GINTMSK_OEPINT; + gintmsk |= GINTMSK_OEPINT; dma_setup_prepare(rhport); } else { dwc2->epout[0].doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); } - dwc2->gintmsk |= GINTMSK_OTGINT | oepmsk | GINTMSK_IEPINT | GINTMSK_IISOIXFRM; + dwc2->gintmsk |= gintmsk; } static void handle_enum_done(uint8_t rhport) { @@ -886,45 +886,50 @@ static void handle_rxflvl_irq(uint8_t rhport) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); const volatile uint32_t* rx_fifo = dwc2->fifo[0]; + // DWC2 v3.10a (e.g. STM32L476) emits an extra EP0 RX_COMPLETE that is NOT a real OUT data transfer completion, in two + // situations - each flagged by a DOEPINT bit set on that word: + // - DOEPINT.STPKTRX (Setup Packet Received): pushed between SETUP_RX and SETUP_DONE of every control transfer. + // - DOEPINT.STSPHSRX (Status Phase Received for control write): pushed after the OUT data stage when the host + // starts the IN status phase. + // Both are dropped in the RX_COMPLETE case below, clearing the flag (W1C) so a latched STSPHSRX + // does not block the core from emitting the next SETUP_DONE. usbd still processes the real OUT data + // and queues the IN status ZLP itself - the core does not auto-complete the control-write status. + const bool quirk_v310a = (dwc2->gsnpsid == DWC2_CORE_REV_3_10a); + // Pop control word off FIFO const dwc2_grxstsp_t grxstsp = {.value = dwc2->grxstsp}; + const uint8_t packet_status = grxstsp.packet_status; const uint8_t epnum = grxstsp.ep_ch_num; dwc2_dep_t* epout = &dwc2->epout[epnum]; - switch (grxstsp.packet_status) { + TU_LOG1("packet_status = %u, ep %u, doepint = 0x%04lX\r\n", packet_status, epnum, epout->doepint); + + switch (packet_status) { case GRXSTS_PKTSTS_GLOBAL_OUT_NAK: // Global OUT NAK: do nothing break; case GRXSTS_PKTSTS_SETUP_RX: { // Setup packet received - uint32_t* setup = (uint32_t*)(uintptr_t) _dcd_usbbuf.setup_buffer; + uint32_t * setup = (uint32_t*)(uintptr_t) _dcd_usbbuf.setup_buffer; // We can receive up to three setup packets in succession, but only the last one is valid. setup[0] = (*rx_fifo); setup[1] = (*rx_fifo); - - dwc2_dep_t* epin0 = &dwc2->epin[0]; - if (edpt_is_enabled(epin0)) { - edpt_disable(rhport, 0x80, false); - } - - // (GenID < 3.00a) Must wait SETUP_DONE before next OUT transfer, otherwise OUT data may be corrupted. - // (GenID >= 3.00a) On the other hand STUPCNT is auto reloaded and SETUP_DONE is only triggered once after bus reset. - if (dwc2->gsnpsid >= DWC2_CORE_REV_3_00a) { - dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); - } break; } - case GRXSTS_PKTSTS_SETUP_DONE: - // Setup packet done: + case GRXSTS_PKTSTS_SETUP_DONE: { + // Pop this word cause Setup interrupt + // TU_LOG1("\r\n"); epout->doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); - - if (dwc2->gsnpsid < DWC2_CORE_REV_3_00a) { - dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); + epout->doepint = DOEPINT_SETUP | DOEPINT_STPKTRX; // Clear SETUP interrupt, required for core to re-write this control word + if (edpt_is_enabled(&dwc2->epin[0])) { + edpt_disable(rhport, 0x80, false); } + dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true); break; + } case GRXSTS_PKTSTS_RX_DATA: { // Out packet received @@ -953,7 +958,20 @@ static void handle_rxflvl_irq(uint8_t rhport) { } case GRXSTS_PKTSTS_RX_COMPLETE: { - // Out packet done + // Pop this word cause xfer complete interrupt + const uint32_t doepint = epout->doepint; + epout->doepint = DOEPINT_XFRC; + + // v3.10a quirk (see top of function): the extra RX_COMPLETE flagged with Setup Packet Received (STPKTRX) or + // Status Phase Received for control write (STSPHSRX) is not a real OUT completion. Drop it + if (quirk_v310a) { + if (doepint & (DOEPINT_STPKTRX | DOEPINT_STSPHSRX)) { + epout->doepint = DOEPINT_STPKTRX | DOEPINT_STSPHSRX; + break; + } + } + // TU_LOG1("\r\n"); + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); if (epnum == 0 && _dcd_data.ep0_pending[TUSB_DIR_OUT] > 0) { // EP0 can only handle one packet, schedule another packet to be received. @@ -1093,6 +1111,8 @@ static void handle_ep_irq(uint8_t rhport, uint8_t dir) { #if CFG_TUD_DWC2_SLAVE_ENABLE if (dir == TUSB_DIR_IN) { handle_epin_slave(rhport, epnum, intr.diepint_bm); + } else { + // epout is handled in rxflv } #endif } -- cgit v1.3.1 From a6098c38ac3390716a6cf3046a87b13dd85fecca Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 3 Jun 2026 21:46:11 +0700 Subject: refactor(cmake): comment out unused target folder properties --- hw/bsp/family_support.cmake | 36 ++++++++++++------------ hw/bsp/stm32f7/boards/stm32f769disco/board.cmake | 1 + src/class/mtp/mtp_device.c | 11 +++----- 3 files changed, 23 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/hw/bsp/family_support.cmake b/hw/bsp/family_support.cmake index 2468ac43c..07d693d77 100644 --- a/hw/bsp/family_support.cmake +++ b/hw/bsp/family_support.cmake @@ -244,7 +244,7 @@ function(family_add_bloaty TARGET) COMMAND ${BLOATY_EXE} ${OPTION_LIST} $ VERBATIM) - set_property(TARGET ${TARGET}-bloaty PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-bloaty PROPERTY FOLDER ${TARGET}-group) # post build # add_custom_command(TARGET ${TARGET} POST_BUILD # COMMAND ${BLOATY_EXE} --csv ${OPTION_LIST} $ > ${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_bloaty.csv @@ -265,7 +265,7 @@ function(family_add_linkermap TARGET) VERBATIM ) - set_property(TARGET ${TARGET}-linkermap PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-linkermap PROPERTY FOLDER ${TARGET}-group) # post build add_custom_command(TARGET ${TARGET} POST_BUILD @@ -347,7 +347,7 @@ echo \"$MEMBROWSE_CMD\"") COMMAND ${CMAKE_COMMAND} -E env MEMBROWSE_UPLOAD=0 bash -lc "${MEMBROWSE_PREPARE_CMD}; eval \"$MEMBROWSE_CMD\"" VERBATIM ) - set_property(TARGET ${TARGET}-membrowse PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-membrowse PROPERTY FOLDER ${TARGET}-group) add_custom_target(${TARGET}-membrowse-upload COMMAND ${CMAKE_COMMAND} -E env MEMBROWSE_UPLOAD=1 bash -lc "${MEMBROWSE_PREPARE_CMD}; eval \"$MEMBROWSE_CMD\"" @@ -359,7 +359,7 @@ echo \"$MEMBROWSE_CMD\"") endif () add_dependencies(examples-membrowse-upload ${TARGET}-membrowse-upload) - set_property(TARGET ${TARGET}-membrowse-upload PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-membrowse-upload PROPERTY FOLDER ${TARGET}-group) endif () endfunction() @@ -648,7 +648,7 @@ exit" VERBATIM ) - set_property(TARGET ${NAME_TARGET}-jlink PROPERTY FOLDER ${TARGET}-group) +# set_property(TARGET ${NAME_TARGET}-jlink PROPERTY FOLDER ${NAME_TARGET}-group) endfunction() @@ -663,7 +663,7 @@ function(family_flash_stlink TARGET) COMMAND ${STM32_PROGRAMMER_CLI} --connect port=swd --write $ --go ) - set_property(TARGET ${TARGET}-stlink PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-stlink PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -678,7 +678,7 @@ function(family_flash_stflash TARGET) COMMAND ${ST_FLASH} write $/${TARGET}.bin 0x8000000 ) - set_property(TARGET ${TARGET}-stflash PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-stflash PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -706,7 +706,7 @@ function(family_flash_openocd TARGET) VERBATIM ) - set_property(TARGET ${TARGET}-openocd PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-openocd PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -769,7 +769,7 @@ function(family_flash_wlink_rs TARGET) COMMAND ${WLINK_RS} flash $ ) - set_property(TARGET ${TARGET}-wlink-rs PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-wlink-rs PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -784,7 +784,7 @@ function(family_flash_pyocd TARGET) COMMAND ${PYOCD} flash -t ${PYOCD_TARGET} $ ) - set_property(TARGET ${TARGET}-pyocd PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-pyocd PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -794,7 +794,7 @@ function(family_flash_uf2 TARGET FAMILY_ID) DEPENDS ${TARGET} COMMAND python ${UF2CONV_PY} -f ${FAMILY_ID} --deploy $/${TARGET}.uf2 ) - set_property(TARGET ${TARGET}-uf2 PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-uf2 PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -810,7 +810,7 @@ function(family_flash_teensy TARGET) COMMAND ${TEENSY_CLI} --mcu=${TEENSY_MCU} -w -s $/${TARGET}.hex ) - set_property(TARGET ${TARGET}-teensy PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-teensy PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -830,7 +830,7 @@ function(family_flash_nxplink TARGET) COMMAND ${LINKSERVER_PATH} flash ${NXPLINK_DEVICE} load $ ) - set_property(TARGET ${TARGET}-nxplink PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-nxplink PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -845,7 +845,7 @@ function(family_flash_dfu_util TARGET OPTION) VERBATIM ) - set_property(TARGET ${TARGET}-dfu-util PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-dfu-util PROPERTY FOLDER ${TARGET}-group) endfunction() function(family_flash_msp430flasher TARGET) @@ -862,7 +862,7 @@ function(family_flash_msp430flasher TARGET) ${MSP430FLASHER} -w $/${TARGET}.hex -z [VCC] ) - set_property(TARGET ${TARGET}-msp430flasher PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-msp430flasher PROPERTY FOLDER ${TARGET}-group) endfunction() function(family_flash_rfp TARGET) @@ -880,7 +880,7 @@ function(family_flash_rfp TARGET) VERBATIM ) - set_property(TARGET ${TARGET}-rfp PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-rfp PROPERTY FOLDER ${TARGET}-group) endfunction() @@ -897,7 +897,7 @@ function(family_flash_uniflash TARGET) VERBATIM ) - set_property(TARGET ${TARGET}-uniflash PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-uniflash PROPERTY FOLDER ${TARGET}-group) endfunction() # Add flash ft9xx target need to remove kernal's ftdi_sio and bind D2XX drivers @@ -912,7 +912,7 @@ function(family_flash_ft9xx TARGET) COMMAND ${FT9XXPROG} -f $/${TARGET}.bin ) - set_property(TARGET ${TARGET}-ft9xx PROPERTY FOLDER ${TARGET}-group) + #set_property(TARGET ${TARGET}-ft9xx PROPERTY FOLDER ${TARGET}-group) endfunction() #---------------------------------- diff --git a/hw/bsp/stm32f7/boards/stm32f769disco/board.cmake b/hw/bsp/stm32f7/boards/stm32f769disco/board.cmake index 2335b869e..dbdd07e4d 100644 --- a/hw/bsp/stm32f7/boards/stm32f769disco/board.cmake +++ b/hw/bsp/stm32f7/boards/stm32f769disco/board.cmake @@ -1,5 +1,6 @@ set(MCU_VARIANT stm32f769xx) set(JLINK_DEVICE stm32f769ni) +#set(JLINK_OPTION "-USB 000778170924") set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/STM32F769ZITx_FLASH.ld) diff --git a/src/class/mtp/mtp_device.c b/src/class/mtp/mtp_device.c index fd06b4601..1f76dfcc7 100644 --- a/src/class/mtp/mtp_device.c +++ b/src/class/mtp/mtp_device.c @@ -443,15 +443,12 @@ bool mtpd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t // Check completion for IN and OUT separately bool is_complete; - - if (is_data_in) - { + if (is_data_in) { // IN completion: short packet, ZLP, or reaching total_len is_complete = (xferred_bytes == 0 || xferred_bytes < threshold || p_mtp->xferred_len >= p_mtp->total_len); - } - else - { - // OUT completion: reaching total_len or ZLP + } else { + // OUT completion: reaching total_len or ZLP only. A short packet does NOT end the phase + // (an early short packet before total_len is the cancel case, not normal completion). is_complete = (p_mtp->xferred_len >= p_mtp->total_len) || ((xferred_bytes == 0 && p_mtp->xferred_len > 0)); } -- cgit v1.3.1 From 6b89aea9de07f537611ddffca1183a3a958a7ee4 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 3 Jun 2026 23:18:28 +0700 Subject: dwc2: remove investigation debug logging Co-Authored-By: Claude Opus 4.8 (1M context) --- src/portable/synopsys/dwc2/dcd_dwc2.c | 4 ---- 1 file changed, 4 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 447e64479..ac35eb951 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -903,8 +903,6 @@ static void handle_rxflvl_irq(uint8_t rhport) { dwc2_dep_t* epout = &dwc2->epout[epnum]; - TU_LOG1("packet_status = %u, ep %u, doepint = 0x%04lX\r\n", packet_status, epnum, epout->doepint); - switch (packet_status) { case GRXSTS_PKTSTS_GLOBAL_OUT_NAK: // Global OUT NAK: do nothing @@ -921,7 +919,6 @@ static void handle_rxflvl_irq(uint8_t rhport) { case GRXSTS_PKTSTS_SETUP_DONE: { // Pop this word cause Setup interrupt - // TU_LOG1("\r\n"); epout->doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); epout->doepint = DOEPINT_SETUP | DOEPINT_STPKTRX; // Clear SETUP interrupt, required for core to re-write this control word if (edpt_is_enabled(&dwc2->epin[0])) { @@ -970,7 +967,6 @@ static void handle_rxflvl_irq(uint8_t rhport) { break; } } - // TU_LOG1("\r\n"); xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); if (epnum == 0 && _dcd_data.ep0_pending[TUSB_DIR_OUT] > 0) { -- cgit v1.3.1 From 1f6236ae0788e37bb833e4b018faf10fb691bbdd Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 3 Jun 2026 23:41:19 +0700 Subject: dwc2: address Copilot review (comment grammar/typo, tinyusb.json f407 dedup) Co-Authored-By: Claude Opus 4.8 (1M context) --- src/portable/synopsys/dwc2/dcd_dwc2.c | 6 +++--- test/hil/tinyusb.json | 14 -------------- 2 files changed, 3 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index ac35eb951..bab7118dd 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -918,7 +918,7 @@ static void handle_rxflvl_irq(uint8_t rhport) { } case GRXSTS_PKTSTS_SETUP_DONE: { - // Pop this word cause Setup interrupt + // Pop this word causes the Setup interrupt epout->doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); epout->doepint = DOEPINT_SETUP | DOEPINT_STPKTRX; // Clear SETUP interrupt, required for core to re-write this control word if (edpt_is_enabled(&dwc2->epin[0])) { @@ -955,7 +955,7 @@ static void handle_rxflvl_irq(uint8_t rhport) { } case GRXSTS_PKTSTS_RX_COMPLETE: { - // Pop this word cause xfer complete interrupt + // Pop this word causes the xfer complete interrupt const uint32_t doepint = epout->doepint; epout->doepint = DOEPINT_XFRC; @@ -1108,7 +1108,7 @@ static void handle_ep_irq(uint8_t rhport, uint8_t dir) { if (dir == TUSB_DIR_IN) { handle_epin_slave(rhport, epnum, intr.diepint_bm); } else { - // epout is handled in rxflv + // epout is handled in handle_rxflvl_irq } #endif } diff --git a/test/hil/tinyusb.json b/test/hil/tinyusb.json index c0a35ddc2..467b7378a 100644 --- a/test/hil/tinyusb.json +++ b/test/hil/tinyusb.json @@ -477,20 +477,6 @@ "uid": "EBCA8F0670AF", "args": "" } - }, - { - "name": "stm32f407disco", - "uid": "30001A000647313332353735", - "tests": { - "device": true, - "host": false, - "dual": false - }, - "flasher": { - "name": "jlink", - "uid": "000773661813", - "args": "-device stm32f407vg" - } } ] } -- cgit v1.3.1 From b5e080732e67a52afefa6966ca33474c91a53d0c Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 4 Jun 2026 17:55:44 +0700 Subject: Update setup buffer size definition based on DMA configuration --- src/portable/synopsys/dwc2/dcd_dwc2.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index c7899a354..ee52ef1e7 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -73,8 +73,15 @@ typedef struct { static dcd_data_t _dcd_data; +// DMA receives up to 3 back-to-back SETUP packets (3 x 8 bytes), Slave mode only needs 1 packet (8 bytes) +#if CFG_TUD_DWC2_DMA_ENABLE + #define DWC2_SETUP_BUFFER_SIZE 24 +#else + #define DWC2_SETUP_BUFFER_SIZE 8 +#endif + CFG_TUD_MEM_SECTION static struct { - TUD_EPBUF_DEF(setup_buffer, 24); + TUD_EPBUF_DEF(setup_buffer, DWC2_SETUP_BUFFER_SIZE); } _dcd_usbbuf; static tud_configure_dwc2_t _tud_cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; -- cgit v1.3.1 From a900ea93db686cacde5e595dc09fdfeaa334d556 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 4 Jun 2026 20:46:49 +0700 Subject: dwc2: cleanup setup_packet pointer cast (review feedback) Cast DOEPDMA0 through uintptr_t and use sizeof(tusb_control_request_t) instead of the magic constant 8, matching project convention. Add a reference to Programming Guide v4.20a 9.1.2.1 for the DOEPDMAn-8 rule. Addresses Copilot review comment; no functional change. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/portable/synopsys/dwc2/dcd_dwc2.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index ee52ef1e7..e1a2f6cf2 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -1031,7 +1031,9 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi dcd_dcache_invalidate(_dcd_usbbuf.setup_buffer, sizeof(_dcd_usbbuf.setup_buffer)); - tusb_control_request_t *setup_packet = (tusb_control_request_t *) (epout0->doepdma - 8); + // DOEPDMA0 has advanced past the last received SETUP packet; back up one packet to the latest valid one + // (Programming Guide v4.20a section 9.1.2.1: "DOEPDMAn-8 provides the pointer to the last valid SETUP data") + tusb_control_request_t *setup_packet = (tusb_control_request_t *) (uintptr_t) (epout0->doepdma - sizeof(tusb_control_request_t)); dcd_event_setup_received(rhport, (uint8_t*)setup_packet, true); // Prepare EP0 for next setup if this setup has no data stage -- cgit v1.3.1 From 8efcc6fbc4903c1e4b41523510a296a92d4b6a05 Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Sat, 6 Jun 2026 15:27:56 +0200 Subject: host/cdc: use local control buffer --- src/class/cdc/cdc_host.c | 92 +++++++++++++++++++++++------------------------- 1 file changed, 44 insertions(+), 48 deletions(-) (limited to 'src') diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c index 62c313b83..4441222c8 100644 --- a/src/class/cdc/cdc_host.c +++ b/src/class/cdc/cdc_host.c @@ -99,6 +99,7 @@ typedef struct { typedef struct { TUH_EPBUF_DEF(tx, CFG_TUH_CDC_TX_EPSIZE); TUH_EPBUF_DEF(rx, CFG_TUH_CDC_RX_EPSIZE); + TUH_EPBUF_DEF(ctrl, 8); } cdch_epbuf_t; static cdch_interface_t cdch_data[CFG_TUH_CDC]; @@ -1003,15 +1004,16 @@ static bool acm_set_line_coding(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_ .wLength = tu_htole16((uint16_t) sizeof(cdc_line_coding_t)) }; - // use usbh enum buf to hold line coding since user line_coding variable does not live long enough - uint8_t *enum_buf = usbh_get_enum_buf(); - memcpy(enum_buf, &p_cdc->requested_line.coding, sizeof(cdc_line_coding_t)); + // use local ctrl buf to hold line coding since user line_coding variable does not live long enough + uint8_t const idx = get_idx_by_ptr(p_cdc); + uint8_t *ctrl_buf = cdch_epbuf[idx].ctrl; + memcpy(ctrl_buf, &p_cdc->requested_line.coding, sizeof(cdc_line_coding_t)); tuh_xfer_t xfer = { .daddr = p_cdc->daddr, .ep_addr = 0, .setup = &request, - .buffer = enum_buf, + .buffer = ctrl_buf, .complete_cb = complete_cb, .user_data = user_data }; @@ -1491,7 +1493,7 @@ static inline uint32_t ftdi_get_divisor(cdch_interface_t *p_cdc) { //------------- Control Request -------------// static bool cp210x_set_request(cdch_interface_t * p_cdc, uint8_t command, uint16_t value, - uint8_t * buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + uint8_t const * buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { tusb_control_request_t const request = { .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, @@ -1504,19 +1506,20 @@ static bool cp210x_set_request(cdch_interface_t * p_cdc, uint8_t command, uint16 .wLength = tu_htole16(length) }; - // use usbh enum buf since application variable does not live long enough - uint8_t * enum_buf = NULL; + // use local ctrl buf since application variable does not live long enough + uint8_t * ctrl_buf = NULL; if (buffer && length > 0) { - enum_buf = usbh_get_enum_buf(); - tu_memcpy_s(enum_buf, CFG_TUH_ENUMERATION_BUFSIZE, buffer, length); + uint8_t const idx = get_idx_by_ptr(p_cdc); + ctrl_buf = cdch_epbuf[idx].ctrl; + tu_memcpy_s(ctrl_buf, sizeof(cdch_epbuf[idx].ctrl), buffer, length); } tuh_xfer_t xfer = { .daddr = p_cdc->daddr, .ep_addr = 0, .setup = &request, - .buffer = enum_buf, + .buffer = ctrl_buf, .complete_cb = complete_cb, .user_data = user_data }; @@ -1563,7 +1566,7 @@ static void cp210x_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t static bool cp210x_set_baudrate(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { // Not every baud rate is supported. See datasheets and AN205 "CP210x Baud Rate Support" uint32_t baud_le = tu_htole32(p_cdc->requested_line.coding.bit_rate); - return cp210x_set_request(p_cdc, CP210X_SET_BAUDRATE, 0, (uint8_t *) &baud_le, 4, complete_cb, user_data); + return cp210x_set_request(p_cdc, CP210X_SET_BAUDRATE, 0, (uint8_t const *) &baud_le, 4, complete_cb, user_data); } static bool cp210x_set_data_format(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { @@ -1640,7 +1643,7 @@ static uint16_t ch34x_get_divisor_prescaler(cdch_interface_t *p_cdc); //------------- Control Request -------------// static bool ch34x_set_request(cdch_interface_t *p_cdc, uint8_t direction, uint8_t request, - uint16_t value, uint16_t index, uint8_t *buffer, uint16_t length, + uint16_t value, uint16_t index, uint8_t const *buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { tusb_control_request_t const request_setup = { .bmRequestType_bit = { @@ -1654,13 +1657,14 @@ static bool ch34x_set_request(cdch_interface_t *p_cdc, uint8_t direction, uint8_ .wLength = tu_htole16(length) }; - // use usbh enum buf since application variable does not live long enough - uint8_t *enum_buf = NULL; + // use local ctrl buf since application variable does not live long enough + uint8_t *ctrl_buf = NULL; - if (buffer && length > 0) { - enum_buf = usbh_get_enum_buf(); - if (direction == TUSB_DIR_OUT) { - tu_memcpy_s(enum_buf, CFG_TUH_ENUMERATION_BUFSIZE, buffer, length); + if (length > 0) { + uint8_t const idx = get_idx_by_ptr(p_cdc); + ctrl_buf = cdch_epbuf[idx].ctrl; + if (buffer && direction == TUSB_DIR_OUT) { + tu_memcpy_s(ctrl_buf, sizeof(cdch_epbuf[idx].ctrl), buffer, length); } } @@ -1668,7 +1672,7 @@ static bool ch34x_set_request(cdch_interface_t *p_cdc, uint8_t direction, uint8_ .daddr = p_cdc->daddr, .ep_addr = 0, .setup = &request_setup, - .buffer = enum_buf, + .buffer = ctrl_buf, .complete_cb = complete_cb, .user_data = user_data }; @@ -1682,8 +1686,8 @@ TU_ATTR_ALWAYS_INLINE static inline bool ch34x_control_out(cdch_interface_t *p_c } TU_ATTR_ALWAYS_INLINE static inline bool ch34x_control_in(cdch_interface_t *p_cdc, uint8_t request, uint16_t value, uint16_t index, - uint8_t *buffer, uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - return ch34x_set_request(p_cdc, TUSB_DIR_IN, request, value, index, buffer, buffersize, + uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return ch34x_set_request(p_cdc, TUSB_DIR_IN, request, value, index, NULL, buffersize, complete_cb, user_data); } @@ -1692,12 +1696,6 @@ TU_ATTR_ALWAYS_INLINE static inline bool ch34x_write_reg(cdch_interface_t *p_cdc return ch34x_control_out(p_cdc, CH34X_REQ_WRITE_REG, reg, reg_value, complete_cb, user_data); } -//static bool ch34x_read_reg_request ( cdch_interface_t * p_cdc, uint16_t reg, -// uint8_t *buffer, uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data ) -//{ -// return ch34x_control_in ( p_cdc, CH34X_REQ_READ_REG, reg, 0, buffer, buffersize, complete_cb, user_data ); -//} - //------------- Driver API -------------// // internal control complete to update state such as line state, encoding @@ -1794,8 +1792,7 @@ static bool ch34x_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) switch (state) { case CONFIG_CH34X_READ_VERSION: { - uint8_t* enum_buf = usbh_get_enum_buf(); - TU_ASSERT(ch34x_control_in(p_cdc, CH34X_REQ_READ_VERSION, 0, 0, enum_buf, 2, + TU_ASSERT(ch34x_control_in(p_cdc, CH34X_REQ_READ_VERSION, 0, 0, 2, cdch_process_set_config, CONFIG_CH34X_SERIAL_INIT)); break; } @@ -1950,7 +1947,7 @@ static bool pl2303_encode_baud_rate(cdch_interface_t *p_cdc, uint8_t buf[PL2303_ //------------- Control Request -------------// static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t requesttype, - uint16_t value, uint16_t index, uint8_t *buffer, uint16_t length, + uint16_t value, uint16_t index, uint8_t const *buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { tusb_control_request_t const request_setup = { .bmRequestType = requesttype, @@ -1960,13 +1957,14 @@ static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t .wLength = tu_htole16(length) }; - // use usbh enum buf since application variable does not live long enough - uint8_t *enum_buf = NULL; + // use local ctrl buf since application variable does not live long enough + uint8_t *ctrl_buf = NULL; - if (buffer && length > 0) { - enum_buf = usbh_get_enum_buf(); - if (request_setup.bmRequestType_bit.direction == TUSB_DIR_OUT) { - tu_memcpy_s(enum_buf, CFG_TUH_ENUMERATION_BUFSIZE, buffer, length); + if (length > 0) { + uint8_t const idx = get_idx_by_ptr(p_cdc); + ctrl_buf = cdch_epbuf[idx].ctrl; + if (buffer && request_setup.bmRequestType_bit.direction == TUSB_DIR_OUT) { + tu_memcpy_s(ctrl_buf, sizeof(cdch_epbuf[idx].ctrl), buffer, length); } } @@ -1974,7 +1972,7 @@ static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t .daddr = p_cdc->daddr, .ep_addr = 0, .setup = &request_setup, - .buffer = enum_buf, + .buffer = ctrl_buf, .complete_cb = complete_cb, .user_data = user_data }; @@ -1982,10 +1980,10 @@ static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t return tuh_control_xfer(&xfer); } -static bool pl2303_vendor_read(cdch_interface_t *p_cdc, uint16_t value, uint8_t *buf, +static bool pl2303_vendor_read(cdch_interface_t *p_cdc, uint16_t value, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { uint8_t request = p_cdc->pl2303.type == PL2303_TYPE_HXN ? PL2303_VENDOR_READ_NREQUEST : PL2303_VENDOR_READ_REQUEST; - return pl2303_set_request(p_cdc, request, PL2303_VENDOR_READ_REQUEST_TYPE, value, 0, buf, 1, complete_cb, user_data); + return pl2303_set_request(p_cdc, request, PL2303_VENDOR_READ_REQUEST_TYPE, value, 0, NULL, 1, complete_cb, user_data); } static bool pl2303_vendor_write(cdch_interface_t *p_cdc, uint16_t value, uint16_t index, @@ -1995,9 +1993,8 @@ static bool pl2303_vendor_write(cdch_interface_t *p_cdc, uint16_t value, uint16_ } static inline bool pl2303_supports_hx_status(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - uint8_t buf = 0; return pl2303_set_request(p_cdc, PL2303_VENDOR_READ_REQUEST, PL2303_VENDOR_READ_REQUEST_TYPE, PL2303_READ_TYPE_HX_STATUS, 0, - &buf, 1, complete_cb, user_data); + NULL, 1, complete_cb, user_data); } //static bool pl2303_get_line_request(cdch_interface_t * p_cdc, uint8_t buf[PL2303_LINE_CODING_BUFSIZE]) { @@ -2131,7 +2128,6 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) // state CONFIG_PL2303_READ1 may have no success due to expected stall by pl2303_supports_hx_status() const uintptr_t state = xfer->user_data; TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS || state == CONFIG_PL2303_READ1); - uint8_t* enum_buf = usbh_get_enum_buf(); pl2303_type_t type; switch (state) { @@ -2162,7 +2158,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) // purpose unknown, overtaken from Linux Kernel driver if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { - TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE1)); + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, cdch_process_set_config, CONFIG_PL2303_WRITE1)); break; }// else: continue with next step TU_ATTR_FALLTHROUGH; @@ -2178,7 +2174,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) case CONFIG_PL2303_READ2: // purpose unknown, overtaken from Linux Kernel driver if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { - TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ3)); + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, cdch_process_set_config, CONFIG_PL2303_READ3)); break; }// else: continue with next step TU_ATTR_FALLTHROUGH; @@ -2186,7 +2182,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) case CONFIG_PL2303_READ3: // purpose unknown, overtaken from Linux Kernel driver if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { - TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ4)); + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, cdch_process_set_config, CONFIG_PL2303_READ4)); break; }// else: continue with next step TU_ATTR_FALLTHROUGH; @@ -2194,7 +2190,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) case CONFIG_PL2303_READ4: // purpose unknown, overtaken from Linux Kernel driver if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { - TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE2)); + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, cdch_process_set_config, CONFIG_PL2303_WRITE2)); break; }// else: continue with next step TU_ATTR_FALLTHROUGH; @@ -2210,7 +2206,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) case CONFIG_PL2303_READ5: // purpose unknown, overtaken from Linux Kernel driver if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { - TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ6)); + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, cdch_process_set_config, CONFIG_PL2303_READ6)); break; }// else: continue with next step TU_ATTR_FALLTHROUGH; @@ -2218,7 +2214,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) case CONFIG_PL2303_READ6: // purpose unknown, overtaken from Linux Kernel driver if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { - TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE3)); + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, cdch_process_set_config, CONFIG_PL2303_WRITE3)); break; }// else: continue with next step TU_ATTR_FALLTHROUGH; -- cgit v1.3.1 From dffc57135846a4b00aca06b2f588daa6d13b67ef Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Thu, 11 Jun 2026 10:17:28 +0700 Subject: Fix stm32f723disco host/cdc_msc_hid HIL: UART RX starvation + DWC2 DMA split-IN NAK storm (#3677) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix stm32f723disco host HIL: UART RX starvation + DWC2 split bulk NAK/XactErr handling (#3677) stm32f7 BSP — UART RX starvation - The host console USART shared interrupt priority with the USB OTG ISR, so a long OTG interrupt could starve RXNE and drop received bytes. Raise the USART RX IRQ above OTG_FS/OTG_HS in both the bare-metal and FreeRTOS init paths, guarded by #ifdef UART_ID so boards without a UART console keep the default OTG priority. dwc2 host — split NAK/XactErr handling - Slave mode: a persistently-NAKing split bulk/control IN poll re-armed the start-split immediately, storming the ISR and starving task context. Throttle by disabling the channel and re-arming on the resulting halt (no frame deferral). - Buffer-DMA mode: a pure split bulk-OUT NAK was unhandled, leaving the channel halted and stalling the transfer — the dominant cause of CDC echo truncation. Handle it by rewinding the buffer pointers and retrying the start-split (Programming Guide v4.20a 5.1.4.2). - Buffer-DMA mode: a split bulk-OUT XactErr was retried immediately, exhausting HCD_XFER_ERROR_MAX before the transient cleared. Throttle via channel_disable + re-arm to give the hub TT a recovery gap, mirroring slave mode. - All three are scoped to split transfers (hcsplt.split_en); non-split NAK/XactErr keep the core-handled / immediate-retry behavior. The OUT XactErr throttle also excludes periodic split, where channel_disable() is a no-op and would wedge the channel. The nak_disabled flag is generalized to retry_disabled and honors xfer->closing so an endpoint close during a throttled retry tears down cleanly. Verified on stm32f723disco HIL (slave + CFG_TUH_DWC2_DMA_ENABLE): host/cdc_msc_hid, msc_file_explorer, and device_info all pass on both variants; DMA CDC echo went from ~15-25% raw failure to 10/10 clean. --- AGENTS.md | 4 +-- hw/bsp/stm32f7/family.c | 21 +++++++++++---- src/portable/synopsys/dwc2/hcd_dwc2.c | 51 +++++++++++++++++++++++++++++++---- tools/codespell/ignore-words.txt | 1 + 4 files changed, 65 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/AGENTS.md b/AGENTS.md index 5c9908d19..93faa6332 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ Bias toward caution over speed. For trivial tasks, use judgment. - **Language/style:** C99, 2-space indent (no tabs), snake_case helpers, `UPPER_CASE` macros. Public APIs use `tud_`/`tuh_`; macros use `TU_`. Headers self-contained with `#if CFG_TUSB_MCU` guards. - **Safety:** no dynamic allocation; defer ISR work to task context; use `TU_ASSERT()` for error checks; always check return values; include order: C stdlib → tusb common → drivers → classes. - **Layout:** `src/` core, `hw/{mcu,bsp}/` MCU+BSP, `examples/{device,host,dual}/`, `test/{unit-test,fuzz,hil}/`, `docs/`, `tools/`. -- **Commits/PRs:** imperative mood, scoped changes, link issues, include test/build evidence. +- **Commits/PRs:** imperative mood, scoped changes, link issues, include test/build evidence. After opening a PR, monitor it and drive it to green: address automated review comments (Copilot/Codex/Claude) and fix any failing CI builds, pushing follow-up commits until checks pass and review threads are resolved. Useful: `gh pr checks --watch`, `gh pr view --comments`. - **Formatting/lint:** `clang-format` (`.clang-format`), `codespell` (`.codespellrc`), run `pre-commit run --all-files` before submitting. ## Bootstrap @@ -204,7 +204,7 @@ Device examples need real hardware to validate runtime behavior; must at least b ## References -- MCU reference manuals, datasheets, schematics: `$HOME/Documents/Calibre Library`. +- MCU reference manuals, datasheets, schematics: `$HOME/Documents/calibre-library`. - Supported MCUs/boards: `hw/bsp/` and `docs/reference/boards.rst`. - USB classes: `src/class/{cdc,hid,msc,audio,…}/` — each has `*_device.c` and `*_host.c`. - Key files: `src/tusb.h`, `src/tusb_config.h`, `tools/get_deps.py`, `tools/build.py`, `test/unit-test/project.yml`. diff --git a/hw/bsp/stm32f7/family.c b/hw/bsp/stm32f7/family.c index 7a322591b..9427ac4a6 100644 --- a/hw/bsp/stm32f7/family.c +++ b/hw/bsp/stm32f7/family.c @@ -82,8 +82,9 @@ static UART_HandleTypeDef UartHandle = {.Instance = USARTn, .OverSampling = UART_OVERSAMPLING_16, }}; -// RX ring buffer via RXNE interrupt — no HAL IT functions used (avoid HAL state conflicts) -static uint8_t uart_rx_ff_buf[32]; +// RX ring buffer via RXNE interrupt — no HAL IT functions used (avoid HAL state conflicts). +// Sized to absorb a full host-forwarding burst (>64B) when the main loop briefly stalls. +static uint8_t uart_rx_ff_buf[256]; static tu_fifo_t uart_rx_ff; void USARTn_IRQHandler(void) { @@ -142,13 +143,24 @@ void board_init(void) { // 1ms tick timer SysTick_Config(SystemCoreClock / 1000); + // Set UART interrupt higher priority than USB OTG since the F7 USART has no hardware RX FIFO, so a host example's + // UART RX must not be starved by the frequent USB host interrupts or incoming bytes overrun (ORE) and dropped. + NVIC_SetPriority(OTG_FS_IRQn, 1); + NVIC_SetPriority(OTG_HS_IRQn, 1); + #ifdef UART_ID + NVIC_SetPriority(USARTn_IRQn, 0); + #endif + #elif CFG_TUSB_OS == OPT_OS_FREERTOS // Explicitly disable systick to prevent its ISR from running before scheduler start SysTick->CTRL &= ~1U; // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) - NVIC_SetPriority(OTG_FS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); - NVIC_SetPriority(OTG_HS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(OTG_FS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1); + NVIC_SetPriority(OTG_HS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1); + #ifdef UART_ID + NVIC_SetPriority(USARTn_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + #endif #endif #ifdef UART_ID @@ -156,7 +168,6 @@ void board_init(void) { HAL_UART_Init(&UartHandle); tu_fifo_config(&uart_rx_ff, uart_rx_ff_buf, sizeof(uart_rx_ff_buf), false); USARTn->CR1 |= USART_CR1_RXNEIE; - NVIC_SetPriority(USARTn_IRQn, (1 << __NVIC_PRIO_BITS) - 1); NVIC_EnableIRQ(USARTn_IRQn); #endif diff --git a/src/portable/synopsys/dwc2/hcd_dwc2.c b/src/portable/synopsys/dwc2/hcd_dwc2.c index 9ea5f33c5..84a0c6afd 100644 --- a/src/portable/synopsys/dwc2/hcd_dwc2.c +++ b/src/portable/synopsys/dwc2/hcd_dwc2.c @@ -104,6 +104,7 @@ typedef struct { uint16_t xferred_bytes; // bytes that accumulate transferred though USB bus for the whole hcd_edpt_xfer(), which can // be composed of multiple channel_xfer_start() (retry with NAK/NYET) uint16_t fifo_bytes; // bytes written/read from/to FIFO (may not be transferred on USB bus). + uint8_t retry_disabled; // 1: channel was disabled to throttle a split retry (NAK in / XactErr out); re-arm on its halt } hcd_xfer_t; typedef struct { @@ -1137,7 +1138,16 @@ static bool handle_channel_in_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci // TU_LOG1("in hcint = %02lX\r\n", hcint); if (hcint & HCINT_HALTED) { - if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL | HCINT_BABBLE_ERR)) { + if (xfer->retry_disabled) { + // Halt from our split-NAK throttle disable (below): re-arm the start-split, or let teardown finish + // if the endpoint is closing. Programming Guide 3.5 "Halting a Channel" (p73). + xfer->retry_disabled = 0; + if (xfer->closing) { + is_done = true; + } else { + channel_send_in_token(dwc2, channel); + } + } else if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL | HCINT_BABBLE_ERR)) { const uint16_t remain_bytes = (uint16_t) hctsiz.xfer_size; const uint16_t remain_packets = hctsiz.packet_count; const uint16_t actual_len = edpt->buflen - remain_bytes; @@ -1203,7 +1213,15 @@ static bool handle_channel_in_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci channel->hcintmsk &= ~(HCINT_NAK | HCINT_DATATOGGLE_ERR); hcsplt.split_compl = 0; // restart with start-split channel->hcsplt = hcsplt.value; - channel_xfer_in_retry(dwc2, ch_id, hcint); + // Persistent split bulk/control IN NAK (e.g. idle polled endpoint): re-enabling immediately storms + // the ISR and starves the task. Disable + re-arm on the resulting halt to throttle (like the slave + // path); no frame deferral. Programming Guide 3.5 (p73) Note permits disable on NAK/FrmOvrn splits. + if ((hcint & HCINT_NAK) && hcsplt.split_en && !channel_is_periodic(channel->hcchar)) { + xfer->retry_disabled = 1; + channel_disable(dwc2, channel); + } else { + channel_xfer_in_retry(dwc2, ch_id, hcint); + } } else if (hcint & HCINT_FARME_OVERRUN) { // retry start-split in next binterval channel_xfer_in_retry(dwc2, ch_id, hcint); @@ -1228,7 +1246,16 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc // TU_LOG1("out hcint = %02lX\r\n", hcint); if (hcint & HCINT_HALTED) { - if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL)) { + if (xfer->retry_disabled) { + // Halt from our split-XactErr throttle disable (below): re-issue the start-split (pointers already + // rewound), giving the hub TT a recovery gap. Programming Guide 3.5 "Halting a Channel" (p73). + xfer->retry_disabled = 0; + if (xfer->closing) { + is_done = true; + } else { + channel_xfer_start(dwc2, ch_id); + } + } else if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL)) { is_done = true; xfer->err_count = 0; if (hcint & HCINT_XFER_COMPLETE) { @@ -1251,9 +1278,17 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc xfer->result = XFER_RESULT_FAILED; is_done = true; } else { - // clean up transfer so far and start again + // Rewind, then retry the start-split. Non-periodic SPLIT throttles via channel_disable + re-arm on + // the halt (immediate re-fire exhausts the retry budget; the disable gives the hub TT a recovery + // gap, like slave). Periodic split is excluded: channel_disable() is a no-op for it, so the halt + // never fires and the channel would wedge. Non-split re-inits immediately (Programming Guide 5.1.2.3). channel_xfer_out_wrapup(dwc2, ch_id); - channel_xfer_start(dwc2, ch_id); + if (hcsplt.split_en && !channel_is_periodic(channel->hcchar)) { + xfer->retry_disabled = 1; + channel_disable(dwc2, channel); + } else { + channel_xfer_start(dwc2, ch_id); + } } } } else if (hcint & HCINT_NYET) { @@ -1271,6 +1306,12 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc channel->hcsplt = hcsplt.value; channel->hcchar |= HCCHAR_CHENA; } + } else if ((hcint & HCINT_NAK) && hcsplt.split_en) { + // Split OUT NAK: rewind + retry the start-split, else the channel stalls (Programming Guide 5.1.4.2). + // Non-split OUT NAK is core-handled (5.1.2.2), so this is split-only. + xfer->err_count = 0; + channel_xfer_out_wrapup(dwc2, ch_id); + channel_xfer_start(dwc2, ch_id); } if (xfer->closing == 1) { diff --git a/tools/codespell/ignore-words.txt b/tools/codespell/ignore-words.txt index 7ce778fab..0b1aa284a 100644 --- a/tools/codespell/ignore-words.txt +++ b/tools/codespell/ignore-words.txt @@ -6,6 +6,7 @@ fro hsi inout mot +ore pris ptd ser -- cgit v1.3.1 From 06b8f4f013a6ce0d91d2f713c88313569d8a722c Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 13 Jun 2026 00:17:07 +0700 Subject: dcd/musb: extract pipe0_read_setup() helper The 8-byte EP0 SETUP drain (count0 assert + two FIFO word reads via a union) was duplicated verbatim between the IDLE case and the deferral case; a future fix applied to one copy but not the other would only show up on the rare deferred-race path. Share one helper. count0 is now read inside the only remaining user (DATA OUT drain). Review follow-up for #3643 (dcd_musb.c l.507 finding). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index e00585068..08d7dd700 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -104,6 +104,19 @@ typedef struct { static dcd_data_t _dcd; +// Drain a SETUP packet (8 bytes) from the EP0 FIFO. Does not ack RxPktRdy. +static bool pipe0_read_setup(musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr, tusb_control_request_t* req) { + TU_ASSERT(sizeof(tusb_control_request_t) == ep_csr->count0); + union { + tusb_control_request_t req; + uint32_t u32[2]; + } setup_packet; + setup_packet.u32[0] = musb_regs->fifo[0]; + setup_packet.u32[1] = musb_regs->fifo[0]; + *req = setup_packet.req; + return true; +} + static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, tusb_control_request_t const* req, bool is_isr) { _dcd.pipe0.remain_wlength = req->wLength; @@ -466,23 +479,18 @@ static void process_ep0(uint8_t rhport) { // Receive Data (Setup or OUT) if (csrl & MUSB_CSRL0_RXRDY) { - const uint16_t count0 = ep_csr->count0; switch (_dcd.pipe0.state) { case PIPE0_STATE_IDLE: { - TU_ASSERT(sizeof(tusb_control_request_t) == count0, ); - union { - tusb_control_request_t req; - uint32_t u32[2]; - } setup_packet; - setup_packet.u32[0] = musb_regs->fifo[0]; - setup_packet.u32[1] = musb_regs->fifo[0]; - pipe0_start_setup(rhport, ep_csr, &setup_packet.req, true); + tusb_control_request_t req; + TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &req), ); + pipe0_start_setup(rhport, ep_csr, &req, true); break; } case PIPE0_STATE_DATA_OUT: { // EP0 OUT is single-packet (TU_ASSERT total_bytes <= EP0_SIZE in edpt0_xfer) // so the whole packet drains in one shot. + const uint16_t count0 = ep_csr->count0; if (count0) { tu_hwfifo_read(&musb_regs->fifo[0], _dcd.pipe0.buf, count0, NULL); _dcd.pipe0.remain_wlength -= count0; @@ -503,15 +511,7 @@ static void process_ep0(uint8_t rhport) { case PIPE0_STATE_STATUS_OUT_PENDING: case PIPE0_STATE_STATUS_IN: case PIPE0_STATE_DATA_IN: { - TU_ASSERT(sizeof(tusb_control_request_t) == count0, ); - union { - tusb_control_request_t req; - uint32_t u32[2]; - } setup_packet; - setup_packet.u32[0] = musb_regs->fifo[0]; - setup_packet.u32[1] = musb_regs->fifo[0]; - - _dcd.pipe0.deferred_setup = setup_packet.req; + TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &_dcd.pipe0.deferred_setup), ); _dcd.pipe0.deferred_setup_valid = true; goto process_status; } -- cgit v1.3.1 From 87eeab605ff571a5ac1784c2c26e944aa0129d7e Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 13 Jun 2026 00:17:30 +0700 Subject: dcd/musb: restore EP0 OUT RXRDY flow-control comment The pre-existing comment explaining why the OUT branch does not ack RxPktRdy was dropped when the SETUP handling moved into pipe0_start_setup(). It is load-bearing: acking before edpt0_xfer() arms the drain buffer would let the host send data with nowhere to put it. Restore it with the databook-deviation rationale so the branches don't get "unified" later. Review follow-up for #3643 (dcd_musb.c l.116 finding). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 08d7dd700..fdd2eaac9 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -128,6 +128,9 @@ static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, _dcd.pipe0.state = PIPE0_STATE_DATA_IN; ep_csr->csr0l = MUSB_CSRL0_RXRDYC; } else { + // If OUT (rx) direction, let edpt0_xfer() clear RXRDY when it's ready to receive data. + // Deliberate deviation from the databook's canonical flow (ack right after unload), + // used as NAK flow control until usbd arms the drain buffer. _dcd.pipe0.state = PIPE0_STATE_DATA_OUT; } } -- cgit v1.3.1 From b21d59f8177af967e2b2757c4ef996df00d1e617 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 13 Jun 2026 00:18:32 +0700 Subject: dcd/musb: replace deferral goto with per-state handling The goto jumped into the csrl==0 completion switch with RXRDY still set, making its "When CSRL0 is zero" guard comment untrue on that path. Handle each deferral state in a self-contained switch instead; the csrl==0 switch is now only reached with csrl==0 and its comment is truthful again. Behavior unchanged. Review follow-up for #3643 (dcd_musb.c l.523 finding). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 43 +++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index fdd2eaac9..9bdd6b080 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -510,20 +510,55 @@ static void process_ep0(uint8_t rhport) { // - Status IN/OUT finished, IRQ and new setup packet IRQ arrive at the same time. // - Data IN finished and status OUT is received, both IRQs and new setup packet IRQ arrive at the same time. // could happen when CPU load is high, save the new setup packet for later processing after current status stage complete. + case PIPE0_STATE_DATA_IN: case PIPE0_STATE_STATUS_OUT: case PIPE0_STATE_STATUS_OUT_PENDING: - case PIPE0_STATE_STATUS_IN: - case PIPE0_STATE_DATA_IN: { + case PIPE0_STATE_STATUS_IN: { TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &_dcd.pipe0.deferred_setup), ); _dcd.pipe0.deferred_setup_valid = true; - goto process_status; + + switch (_dcd.pipe0.state) { + case PIPE0_STATE_DATA_IN: + // Last DATA IN packet sent (TXRDY-clear coalesced with the SETUP IRQ). The STATUS OUT + // confirm IRQ is missed too — promote so edpt0_xfer(STATUS OUT) fires complete immediately. + if (_dcd.pipe0.remain_wlength == 0) { + _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING; + } + dcd_event_xfer_complete(rhport, TU_EP0_IN, _dcd.pipe0.xact_len, XFER_RESULT_SUCCESS, true); + break; + + case PIPE0_STATE_STATUS_OUT: + // Status confirm IRQ coalesced with the SETUP — edpt0_xfer(STATUS OUT) fires complete. + _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING; + break; + + case PIPE0_STATE_STATUS_OUT_PENDING: + // edpt0_xfer(STATUS OUT) already called — fire complete and replay now. + _dcd.pipe0.state = PIPE0_STATE_IDLE; + dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); + pipe0_process_deferred_setup(rhport, ep_csr, true); + break; + + default: + // PIPE0_STATE_STATUS_IN: ZLP-sent IRQ coalesced with the SETUP. + if (_dcd.pipe0.pending_addr) { + musb_regs->faddr = _dcd.pipe0.pending_addr; + _dcd.pipe0.pending_addr = 0; + } + _dcd.pipe0.state = PIPE0_STATE_IDLE; + dcd_event_xfer_complete(rhport, TU_EP0_IN, 0, XFER_RESULT_SUCCESS, true); + pipe0_process_deferred_setup(rhport, ep_csr, true); + break; + } + break; } + + default: break; } return; } -process_status: /* When CSRL0 is zero, it means that either * - completion of sending any length packet TxPktRdy clear * - or status stage is complete (ZLP) after DataEnd is set */ -- cgit v1.3.1 From 1ea385a6c431cee759695515a4bed94c6dff65c6 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 13 Jun 2026 00:18:55 +0700 Subject: dcd/musb: check SentStall/SetupEnd before DATAEND guard MUSBMHDRC 21.1.5 requires the EP0 service routine to check SentStall and SetupEnd first; the early DATAEND return ran before both, and SentStall is most likely to fire exactly while DataEnd may still read back set (auto-STALL after DataEnd, 21.1.7), which would skip the recovery. The guard also moves below the RXRDY block so a coalesced DATAEND|RXRDY read cannot swallow a SETUP on cores where the CPU-set-only DataEnd bit reads back 1; the comment documents the vendor-dependent read-back. Review follow-up for #3643 (dcd_musb.c l.445 finding). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 9bdd6b080..86ae3ae9a 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -458,10 +458,7 @@ static void process_ep0(uint8_t rhport) { musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0); uint_fast8_t csrl = ep_csr->csr0l; - if (csrl & MUSB_CSRL0_DATAEND) { - return; - } - + // 21.1.5: SentStall and SetupEnd must be checked before anything else. if (csrl & MUSB_CSRL0_STALLED) { ep_csr->csr0l = 0; _dcd.pipe0.state = PIPE0_STATE_IDLE; @@ -559,6 +556,13 @@ static void process_ep0(uint8_t rhport) { return; } + if (csrl & MUSB_CSRL0_DATAEND) { + // Last DATA IN chunk / STATUS IN arm wrote TXRDY|DATAEND and the status stage has not completed + // yet — nothing to service. DataEnd is CPU-set-only per the CSR access table; whether it ever + // reads back 1 is vendor-dependent (on cores where it reads 0 this guard is dead code). + return; + } + /* When CSRL0 is zero, it means that either * - completion of sending any length packet TxPktRdy clear * - or status stage is complete (ZLP) after DataEnd is set */ -- cgit v1.3.1 From 91608e3c4f8c944674547e5c254759c1dda08379 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 13 Jun 2026 00:20:37 +0700 Subject: dcd/musb: fix deferred-SETUP replay racing usbd's status call STATUS_OUT_PENDING conflated "edpt0_xfer(STATUS OUT) called, awaiting confirm IRQ" with "confirm IRQ seen, awaiting edpt0_xfer". The deferral path completed the status and replayed the saved SETUP from the ISR in both flavors; in the IRQ-first one, usbd's still- outstanding edpt0_xfer(STATUS OUT) for the old transfer (queued via status_stage_xact) then landed in the replayed transfer's state and corrupted it: NULL pipe0.buf armed plus RXRDYC, so the host's next DATA OUT drained through a NULL pointer. usbd processes EP0 XFER_COMPLETE events unconditionally, so nothing downstream defuses it. Split the state into STATUS_OUT_PENDING_XFER / _IRQ. The deferral completes and replays only in PENDING_XFER (old transfer already retired); in PENDING_IRQ it only holds the SETUP and the usbd-driven edpt0_xfer fires the completion and replays. The DATA_IN deferral now synthesizes PENDING_IRQ (its remain==0 invariant asserted: a SETUP before DataEnd raises SetupEnd instead), which also makes the old deferred-promotion in the csrl==0 DATA_IN case unreachable - dropped. Assert the drain buffer before the DATA OUT FIFO read as a cheap backstop for this corruption class. Review follow-up for #3643 (dcd_musb.c l.503 finding). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 59 ++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 86ae3ae9a..2c31e3b2f 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -86,7 +86,8 @@ enum { PIPE0_STATE_DATA_OUT, // DATA OUT stage PIPE0_STATE_STATUS_IN, // STATUS IN — device sends IN-ZLP; awaits send-ACK IRQ PIPE0_STATE_STATUS_OUT, // post-DATAEND, neither edpt0_xfer(STATUS OUT) nor confirmation IRQ has happened yet - PIPE0_STATE_STATUS_OUT_PENDING, // one of {edpt0_xfer(STATUS OUT), confirmation IRQ} has happened; the other fires xfer_complete + PIPE0_STATE_STATUS_OUT_PENDING_XFER, // edpt0_xfer(STATUS OUT) called first; the confirmation IRQ fires xfer_complete + PIPE0_STATE_STATUS_OUT_PENDING_IRQ, // confirmation IRQ seen (or synthesized) first; edpt0_xfer(STATUS OUT) fires xfer_complete }; typedef struct { @@ -436,11 +437,12 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ case PIPE0_STATE_STATUS_OUT: TU_ASSERT(!dir_in && total_bytes == 0); // only STATUS OUT allowed // First event of the STATUS OUT pair — wait for the IRQ to fire complete. - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING; + _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING_XFER; break; - case PIPE0_STATE_STATUS_OUT_PENDING: - // Second event — IRQ already arrived, fire complete now. + case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: + // Second event — IRQ already arrived, fire complete now. The old transfer is retired here, + // so a deferred SETUP can be replayed safely. _dcd.pipe0.state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, ep_addr, 0, XFER_RESULT_SUCCESS, is_isr); pipe0_process_deferred_setup(rhport, ep_csr, is_isr); @@ -492,6 +494,7 @@ static void process_ep0(uint8_t rhport) { // so the whole packet drains in one shot. const uint16_t count0 = ep_csr->count0; if (count0) { + TU_ASSERT(_dcd.pipe0.buf, ); tu_hwfifo_read(&musb_regs->fifo[0], _dcd.pipe0.buf, count0, NULL); _dcd.pipe0.remain_wlength -= count0; } @@ -503,39 +506,48 @@ static void process_ep0(uint8_t rhport) { break; } - // New SETUP packet arrived while old control transfer is not finished yet. This could happen in following scenarios: - // - Status IN/OUT finished, IRQ and new setup packet IRQ arrive at the same time. - // - Data IN finished and status OUT is received, both IRQs and new setup packet IRQ arrive at the same time. - // could happen when CPU load is high, save the new setup packet for later processing after current status stage complete. + // New SETUP packet arrived while the old control transfer's tail events are still in flight + // (IRQs coalesced under high CPU load), e.g.: + // - Status IN/OUT finished, its IRQ and the new SETUP IRQ arrive at the same time. + // - Data IN finished and status OUT is received, both IRQs and the new SETUP IRQ arrive at the same time. + // Save the SETUP; it is replayed only once the old transfer is fully retired — i.e. when usbd has + // made (or already made) its final edpt0_xfer() call for it. case PIPE0_STATE_DATA_IN: case PIPE0_STATE_STATUS_OUT: - case PIPE0_STATE_STATUS_OUT_PENDING: + case PIPE0_STATE_STATUS_OUT_PENDING_XFER: + case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: case PIPE0_STATE_STATUS_IN: { TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &_dcd.pipe0.deferred_setup), ); _dcd.pipe0.deferred_setup_valid = true; switch (_dcd.pipe0.state) { case PIPE0_STATE_DATA_IN: - // Last DATA IN packet sent (TXRDY-clear coalesced with the SETUP IRQ). The STATUS OUT - // confirm IRQ is missed too — promote so edpt0_xfer(STATUS OUT) fires complete immediately. - if (_dcd.pipe0.remain_wlength == 0) { - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING; - } + // Coalesced: last DATA IN sent + status OUT done + new SETUP in one csrl read. Fire the + // DATA IN completion and synthesize the missed status confirm; usbd's edpt0_xfer(STATUS OUT) + // fires the status completion and replays. + TU_ASSERT(_dcd.pipe0.remain_wlength == 0, ); + _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; dcd_event_xfer_complete(rhport, TU_EP0_IN, _dcd.pipe0.xact_len, XFER_RESULT_SUCCESS, true); break; case PIPE0_STATE_STATUS_OUT: // Status confirm IRQ coalesced with the SETUP — edpt0_xfer(STATUS OUT) fires complete. - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING; + _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; break; - case PIPE0_STATE_STATUS_OUT_PENDING: - // edpt0_xfer(STATUS OUT) already called — fire complete and replay now. + case PIPE0_STATE_STATUS_OUT_PENDING_XFER: + // edpt0_xfer(STATUS OUT) already called — old transfer retired, complete and replay now. _dcd.pipe0.state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); pipe0_process_deferred_setup(rhport, ep_csr, true); break; + case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: + // usbd has not called edpt0_xfer(STATUS OUT) for the old transfer yet — only hold the + // SETUP. Replaying here would let that still-outstanding call land in the replayed + // transfer's state and corrupt it (e.g. NULL DATA OUT drain buffer). + break; + default: // PIPE0_STATE_STATUS_IN: ZLP-sent IRQ coalesced with the SETUP. if (_dcd.pipe0.pending_addr) { @@ -573,27 +585,26 @@ static void process_ep0(uint8_t rhport) { // to STATUS_OUT to await the host's STATUS-OUT ZLP confirmation IRQ. if (_dcd.pipe0.remain_wlength == 0) { _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT; - // If a new SETUP was deferred then STATUS OUT IRQ is missed, manually transition to STATUS_OUT_PENDING to allow ep0_xfer(STATUS OUT) to fire complete immediately. - if (_dcd.pipe0.deferred_setup_valid) { - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING; - } } dcd_event_xfer_complete(rhport, TU_EP0_IN, _dcd.pipe0.xact_len, XFER_RESULT_SUCCESS, true); - break; case PIPE0_STATE_STATUS_OUT: // First event of the STATUS OUT pair — wait for edpt0_xfer(STATUS OUT) to fire complete. - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING; + _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; break; - case PIPE0_STATE_STATUS_OUT_PENDING: + case PIPE0_STATE_STATUS_OUT_PENDING_XFER: // Second event — edpt0_xfer(STATUS OUT) already called, fire complete now. _dcd.pipe0.state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); pipe0_process_deferred_setup(rhport, ep_csr, true); break; + case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: + // Stale duplicate of the status confirm — already accounted for; edpt0_xfer fires complete. + break; + case PIPE0_STATE_STATUS_IN: if (_dcd.pipe0.pending_addr) { musb_regs->faddr = _dcd.pipe0.pending_addr; -- cgit v1.3.1 From 3b73ee7e926d228bfa6ea4961d15a11a0310ed44 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 13 Jun 2026 00:22:03 +0700 Subject: dcd/musb: gate stale EP0 RXRDY interrupts with rxrdy_consumed The deferral path drains the SETUP but leaves RxPktRdy set, and the SETUP's IRQ latches after the ISR's clear-on-read intr_tx read - so a second process_ep0 pass (same ISR, via the intr_tx re-read merge) is guaranteed and misreads the leftovers: count0==0 fires a spurious DATA OUT completion, the replay's RXRDYC write turns the second pass into a phantom csrl==0 DATA IN completion, and a zero-length replay re-enters the deferral case on a drained FIFO (count0 assert or garbage saved as a SETUP). The registers cannot expose the staleness: RxPktRdy and count0 read unchanged until ServicedRxPktRdy is written. Track it in software: rxrdy_consumed means "RxPktRdy is set in hw but its packet was already consumed". Set wherever a drained packet's RXRDY is intentionally left set (OUT/zero-length flow-control parks, every DATA OUT drain awaiting the next arm, the deferral path); cleared at every RXRDYC write site (edpt0_xfer arms, dcd_set_address, STALLED/SETEND recovery, bus reset). The RXRDY block returns early while parked. Replayed IN requests skip the RXRDYC in pipe0_start_setup and keep the packet parked until the edpt0_xfer(DATA IN) arm acks it (before loading the shared FIFO), so the stale pass sees RXRDY+parked instead of csrl==0. The normal IDLE path is unchanged - master never re-entered these windows because the single SETUP edge was always consumed by the pass that parked it; the deferral is what introduced a pending second pass. Review follow-up for #3643 (dcd_musb.c l.516 finding). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 2c31e3b2f..0485c4374 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -99,6 +99,8 @@ typedef struct { uint8_t pending_addr; // new USB address latched by dcd_set_address; applied when STATUS IN completes tusb_control_request_t deferred_setup; bool deferred_setup_valid; + bool rxrdy_consumed; // RxPktRdy left set in hw for an already-consumed packet (NAK flow control); + // RXRDY events are stale while set. Cleared when RXRDYC is written. } pipe0; pipe_state_t pipe[MUSB_PIPE_COUNT]; } dcd_data_t; @@ -123,16 +125,23 @@ static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, _dcd.pipe0.remain_wlength = req->wLength; if (req->wLength == 0) { + // Leave RXRDY set; edpt0_xfer(STATUS IN) acks it together with DATAEND. _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; + _dcd.pipe0.rxrdy_consumed = true; } else { if (req->bmRequestType & TUSB_DIR_IN_MASK) { _dcd.pipe0.state = PIPE0_STATE_DATA_IN; - ep_csr->csr0l = MUSB_CSRL0_RXRDYC; + // On a deferred replay the packet's RXRDY stays parked until the edpt0_xfer(DATA IN) arm + // acks it — a stale latched EP0 IRQ in between is gated by rxrdy_consumed. + if (!_dcd.pipe0.rxrdy_consumed) { + ep_csr->csr0l = MUSB_CSRL0_RXRDYC; + } } else { // If OUT (rx) direction, let edpt0_xfer() clear RXRDY when it's ready to receive data. // Deliberate deviation from the databook's canonical flow (ack right after unload), // used as NAK flow control until usbd arms the drain buffer. _dcd.pipe0.state = PIPE0_STATE_DATA_OUT; + _dcd.pipe0.rxrdy_consumed = true; } } @@ -412,6 +421,11 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ case PIPE0_STATE_DATA_OUT: { _dcd.pipe0.xact_len = total_bytes; if (dir_in) { + // Replayed SETUP keeps its RXRDY parked until here; ack it before loading the shared FIFO. + if (_dcd.pipe0.rxrdy_consumed) { + ep_csr->csr0l = MUSB_CSRL0_RXRDYC; + _dcd.pipe0.rxrdy_consumed = false; + } // DATA IN: load FIFO, set TXRDY. Add DATAEND on the last chunk // (ep0_remain_datalen == 0 after this load) to end the data stage. tu_hwfifo_write(&musb_regs->fifo[0], buffer, total_bytes, NULL); @@ -425,6 +439,7 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ // DATA OUT: arm drain target, ack RXRDY so host can send DATA OUT. _dcd.pipe0.buf = buffer; ep_csr->csr0l = MUSB_CSRL0_RXRDYC; + _dcd.pipe0.rxrdy_consumed = false; } break; } @@ -432,6 +447,7 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ case PIPE0_STATE_STATUS_IN: TU_ASSERT(dir_in && total_bytes == 0); // only STATUS IN allowed ep_csr->csr0l = MUSB_CSRL0_RXRDYC | MUSB_CSRL0_DATAEND; + _dcd.pipe0.rxrdy_consumed = false; break; case PIPE0_STATE_STATUS_OUT: @@ -465,6 +481,7 @@ static void process_ep0(uint8_t rhport) { ep_csr->csr0l = 0; _dcd.pipe0.state = PIPE0_STATE_IDLE; _dcd.pipe0.deferred_setup_valid = false; + _dcd.pipe0.rxrdy_consumed = false; return; } @@ -474,6 +491,7 @@ static void process_ep0(uint8_t rhport) { ep_csr->csr0l = MUSB_CSRL0_SETENDC; _dcd.pipe0.state = PIPE0_STATE_IDLE; _dcd.pipe0.deferred_setup_valid = false; + _dcd.pipe0.rxrdy_consumed = false; if (!(csrl & MUSB_CSRL0_RXRDY)) { return; /* no SETUP waiting behind it */ } @@ -481,6 +499,9 @@ static void process_ep0(uint8_t rhport) { // Receive Data (Setup or OUT) if (csrl & MUSB_CSRL0_RXRDY) { + if (_dcd.pipe0.rxrdy_consumed) { + return; // stale latched IRQ: this RXRDY's packet was already drained + } switch (_dcd.pipe0.state) { case PIPE0_STATE_IDLE: { tusb_control_request_t req; @@ -498,8 +519,10 @@ static void process_ep0(uint8_t rhport) { tu_hwfifo_read(&musb_regs->fifo[0], _dcd.pipe0.buf, count0, NULL); _dcd.pipe0.remain_wlength -= count0; } + // RXRDY stays set until the next edpt0_xfer arm acks it (NAK flow control): + // edpt0_xfer(DATA OUT) for a mid-stream packet, edpt0_xfer(STATUS IN) for the last. + _dcd.pipe0.rxrdy_consumed = true; if (_dcd.pipe0.remain_wlength == 0) { - // last packet: change state and leave RXRDY for edpt0_xfer(STATUS IN) to ack _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; } dcd_event_xfer_complete(rhport, TU_EP0_OUT, count0, XFER_RESULT_SUCCESS, true); @@ -511,7 +534,8 @@ static void process_ep0(uint8_t rhport) { // - Status IN/OUT finished, its IRQ and the new SETUP IRQ arrive at the same time. // - Data IN finished and status OUT is received, both IRQs and the new SETUP IRQ arrive at the same time. // Save the SETUP; it is replayed only once the old transfer is fully retired — i.e. when usbd has - // made (or already made) its final edpt0_xfer() call for it. + // made (or already made) its final edpt0_xfer() call for it. Until the replayed + // packet is acked, its RXRDY stays parked so a stale latched EP0 IRQ cannot re-process it. case PIPE0_STATE_DATA_IN: case PIPE0_STATE_STATUS_OUT: case PIPE0_STATE_STATUS_OUT_PENDING_XFER: @@ -519,6 +543,7 @@ static void process_ep0(uint8_t rhport) { case PIPE0_STATE_STATUS_IN: { TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &_dcd.pipe0.deferred_setup), ); _dcd.pipe0.deferred_setup_valid = true; + _dcd.pipe0.rxrdy_consumed = true; switch (_dcd.pipe0.state) { case PIPE0_STATE_DATA_IN: @@ -549,7 +574,8 @@ static void process_ep0(uint8_t rhport) { break; default: - // PIPE0_STATE_STATUS_IN: ZLP-sent IRQ coalesced with the SETUP. + // PIPE0_STATE_STATUS_IN: rxrdy_consumed gate + SetupEnd guarantee DATAEND was armed, i.e. + // usbd already made its status call; the ZLP-sent IRQ coalesced with the SETUP. if (_dcd.pipe0.pending_addr) { musb_regs->faddr = _dcd.pipe0.pending_addr; _dcd.pipe0.pending_addr = 0; @@ -633,6 +659,7 @@ static void process_bus_reset(uint8_t rhport) { _dcd.pipe0.xact_len = 0; _dcd.pipe0.remain_wlength = 0; _dcd.pipe0.deferred_setup_valid = false; + _dcd.pipe0.rxrdy_consumed = false; musb->intr_txen = 1; /* Enable only EP0 */ musb->intr_rxen = 0; @@ -708,6 +735,7 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; /* Send STATUS IN ZLP with DATAEND; host ACK fires the confirmation IRQ. */ ep_csr->csr0l = MUSB_CSRL0_RXRDYC | MUSB_CSRL0_DATAEND; + _dcd.pipe0.rxrdy_consumed = false; } // Wake up host -- cgit v1.3.1 From e47eabd49d1838dc2a4eb42b9bd167a1d24d7cf5 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 13 Jun 2026 00:22:28 +0700 Subject: dcd/musb: replay deferred SETUP instead of stalling EP0 dcd_edpt_stall(EP0 OUT) discarded the deferred SETUP and armed SendStall. A deferred SETUP can only exist once the old transfer's status stage was seen on the wire, so the request usbd is rejecting (class callback failing at CONTROL_STAGE_DATA) already succeeded host-side and the hardware already ACKed the next SETUP - the STALL would land on that innocent request, which then fails host-side without any tud callback ever seeing it. Skip the stall and replay the deferred SETUP; the rejected transfer needs no wire-level stall since it is already over. Review follow-up for #3643 (dcd_musb.c l.860 finding). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 0485c4374..15928ec24 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -534,7 +534,7 @@ static void process_ep0(uint8_t rhport) { // - Status IN/OUT finished, its IRQ and the new SETUP IRQ arrive at the same time. // - Data IN finished and status OUT is received, both IRQs and the new SETUP IRQ arrive at the same time. // Save the SETUP; it is replayed only once the old transfer is fully retired — i.e. when usbd has - // made (or already made) its final edpt0_xfer() call for it. Until the replayed + // made (or already made) its final edpt0_xfer()/dcd_edpt_stall() call for it. Until the replayed // packet is acked, its RXRDY stays parked so a stale latched EP0 IRQ cannot re-process it. case PIPE0_STATE_DATA_IN: case PIPE0_STATE_STATUS_OUT: @@ -935,11 +935,17 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epn); if (0 == epn) { - if (ep_addr == TU_EP0_OUT) { /* Ignore EP0 OUT */ + if (ep_addr == TU_EP0_OUT) { /* Ignore EP0 IN */ _dcd.pipe0.state = PIPE0_STATE_IDLE; _dcd.pipe0.buf = NULL; - _dcd.pipe0.deferred_setup_valid = false; - ep_csr->csr0l = MUSB_CSRL0_STALL; + if (_dcd.pipe0.deferred_setup_valid) { + // The transfer being stalled already completed on the wire (a deferred SETUP can only exist + // once its status stage was seen) and the host's next request was already ACKed — SendStall + // would land on that innocent request. Skip the stall and replay the deferred SETUP instead. + pipe0_process_deferred_setup(rhport, ep_csr, false); + } else { + ep_csr->csr0l = MUSB_CSRL0_STALL; + } } } else { const tusb_dir_t ep_dir = tu_edpt_dir(ep_addr); -- cgit v1.3.1 From c8c63c30617d23bb604affcad423acbb11f8d10d Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 13 Jun 2026 23:26:23 +0700 Subject: dcd/musb: clear rxrdy_consumed when stalling EP0 The actual-STALL path (no deferred SETUP) forced EP0 to IDLE but left rxrdy_consumed set if the aborted transfer had parked RXRDY via NAK flow control (e.g. a rejected OUT-data request in DATA_OUT). A subsequent SETUP IRQ would then hit the parked-gate early return and be ignored, relying on SentStall/SetupEnd to clear the flag first. Clear it here so recovery never depends on that ordering. Addresses Copilot review on #3699. Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 15928ec24..5f0ac4546 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -944,6 +944,9 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { // would land on that innocent request. Skip the stall and replay the deferred SETUP instead. pipe0_process_deferred_setup(rhport, ep_csr, false); } else { + // Forcing EP0 to IDLE: any RXRDY parked by the aborted transfer's flow control is stale, + // clear it so the next SETUP IRQ is not gated off. + _dcd.pipe0.rxrdy_consumed = false; ep_csr->csr0l = MUSB_CSRL0_STALL; } } -- cgit v1.3.1 From 3bdf52fc1ba06eb96ca28e9c3656b0d6a59cd201 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 15 Jun 2026 14:53:33 +0700 Subject: dcd/musb: name pipe0_state_t, use local pointer, group struct fields MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pure cleanup, no behavior change: - Extract the EP0 control-transfer state into a named pipe0_state_t typedef instead of an anonymous nested struct, and access it through a local pipe0_state_t* in the functions that touch it repeatedly. - Group the pipe0 fields so the two bools sit together and the larger tusb_control_request_t deferred_setup is last. - Reword the deferral comments: "coalesced" -> "combined". Note: separating the edpt0_xfer DATA_IN/DATA_OUT case (dispatch on state instead of dir_in) was attempted and reverted — it breaks ADI MUSB enumeration. usbd can arm the opposite-direction status while pipe0 is still in a DATA state, and only dir-dispatch routes that correctly; a comment on the combined case records this. Verified: HIL pass on ek_tm4c123gxl and max32666fthr (13/13 each). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 197 +++++++++++++++++++----------------- 1 file changed, 105 insertions(+), 92 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 5f0ac4546..f52ac10e3 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -90,18 +90,21 @@ enum { PIPE0_STATE_STATUS_OUT_PENDING_IRQ, // confirmation IRQ seen (or synthesized) first; edpt0_xfer(STATUS OUT) fires xfer_complete }; +// EP0 control-transfer state (own scalars, not a pipe[] slot). typedef struct { - struct { - uint8_t *buf; // DATA OUT drain target (only valid while EP0 is in DATA OUT stage) - uint16_t xact_len; // chunk length most recently armed via edpt0_xfer; reported in xfer_complete - uint16_t remain_wlength; // bytes remaining in the control transfer's DATA stage - uint8_t state; - uint8_t pending_addr; // new USB address latched by dcd_set_address; applied when STATUS IN completes - tusb_control_request_t deferred_setup; - bool deferred_setup_valid; - bool rxrdy_consumed; // RxPktRdy left set in hw for an already-consumed packet (NAK flow control); - // RXRDY events are stale while set. Cleared when RXRDYC is written. - } pipe0; + uint8_t *buf; // DATA OUT drain target (only valid while EP0 is in DATA OUT stage) + uint16_t xact_len; // chunk length most recently armed via edpt0_xfer; reported in xfer_complete + uint16_t remain_wlength; // bytes remaining in the control transfer's DATA stage + uint8_t state; + uint8_t pending_addr; // new USB address latched by dcd_set_address; applied when STATUS IN completes + bool rxrdy_consumed; // RxPktRdy left set in hw for an already-consumed packet (NAK flow control); + // RXRDY events are stale while set. Cleared when RXRDYC is written. + bool deferred_setup_valid; + tusb_control_request_t deferred_setup; +} pipe0_state_t; + +typedef struct { + pipe0_state_t pipe0; pipe_state_t pipe[MUSB_PIPE_COUNT]; } dcd_data_t; @@ -122,26 +125,27 @@ static bool pipe0_read_setup(musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr, tusb static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, tusb_control_request_t const* req, bool is_isr) { - _dcd.pipe0.remain_wlength = req->wLength; + pipe0_state_t* pipe0 = &_dcd.pipe0; + pipe0->remain_wlength = req->wLength; if (req->wLength == 0) { // Leave RXRDY set; edpt0_xfer(STATUS IN) acks it together with DATAEND. - _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; - _dcd.pipe0.rxrdy_consumed = true; + pipe0->state = PIPE0_STATE_STATUS_IN; + pipe0->rxrdy_consumed = true; } else { if (req->bmRequestType & TUSB_DIR_IN_MASK) { - _dcd.pipe0.state = PIPE0_STATE_DATA_IN; + pipe0->state = PIPE0_STATE_DATA_IN; // On a deferred replay the packet's RXRDY stays parked until the edpt0_xfer(DATA IN) arm // acks it — a stale latched EP0 IRQ in between is gated by rxrdy_consumed. - if (!_dcd.pipe0.rxrdy_consumed) { + if (!pipe0->rxrdy_consumed) { ep_csr->csr0l = MUSB_CSRL0_RXRDYC; } } else { // If OUT (rx) direction, let edpt0_xfer() clear RXRDY when it's ready to receive data. // Deliberate deviation from the databook's canonical flow (ack right after unload), // used as NAK flow control until usbd arms the drain buffer. - _dcd.pipe0.state = PIPE0_STATE_DATA_OUT; - _dcd.pipe0.rxrdy_consumed = true; + pipe0->state = PIPE0_STATE_DATA_OUT; + pipe0->rxrdy_consumed = true; } } @@ -149,12 +153,13 @@ static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, } static void pipe0_process_deferred_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, bool is_isr) { - if (!_dcd.pipe0.deferred_setup_valid) { + pipe0_state_t* pipe0 = &_dcd.pipe0; + if (!pipe0->deferred_setup_valid) { return; } - _dcd.pipe0.deferred_setup_valid = false; - pipe0_start_setup(rhport, ep_csr, &_dcd.pipe0.deferred_setup, is_isr); + pipe0->deferred_setup_valid = false; + pipe0_start_setup(rhport, ep_csr, &pipe0->deferred_setup, is_isr); } // EP0 must not call this — it has its own scalars in dcd_data_t. @@ -414,32 +419,36 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ TU_ASSERT(total_bytes <= CFG_TUD_ENDPOINT0_SIZE); /* EP0 only supports 1 packet per dcd_edpt_xfer()*/ musb_regs_t* musb_regs = MUSB_REGS(rhport); musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0); + pipe0_state_t* pipe0 = &_dcd.pipe0; const unsigned dir_in = tu_edpt_dir(ep_addr); - switch (_dcd.pipe0.state) { + switch (pipe0->state) { + // Combined: usbd can arm the opposite-direction status/ZLP while pipe0 is still in a DATA + // state, so dispatch on the call direction (dir_in), not the state. (Splitting into separate + // DATA_IN/DATA_OUT cases mis-routes those dir != state calls and breaks ADI MUSB.) case PIPE0_STATE_DATA_IN: case PIPE0_STATE_DATA_OUT: { - _dcd.pipe0.xact_len = total_bytes; + pipe0->xact_len = total_bytes; if (dir_in) { // Replayed SETUP keeps its RXRDY parked until here; ack it before loading the shared FIFO. - if (_dcd.pipe0.rxrdy_consumed) { + if (pipe0->rxrdy_consumed) { ep_csr->csr0l = MUSB_CSRL0_RXRDYC; - _dcd.pipe0.rxrdy_consumed = false; + pipe0->rxrdy_consumed = false; } // DATA IN: load FIFO, set TXRDY. Add DATAEND on the last chunk - // (ep0_remain_datalen == 0 after this load) to end the data stage. + // (remain_wlength == 0 after this load) to end the data stage. tu_hwfifo_write(&musb_regs->fifo[0], buffer, total_bytes, NULL); - _dcd.pipe0.remain_wlength -= total_bytes; - if (_dcd.pipe0.remain_wlength == 0) { + pipe0->remain_wlength -= total_bytes; + if (pipe0->remain_wlength == 0) { ep_csr->csr0l = MUSB_CSRL0_TXRDY | MUSB_CSRL0_DATAEND; } else { ep_csr->csr0l = MUSB_CSRL0_TXRDY; } } else { // DATA OUT: arm drain target, ack RXRDY so host can send DATA OUT. - _dcd.pipe0.buf = buffer; + pipe0->buf = buffer; ep_csr->csr0l = MUSB_CSRL0_RXRDYC; - _dcd.pipe0.rxrdy_consumed = false; + pipe0->rxrdy_consumed = false; } break; } @@ -447,19 +456,19 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ case PIPE0_STATE_STATUS_IN: TU_ASSERT(dir_in && total_bytes == 0); // only STATUS IN allowed ep_csr->csr0l = MUSB_CSRL0_RXRDYC | MUSB_CSRL0_DATAEND; - _dcd.pipe0.rxrdy_consumed = false; + pipe0->rxrdy_consumed = false; break; case PIPE0_STATE_STATUS_OUT: TU_ASSERT(!dir_in && total_bytes == 0); // only STATUS OUT allowed // First event of the STATUS OUT pair — wait for the IRQ to fire complete. - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING_XFER; + pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_XFER; break; case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: // Second event — IRQ already arrived, fire complete now. The old transfer is retired here, // so a deferred SETUP can be replayed safely. - _dcd.pipe0.state = PIPE0_STATE_IDLE; + pipe0->state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, ep_addr, 0, XFER_RESULT_SUCCESS, is_isr); pipe0_process_deferred_setup(rhport, ep_csr, is_isr); break; @@ -474,14 +483,15 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ static void process_ep0(uint8_t rhport) { musb_regs_t* musb_regs = MUSB_REGS(rhport); musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0); + pipe0_state_t* pipe0 = &_dcd.pipe0; uint_fast8_t csrl = ep_csr->csr0l; // 21.1.5: SentStall and SetupEnd must be checked before anything else. if (csrl & MUSB_CSRL0_STALLED) { ep_csr->csr0l = 0; - _dcd.pipe0.state = PIPE0_STATE_IDLE; - _dcd.pipe0.deferred_setup_valid = false; - _dcd.pipe0.rxrdy_consumed = false; + pipe0->state = PIPE0_STATE_IDLE; + pipe0->deferred_setup_valid = false; + pipe0->rxrdy_consumed = false; return; } @@ -489,9 +499,9 @@ static void process_ep0(uint8_t rhport) { // Host aborted the current control transfer (new SETUP or premature STATUS). // do nothing, it is probably another setup packet, usbd will reset its state. ep_csr->csr0l = MUSB_CSRL0_SETENDC; - _dcd.pipe0.state = PIPE0_STATE_IDLE; - _dcd.pipe0.deferred_setup_valid = false; - _dcd.pipe0.rxrdy_consumed = false; + pipe0->state = PIPE0_STATE_IDLE; + pipe0->deferred_setup_valid = false; + pipe0->rxrdy_consumed = false; if (!(csrl & MUSB_CSRL0_RXRDY)) { return; /* no SETUP waiting behind it */ } @@ -499,10 +509,10 @@ static void process_ep0(uint8_t rhport) { // Receive Data (Setup or OUT) if (csrl & MUSB_CSRL0_RXRDY) { - if (_dcd.pipe0.rxrdy_consumed) { + if (pipe0->rxrdy_consumed) { return; // stale latched IRQ: this RXRDY's packet was already drained } - switch (_dcd.pipe0.state) { + switch (pipe0->state) { case PIPE0_STATE_IDLE: { tusb_control_request_t req; TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &req), ); @@ -515,22 +525,22 @@ static void process_ep0(uint8_t rhport) { // so the whole packet drains in one shot. const uint16_t count0 = ep_csr->count0; if (count0) { - TU_ASSERT(_dcd.pipe0.buf, ); - tu_hwfifo_read(&musb_regs->fifo[0], _dcd.pipe0.buf, count0, NULL); - _dcd.pipe0.remain_wlength -= count0; + TU_ASSERT(pipe0->buf, ); + tu_hwfifo_read(&musb_regs->fifo[0], pipe0->buf, count0, NULL); + pipe0->remain_wlength -= count0; } // RXRDY stays set until the next edpt0_xfer arm acks it (NAK flow control): // edpt0_xfer(DATA OUT) for a mid-stream packet, edpt0_xfer(STATUS IN) for the last. - _dcd.pipe0.rxrdy_consumed = true; - if (_dcd.pipe0.remain_wlength == 0) { - _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; + pipe0->rxrdy_consumed = true; + if (pipe0->remain_wlength == 0) { + pipe0->state = PIPE0_STATE_STATUS_IN; } dcd_event_xfer_complete(rhport, TU_EP0_OUT, count0, XFER_RESULT_SUCCESS, true); break; } // New SETUP packet arrived while the old control transfer's tail events are still in flight - // (IRQs coalesced under high CPU load), e.g.: + // (IRQs combined under high CPU load), e.g.: // - Status IN/OUT finished, its IRQ and the new SETUP IRQ arrive at the same time. // - Data IN finished and status OUT is received, both IRQs and the new SETUP IRQ arrive at the same time. // Save the SETUP; it is replayed only once the old transfer is fully retired — i.e. when usbd has @@ -541,28 +551,28 @@ static void process_ep0(uint8_t rhport) { case PIPE0_STATE_STATUS_OUT_PENDING_XFER: case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: case PIPE0_STATE_STATUS_IN: { - TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &_dcd.pipe0.deferred_setup), ); - _dcd.pipe0.deferred_setup_valid = true; - _dcd.pipe0.rxrdy_consumed = true; + TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &pipe0->deferred_setup), ); + pipe0->deferred_setup_valid = true; + pipe0->rxrdy_consumed = true; - switch (_dcd.pipe0.state) { + switch (pipe0->state) { case PIPE0_STATE_DATA_IN: - // Coalesced: last DATA IN sent + status OUT done + new SETUP in one csrl read. Fire the + // Combined: last DATA IN sent + status OUT done + new SETUP in one csrl read. Fire the // DATA IN completion and synthesize the missed status confirm; usbd's edpt0_xfer(STATUS OUT) // fires the status completion and replays. - TU_ASSERT(_dcd.pipe0.remain_wlength == 0, ); - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; - dcd_event_xfer_complete(rhport, TU_EP0_IN, _dcd.pipe0.xact_len, XFER_RESULT_SUCCESS, true); + TU_ASSERT(pipe0->remain_wlength == 0, ); + pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; + dcd_event_xfer_complete(rhport, TU_EP0_IN, pipe0->xact_len, XFER_RESULT_SUCCESS, true); break; case PIPE0_STATE_STATUS_OUT: - // Status confirm IRQ coalesced with the SETUP — edpt0_xfer(STATUS OUT) fires complete. - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; + // Status confirm IRQ combined with the SETUP — edpt0_xfer(STATUS OUT) fires complete. + pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; break; case PIPE0_STATE_STATUS_OUT_PENDING_XFER: // edpt0_xfer(STATUS OUT) already called — old transfer retired, complete and replay now. - _dcd.pipe0.state = PIPE0_STATE_IDLE; + pipe0->state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); pipe0_process_deferred_setup(rhport, ep_csr, true); break; @@ -575,12 +585,12 @@ static void process_ep0(uint8_t rhport) { default: // PIPE0_STATE_STATUS_IN: rxrdy_consumed gate + SetupEnd guarantee DATAEND was armed, i.e. - // usbd already made its status call; the ZLP-sent IRQ coalesced with the SETUP. - if (_dcd.pipe0.pending_addr) { - musb_regs->faddr = _dcd.pipe0.pending_addr; - _dcd.pipe0.pending_addr = 0; + // usbd already made its status call; the ZLP-sent IRQ combined with the SETUP. + if (pipe0->pending_addr) { + musb_regs->faddr = pipe0->pending_addr; + pipe0->pending_addr = 0; } - _dcd.pipe0.state = PIPE0_STATE_IDLE; + pipe0->state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, TU_EP0_IN, 0, XFER_RESULT_SUCCESS, true); pipe0_process_deferred_setup(rhport, ep_csr, true); break; @@ -604,25 +614,25 @@ static void process_ep0(uint8_t rhport) { /* When CSRL0 is zero, it means that either * - completion of sending any length packet TxPktRdy clear * - or status stage is complete (ZLP) after DataEnd is set */ - switch (_dcd.pipe0.state) { + switch (pipe0->state) { case PIPE0_STATE_DATA_IN: - // csrl == 0 in DATA state = TXRDY just cleared, i.e. a DATA IN packet was successfully sent. If the just-sent - // packet was the last (DATAEND was set when ep0_remain_datalen hit zero), transition - // to STATUS_OUT to await the host's STATUS-OUT ZLP confirmation IRQ. - if (_dcd.pipe0.remain_wlength == 0) { - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT; + // csrl == 0 in DATA IN = TXRDY just cleared, i.e. a DATA IN packet was successfully sent. If the + // just-sent packet was the last (DATAEND set when remain_wlength hit 0), transition to STATUS_OUT + // to await the host's STATUS-OUT ZLP confirmation IRQ. + if (pipe0->remain_wlength == 0) { + pipe0->state = PIPE0_STATE_STATUS_OUT; } - dcd_event_xfer_complete(rhport, TU_EP0_IN, _dcd.pipe0.xact_len, XFER_RESULT_SUCCESS, true); + dcd_event_xfer_complete(rhport, TU_EP0_IN, pipe0->xact_len, XFER_RESULT_SUCCESS, true); break; case PIPE0_STATE_STATUS_OUT: // First event of the STATUS OUT pair — wait for edpt0_xfer(STATUS OUT) to fire complete. - _dcd.pipe0.state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; + pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; break; case PIPE0_STATE_STATUS_OUT_PENDING_XFER: // Second event — edpt0_xfer(STATUS OUT) already called, fire complete now. - _dcd.pipe0.state = PIPE0_STATE_IDLE; + pipe0->state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); pipe0_process_deferred_setup(rhport, ep_csr, true); break; @@ -632,11 +642,11 @@ static void process_ep0(uint8_t rhport) { break; case PIPE0_STATE_STATUS_IN: - if (_dcd.pipe0.pending_addr) { - musb_regs->faddr = _dcd.pipe0.pending_addr; - _dcd.pipe0.pending_addr = 0; + if (pipe0->pending_addr) { + musb_regs->faddr = pipe0->pending_addr; + pipe0->pending_addr = 0; } - _dcd.pipe0.state = PIPE0_STATE_IDLE; + pipe0->state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, TU_EP0_IN, 0, XFER_RESULT_SUCCESS, true); pipe0_process_deferred_setup(rhport, ep_csr, true); break; @@ -654,12 +664,13 @@ static void process_bus_reset(uint8_t rhport) { alloced_fifo_bytes = CFG_TUD_ENDPOINT0_SIZE; #endif - _dcd.pipe0.state = PIPE0_STATE_IDLE; - _dcd.pipe0.buf = NULL; - _dcd.pipe0.xact_len = 0; - _dcd.pipe0.remain_wlength = 0; - _dcd.pipe0.deferred_setup_valid = false; - _dcd.pipe0.rxrdy_consumed = false; + pipe0_state_t* pipe0 = &_dcd.pipe0; + pipe0->state = PIPE0_STATE_IDLE; + pipe0->buf = NULL; + pipe0->xact_len = 0; + pipe0->remain_wlength = 0; + pipe0->deferred_setup_valid = false; + pipe0->rxrdy_consumed = false; musb->intr_txen = 1; /* Enable only EP0 */ musb->intr_rxen = 0; @@ -729,13 +740,14 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) musb_regs_t* musb_regs = MUSB_REGS(rhport); musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0); - _dcd.pipe0.pending_addr = dev_addr; - _dcd.pipe0.buf = NULL; - _dcd.pipe0.xact_len = 0; - _dcd.pipe0.state = PIPE0_STATE_STATUS_IN; + pipe0_state_t* pipe0 = &_dcd.pipe0; + pipe0->pending_addr = dev_addr; + pipe0->buf = NULL; + pipe0->xact_len = 0; + pipe0->state = PIPE0_STATE_STATUS_IN; /* Send STATUS IN ZLP with DATAEND; host ACK fires the confirmation IRQ. */ ep_csr->csr0l = MUSB_CSRL0_RXRDYC | MUSB_CSRL0_DATAEND; - _dcd.pipe0.rxrdy_consumed = false; + pipe0->rxrdy_consumed = false; } // Wake up host @@ -936,9 +948,10 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { if (0 == epn) { if (ep_addr == TU_EP0_OUT) { /* Ignore EP0 IN */ - _dcd.pipe0.state = PIPE0_STATE_IDLE; - _dcd.pipe0.buf = NULL; - if (_dcd.pipe0.deferred_setup_valid) { + pipe0_state_t* pipe0 = &_dcd.pipe0; + pipe0->state = PIPE0_STATE_IDLE; + pipe0->buf = NULL; + if (pipe0->deferred_setup_valid) { // The transfer being stalled already completed on the wire (a deferred SETUP can only exist // once its status stage was seen) and the host's next request was already ACKed — SendStall // would land on that innocent request. Skip the stall and replay the deferred SETUP instead. @@ -946,7 +959,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { } else { // Forcing EP0 to IDLE: any RXRDY parked by the aborted transfer's flow control is stale, // clear it so the next SETUP IRQ is not gated off. - _dcd.pipe0.rxrdy_consumed = false; + pipe0->rxrdy_consumed = false; ep_csr->csr0l = MUSB_CSRL0_STALL; } } -- cgit v1.3.1 From abc3114d53aee421a0a457ece561ac000ace2c67 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 15 Jun 2026 16:42:10 +0700 Subject: dcd/musb: end EP0 IN data stage on short packet, split DATA case MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A short IN control response (device sends fewer bytes than wLength — e.g. the 18-byte device descriptor answering a 64-byte GET_DESCRIPTOR) left remain_wlength != 0, so the DATA_IN -> STATUS_OUT transition never fired and pipe0 stayed in DATA_IN through the status stage. usbd then armed the status-OUT while state was still DATA_IN. Set DATAEND and transition on the last packet: remain_wlength == 0, or a short packet (incl. a terminating ZLP) which ends the data stage. With state now tracking the stage, split edpt0_xfer's DATA handling into separate DATA_IN / DATA_OUT cases dispatching on state (asserting state == call direction) instead of the combined dir_in branch. Verified: HIL pass on ek_tm4c123gxl and max32666fthr (13/13 each), including the #3643 high-CPU-load IRQ-toggle coalescing stress. Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 49 +++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index f52ac10e3..261ff64e8 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -423,35 +423,31 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ const unsigned dir_in = tu_edpt_dir(ep_addr); switch (pipe0->state) { - // Combined: usbd can arm the opposite-direction status/ZLP while pipe0 is still in a DATA - // state, so dispatch on the call direction (dir_in), not the state. (Splitting into separate - // DATA_IN/DATA_OUT cases mis-routes those dir != state calls and breaks ADI MUSB.) + // DATA stage exits on its last packet, so state matches the call direction here. case PIPE0_STATE_DATA_IN: - case PIPE0_STATE_DATA_OUT: { + TU_ASSERT(dir_in); pipe0->xact_len = total_bytes; - if (dir_in) { - // Replayed SETUP keeps its RXRDY parked until here; ack it before loading the shared FIFO. - if (pipe0->rxrdy_consumed) { - ep_csr->csr0l = MUSB_CSRL0_RXRDYC; - pipe0->rxrdy_consumed = false; - } - // DATA IN: load FIFO, set TXRDY. Add DATAEND on the last chunk - // (remain_wlength == 0 after this load) to end the data stage. - tu_hwfifo_write(&musb_regs->fifo[0], buffer, total_bytes, NULL); - pipe0->remain_wlength -= total_bytes; - if (pipe0->remain_wlength == 0) { - ep_csr->csr0l = MUSB_CSRL0_TXRDY | MUSB_CSRL0_DATAEND; - } else { - ep_csr->csr0l = MUSB_CSRL0_TXRDY; - } - } else { - // DATA OUT: arm drain target, ack RXRDY so host can send DATA OUT. - pipe0->buf = buffer; + if (pipe0->rxrdy_consumed) { // replayed SETUP: ack its parked RXRDY before loading the FIFO ep_csr->csr0l = MUSB_CSRL0_RXRDYC; pipe0->rxrdy_consumed = false; } + tu_hwfifo_write(&musb_regs->fifo[0], buffer, total_bytes, NULL); + pipe0->remain_wlength -= total_bytes; + // DATAEND on the last packet: wLength met, or a short packet (incl. ZLP) ends the data stage. + if (pipe0->remain_wlength == 0 || total_bytes < CFG_TUD_ENDPOINT0_SIZE) { + ep_csr->csr0l = MUSB_CSRL0_TXRDY | MUSB_CSRL0_DATAEND; + } else { + ep_csr->csr0l = MUSB_CSRL0_TXRDY; + } + break; + + case PIPE0_STATE_DATA_OUT: + TU_ASSERT(!dir_in); + pipe0->xact_len = total_bytes; + pipe0->buf = buffer; // arm drain target, ack RXRDY so host can send DATA OUT + ep_csr->csr0l = MUSB_CSRL0_RXRDYC; + pipe0->rxrdy_consumed = false; break; - } case PIPE0_STATE_STATUS_IN: TU_ASSERT(dir_in && total_bytes == 0); // only STATUS IN allowed @@ -616,10 +612,9 @@ static void process_ep0(uint8_t rhport) { * - or status stage is complete (ZLP) after DataEnd is set */ switch (pipe0->state) { case PIPE0_STATE_DATA_IN: - // csrl == 0 in DATA IN = TXRDY just cleared, i.e. a DATA IN packet was successfully sent. If the - // just-sent packet was the last (DATAEND set when remain_wlength hit 0), transition to STATUS_OUT - // to await the host's STATUS-OUT ZLP confirmation IRQ. - if (pipe0->remain_wlength == 0) { + // DATA IN packet sent (TXRDY cleared). On the last packet (DATAEND condition above) move to + // STATUS_OUT to await the host's STATUS-OUT ZLP IRQ. + if (pipe0->remain_wlength == 0 || pipe0->xact_len < CFG_TUD_ENDPOINT0_SIZE) { pipe0->state = PIPE0_STATE_STATUS_OUT; } dcd_event_xfer_complete(rhport, TU_EP0_IN, pipe0->xact_len, XFER_RESULT_SUCCESS, true); -- cgit v1.3.1 From 9562f54f95da485c17192b07a9b2cc21126c8ef1 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 15 Jun 2026 16:43:10 +0700 Subject: dcd/musb: suffix ISR-context process_* handlers with _isr Rename process_ep0/process_epin/process_epout/process_bus_reset (all invoked only from dcd_int_handler) to *_isr, making their ISR context explicit at every call site. pipe0_process_deferred_setup is left as-is since it also runs from task context (dcd_edpt_stall). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 261ff64e8..eb5f83e73 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -299,7 +299,7 @@ static void pipe_write(musb_regs_t* musb_regs, pipe_state_t* pipe, uint8_t epnum // Called from the TX interrupt. If the last queued packet finished the transfer, // signal completion; otherwise queue the next packet. -static void process_epin(uint8_t rhport, musb_regs_t *musb_regs, uint8_t epnum) { +static void process_epin_isr(uint8_t rhport, musb_regs_t *musb_regs, uint8_t epnum) { musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epnum); const uint_fast8_t csrl = ep_csr->tx_csrl; if (csrl & MUSB_TXCSRL1_STALLED) { @@ -329,7 +329,7 @@ static void process_epin(uint8_t rhport, musb_regs_t *musb_regs, uint8_t epnum) // Drain one packet from the Rx FIFO into pipe->buf/fifo, update pipe state, and // release the FIFO slot by clearing RXRDY. return true if short packet static bool pipe_read(musb_regs_t* musb_regs, pipe_state_t* pipe, uint8_t epnum) { - musb_ep_csr_t* ep_csr = &musb_regs->indexed_csr; // index already set in process_epout() + musb_ep_csr_t* ep_csr = &musb_regs->indexed_csr; // index already set in process_epout_isr() const uint16_t mps = ep_csr->rx_maxp & MUSB_RXMAXP_PACKET_SIZE_M; const uint16_t rx_count = ep_csr->rx_count; const uint16_t xact_len = tu_min16(tu_min16(pipe->remaining, mps), rx_count); @@ -348,7 +348,7 @@ static bool pipe_read(musb_regs_t* musb_regs, pipe_state_t* pipe, uint8_t epnum) return (xact_len < mps); } -static void process_epout(uint8_t rhport, musb_regs_t *musb_regs, uint8_t epnum, bool is_isr) { +static void process_epout_isr(uint8_t rhport, musb_regs_t *musb_regs, uint8_t epnum, bool is_isr) { musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epnum); if (ep_csr->rx_csrl & MUSB_RXCSRL1_STALLED) { ep_csr->rx_csrl &= ~(MUSB_RXCSRL1_STALLED | MUSB_RXCSRL1_OVER); @@ -403,13 +403,13 @@ static bool edpt_n_xfer(uint8_t rhport, uint8_t ep_addr, void *buffer, uint16_t if (dir_in) { pipe_write(musb_regs, pipe, epnum); } else { - // Re-enable Rx interrupt (may have been masked by the no-buffer path in process_epout) + // Re-enable Rx interrupt (may have been masked by the no-buffer path in process_epout_isr) musb_regs->intr_rxen |= (uint16_t)TU_BIT(epnum); // Drain any packet staged in the Rx FIFO from a prior no-buffer interrupt. - // process_epout() fires dcd_event_xfer_complete() itself if the drain completes. + // process_epout_isr() fires dcd_event_xfer_complete() itself if the drain completes. if (ep_csr->rx_csrl & MUSB_RXCSRL1_RXRDY) { - process_epout(rhport, musb_regs, epnum, is_isr); + process_epout_isr(rhport, musb_regs, epnum, is_isr); } } return true; @@ -476,7 +476,7 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ } // 21.1.5: endpoint 0 service routine as peripheral -static void process_ep0(uint8_t rhport) { +static void process_ep0_isr(uint8_t rhport) { musb_regs_t* musb_regs = MUSB_REGS(rhport); musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0); pipe0_state_t* pipe0 = &_dcd.pipe0; @@ -652,7 +652,7 @@ static void process_ep0(uint8_t rhport) { // Upon BUS RESET is detected, hardware havs already done: // faddr = 0, index = 0, flushes all ep fifos, clears all ep csr, enabled all ep interrupts -static void process_bus_reset(uint8_t rhport) { +static void process_bus_reset_isr(uint8_t rhport) { musb_regs_t* musb = MUSB_REGS(rhport); #if MUSB_CFG_DYNAMIC_FIFO @@ -728,7 +728,7 @@ void dcd_int_disable(uint8_t rhport) { } // Receive Set Address request. Stash the new address here; hardware faddr is -// latched from pending_addr in process_ep0 once the STATUS IN completes (per +// latched from pending_addr in process_ep0_isr once the STATUS IN completes (per // USB spec, address must only take effect after the status stage). void dcd_set_address(uint8_t rhport, uint8_t dev_addr) { @@ -1008,7 +1008,7 @@ void dcd_int_handler(uint8_t rhport) { dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); } if (intr_usb & MUSB_IS_RESET) { - process_bus_reset(rhport); + process_bus_reset_isr(rhport); } if (intr_usb & MUSB_IS_RESUME) { dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); @@ -1022,9 +1022,9 @@ void dcd_int_handler(uint8_t rhport) { while (intr_tx) { const unsigned epnum = __builtin_ctz(intr_tx); if (epnum == 0) { - process_ep0(rhport); // EP0 has its own state machine (control transfers) + process_ep0_isr(rhport); // EP0 has its own state machine (control transfers) } else { - process_epin(rhport, musb_regs, epnum); + process_epin_isr(rhport, musb_regs, epnum); } intr_tx &= ~TU_BIT(epnum); @@ -1039,7 +1039,7 @@ void dcd_int_handler(uint8_t rhport) { intr_rx &= musb_regs->intr_rxen; /* Clear disabled interrupts */ while (intr_rx) { unsigned const epnum = __builtin_ctz(intr_rx); - process_epout(rhport, musb_regs, epnum, true); + process_epout_isr(rhport, musb_regs, epnum, true); intr_rx &= ~TU_BIT(epnum); // Double packet endpoint: RxPktRdy is set and interrupt is generated immediately if 2nd packet is received -- cgit v1.3.1 From d4eeaf10cb1a95b6b74e18cd933c6320d31c2031 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 15 Jun 2026 16:48:40 +0700 Subject: dcd/musb: extract pipe0_process_status_isr() to de-dup EP0 tail paths The deferral (RXRDY-combined) and csrl==0 tail paths in process_ep0_isr ran the same per-state status-stage logic. Move all of it into one pipe0_process_status_isr() helper covering every state including DATA_IN, which picks STATUS_OUT vs STATUS_OUT_PENDING_IRQ from deferred_setup_valid (a deferred SETUP means the status confirm was coalesced with it). Both callers now just invoke the helper; the deferral path saves the SETUP and sets deferred_setup_valid first. Also drops the deferral path's TU_ASSERT(remain_wlength == 0), which was wrong for a short last DATA-IN packet, and renames pipe0_process_deferred_setup -> pipe0_try_deferred_setup (it no-ops when nothing is deferred). Verified: HIL pass on ek_tm4c123gxl and max32666fthr (13/13 each), including the #3643 high-CPU-load IRQ-toggle coalescing stress. Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 149 ++++++++++++++---------------------- 1 file changed, 58 insertions(+), 91 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index eb5f83e73..e769b08a5 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -152,7 +152,8 @@ static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, dcd_event_setup_received(rhport, (const uint8_t *) req, is_isr); } -static void pipe0_process_deferred_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, bool is_isr) { +// Replay a previously deferred SETUP, if any. +static void pipe0_try_deferred_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, bool is_isr) { pipe0_state_t* pipe0 = &_dcd.pipe0; if (!pipe0->deferred_setup_valid) { return; @@ -466,7 +467,7 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ // so a deferred SETUP can be replayed safely. pipe0->state = PIPE0_STATE_IDLE; dcd_event_xfer_complete(rhport, ep_addr, 0, XFER_RESULT_SUCCESS, is_isr); - pipe0_process_deferred_setup(rhport, ep_csr, is_isr); + pipe0_try_deferred_setup(rhport, ep_csr, is_isr); break; default: break; @@ -475,6 +476,52 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ return true; } +// Advance EP0's status-stage state machine on a tail event: the csrl==0 confirmation IRQ, or such a +// confirmation combined with a new SETUP (caller sets deferred_setup_valid first). ISR context only. +static void pipe0_process_status_isr(uint8_t rhport, musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr) { + pipe0_state_t* pipe0 = &_dcd.pipe0; + switch (pipe0->state) { + case PIPE0_STATE_DATA_IN: + if (pipe0->remain_wlength == 0 || pipe0->xact_len < CFG_TUD_ENDPOINT0_SIZE) { // last DATA IN packet + if (pipe0->deferred_setup_valid) { + pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; // status confirm coalesced with deferred SETUP + } else { + pipe0->state = PIPE0_STATE_STATUS_OUT; // await host's STATUS-OUT ZLP IRQ + } + } + dcd_event_xfer_complete(rhport, TU_EP0_IN, pipe0->xact_len, XFER_RESULT_SUCCESS, true); + break; + + case PIPE0_STATE_STATUS_OUT: + // Confirmation seen — await edpt0_xfer(STATUS OUT) to fire complete. + pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; + break; + + case PIPE0_STATE_STATUS_OUT_PENDING_XFER: + // edpt0_xfer(STATUS OUT) already called — fire complete and replay now. + pipe0->state = PIPE0_STATE_IDLE; + dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); + pipe0_try_deferred_setup(rhport, ep_csr, true); + break; + + case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: + // Confirmation already accounted for — the pairing edpt0_xfer(STATUS OUT) fires complete. + break; + + case PIPE0_STATE_STATUS_IN: + if (pipe0->pending_addr) { + musb_regs->faddr = pipe0->pending_addr; + pipe0->pending_addr = 0; + } + pipe0->state = PIPE0_STATE_IDLE; + dcd_event_xfer_complete(rhport, TU_EP0_IN, 0, XFER_RESULT_SUCCESS, true); + pipe0_try_deferred_setup(rhport, ep_csr, true); + break; + + default: break; + } +} + // 21.1.5: endpoint 0 service routine as peripheral static void process_ep0_isr(uint8_t rhport) { musb_regs_t* musb_regs = MUSB_REGS(rhport); @@ -535,64 +582,21 @@ static void process_ep0_isr(uint8_t rhport) { break; } - // New SETUP packet arrived while the old control transfer's tail events are still in flight - // (IRQs combined under high CPU load), e.g.: - // - Status IN/OUT finished, its IRQ and the new SETUP IRQ arrive at the same time. - // - Data IN finished and status OUT is received, both IRQs and the new SETUP IRQ arrive at the same time. - // Save the SETUP; it is replayed only once the old transfer is fully retired — i.e. when usbd has - // made (or already made) its final edpt0_xfer()/dcd_edpt_stall() call for it. Until the replayed - // packet is acked, its RXRDY stays parked so a stale latched EP0 IRQ cannot re-process it. + // New SETUP arrived while the old control transfer's tail events are still in flight (IRQs + // combined under high CPU load): the old transfer's status confirm and this SETUP land together. case PIPE0_STATE_DATA_IN: case PIPE0_STATE_STATUS_OUT: case PIPE0_STATE_STATUS_OUT_PENDING_XFER: case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: - case PIPE0_STATE_STATUS_IN: { + case PIPE0_STATE_STATUS_IN: + // Save it, then finish the old transfer's tail event; deferred_setup_valid makes + // pipe0_process_status_isr() synthesize the coalesced status confirm and replay the SETUP + // once the old transfer is retired. Its RXRDY stays parked so a stale IRQ can't re-process it. TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &pipe0->deferred_setup), ); pipe0->deferred_setup_valid = true; pipe0->rxrdy_consumed = true; - - switch (pipe0->state) { - case PIPE0_STATE_DATA_IN: - // Combined: last DATA IN sent + status OUT done + new SETUP in one csrl read. Fire the - // DATA IN completion and synthesize the missed status confirm; usbd's edpt0_xfer(STATUS OUT) - // fires the status completion and replays. - TU_ASSERT(pipe0->remain_wlength == 0, ); - pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; - dcd_event_xfer_complete(rhport, TU_EP0_IN, pipe0->xact_len, XFER_RESULT_SUCCESS, true); - break; - - case PIPE0_STATE_STATUS_OUT: - // Status confirm IRQ combined with the SETUP — edpt0_xfer(STATUS OUT) fires complete. - pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; - break; - - case PIPE0_STATE_STATUS_OUT_PENDING_XFER: - // edpt0_xfer(STATUS OUT) already called — old transfer retired, complete and replay now. - pipe0->state = PIPE0_STATE_IDLE; - dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); - pipe0_process_deferred_setup(rhport, ep_csr, true); - break; - - case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: - // usbd has not called edpt0_xfer(STATUS OUT) for the old transfer yet — only hold the - // SETUP. Replaying here would let that still-outstanding call land in the replayed - // transfer's state and corrupt it (e.g. NULL DATA OUT drain buffer). - break; - - default: - // PIPE0_STATE_STATUS_IN: rxrdy_consumed gate + SetupEnd guarantee DATAEND was armed, i.e. - // usbd already made its status call; the ZLP-sent IRQ combined with the SETUP. - if (pipe0->pending_addr) { - musb_regs->faddr = pipe0->pending_addr; - pipe0->pending_addr = 0; - } - pipe0->state = PIPE0_STATE_IDLE; - dcd_event_xfer_complete(rhport, TU_EP0_IN, 0, XFER_RESULT_SUCCESS, true); - pipe0_process_deferred_setup(rhport, ep_csr, true); - break; - } + pipe0_process_status_isr(rhport, musb_regs, ep_csr); break; - } default: break; } @@ -610,44 +614,7 @@ static void process_ep0_isr(uint8_t rhport) { /* When CSRL0 is zero, it means that either * - completion of sending any length packet TxPktRdy clear * - or status stage is complete (ZLP) after DataEnd is set */ - switch (pipe0->state) { - case PIPE0_STATE_DATA_IN: - // DATA IN packet sent (TXRDY cleared). On the last packet (DATAEND condition above) move to - // STATUS_OUT to await the host's STATUS-OUT ZLP IRQ. - if (pipe0->remain_wlength == 0 || pipe0->xact_len < CFG_TUD_ENDPOINT0_SIZE) { - pipe0->state = PIPE0_STATE_STATUS_OUT; - } - dcd_event_xfer_complete(rhport, TU_EP0_IN, pipe0->xact_len, XFER_RESULT_SUCCESS, true); - break; - - case PIPE0_STATE_STATUS_OUT: - // First event of the STATUS OUT pair — wait for edpt0_xfer(STATUS OUT) to fire complete. - pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; - break; - - case PIPE0_STATE_STATUS_OUT_PENDING_XFER: - // Second event — edpt0_xfer(STATUS OUT) already called, fire complete now. - pipe0->state = PIPE0_STATE_IDLE; - dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true); - pipe0_process_deferred_setup(rhport, ep_csr, true); - break; - - case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: - // Stale duplicate of the status confirm — already accounted for; edpt0_xfer fires complete. - break; - - case PIPE0_STATE_STATUS_IN: - if (pipe0->pending_addr) { - musb_regs->faddr = pipe0->pending_addr; - pipe0->pending_addr = 0; - } - pipe0->state = PIPE0_STATE_IDLE; - dcd_event_xfer_complete(rhport, TU_EP0_IN, 0, XFER_RESULT_SUCCESS, true); - pipe0_process_deferred_setup(rhport, ep_csr, true); - break; - - default: break; - } + pipe0_process_status_isr(rhport, musb_regs, ep_csr); } // Upon BUS RESET is detected, hardware havs already done: @@ -950,7 +917,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { // The transfer being stalled already completed on the wire (a deferred SETUP can only exist // once its status stage was seen) and the host's next request was already ACKed — SendStall // would land on that innocent request. Skip the stall and replay the deferred SETUP instead. - pipe0_process_deferred_setup(rhport, ep_csr, false); + pipe0_try_deferred_setup(rhport, ep_csr, false); } else { // Forcing EP0 to IDLE: any RXRDY parked by the aborted transfer's flow control is stale, // clear it so the next SETUP IRQ is not gated off. -- cgit v1.3.1 From 3d9468152c44148c6881fb3f30ff3dae91a09b68 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 15 Jun 2026 22:19:34 +0700 Subject: dcd/musb: read EP0 SETUP into uint32_t[2], drop the double copy pipe0_read_setup() copied the FIFO into a local union, then copied that into the caller's struct. Read the two FIFO words straight into the caller's uint32_t[2] (one copy) and cast to tusb_control_request_t* in pipe0_start_setup(). pipe0.deferred_setup becomes uint32_t[2] so the deferral path reads directly into it as well. Verified: HIL pass on ek_tm4c123gxl and max32666fthr (13/13 each). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index e769b08a5..5c2b80cf6 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -100,7 +100,7 @@ typedef struct { bool rxrdy_consumed; // RxPktRdy left set in hw for an already-consumed packet (NAK flow control); // RXRDY events are stale while set. Cleared when RXRDYC is written. bool deferred_setup_valid; - tusb_control_request_t deferred_setup; + uint32_t deferred_setup[2]; // raw SETUP words, replayed via pipe0_start_setup } pipe0_state_t; typedef struct { @@ -110,21 +110,17 @@ typedef struct { static dcd_data_t _dcd; -// Drain a SETUP packet (8 bytes) from the EP0 FIFO. Does not ack RxPktRdy. -static bool pipe0_read_setup(musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr, tusb_control_request_t* req) { +// Read the 8-byte SETUP packet (2 words) from the EP0 FIFO into setup[]. Does not ack RxPktRdy. +static bool pipe0_read_setup(musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr, uint32_t setup[2]) { TU_ASSERT(sizeof(tusb_control_request_t) == ep_csr->count0); - union { - tusb_control_request_t req; - uint32_t u32[2]; - } setup_packet; - setup_packet.u32[0] = musb_regs->fifo[0]; - setup_packet.u32[1] = musb_regs->fifo[0]; - *req = setup_packet.req; + setup[0] = musb_regs->fifo[0]; + setup[1] = musb_regs->fifo[0]; return true; } static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, - tusb_control_request_t const* req, bool is_isr) { + const uint32_t setup[2], bool is_isr) { + tusb_control_request_t const* req = (tusb_control_request_t const*) setup; pipe0_state_t* pipe0 = &_dcd.pipe0; pipe0->remain_wlength = req->wLength; @@ -149,7 +145,7 @@ static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, } } - dcd_event_setup_received(rhport, (const uint8_t *) req, is_isr); + dcd_event_setup_received(rhport, (const uint8_t *) setup, is_isr); } // Replay a previously deferred SETUP, if any. @@ -160,7 +156,7 @@ static void pipe0_try_deferred_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, bool } pipe0->deferred_setup_valid = false; - pipe0_start_setup(rhport, ep_csr, &pipe0->deferred_setup, is_isr); + pipe0_start_setup(rhport, ep_csr, pipe0->deferred_setup, is_isr); } // EP0 must not call this — it has its own scalars in dcd_data_t. @@ -557,9 +553,9 @@ static void process_ep0_isr(uint8_t rhport) { } switch (pipe0->state) { case PIPE0_STATE_IDLE: { - tusb_control_request_t req; - TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &req), ); - pipe0_start_setup(rhport, ep_csr, &req, true); + uint32_t setup[2]; + TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, setup), ); + pipe0_start_setup(rhport, ep_csr, setup, true); break; } @@ -592,7 +588,7 @@ static void process_ep0_isr(uint8_t rhport) { // Save it, then finish the old transfer's tail event; deferred_setup_valid makes // pipe0_process_status_isr() synthesize the coalesced status confirm and replay the SETUP // once the old transfer is retired. Its RXRDY stays parked so a stale IRQ can't re-process it. - TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, &pipe0->deferred_setup), ); + TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, pipe0->deferred_setup), ); pipe0->deferred_setup_valid = true; pipe0->rxrdy_consumed = true; pipe0_process_status_isr(rhport, musb_regs, ep_csr); -- cgit v1.3.1 From f1080e158aeec31faee0f3371d2d5c6f624dd4f4 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 15 Jun 2026 22:50:01 +0700 Subject: dcd/musb: harden EP0 DATA_OUT against short packet and host overrun Mirror the IN-side short-packet fix on the OUT drain: end the data stage (-> STATUS_IN) when wLength is received OR a short OUT packet (count0 < CFG_TUD_ENDPOINT0_SIZE) signals the host's end-of-data, not only when remain_wlength hits exactly 0. Also clamp the remain_wlength subtraction so a host that overruns wLength can't underflow it and strand the transfer. Without this, a control-OUT whose host sends fewer bytes than wLength left pipe0 in DATA_OUT; usbd then armed STATUS IN and tripped the split's TU_ASSERT(!dir_in). Found by /code-review; conformant hosts send exactly wLength so HIL was already green. Verified: HIL pass on ek_tm4c123gxl and max32666fthr (13/13 each). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 5c2b80cf6..0a2df3e71 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -566,12 +566,13 @@ static void process_ep0_isr(uint8_t rhport) { if (count0) { TU_ASSERT(pipe0->buf, ); tu_hwfifo_read(&musb_regs->fifo[0], pipe0->buf, count0, NULL); - pipe0->remain_wlength -= count0; + pipe0->remain_wlength -= tu_min16(count0, pipe0->remain_wlength); // clamp: host may overrun } // RXRDY stays set until the next edpt0_xfer arm acks it (NAK flow control): // edpt0_xfer(DATA OUT) for a mid-stream packet, edpt0_xfer(STATUS IN) for the last. pipe0->rxrdy_consumed = true; - if (pipe0->remain_wlength == 0) { + // Last packet: wLength received, or a short packet (host's end-of-data). + if (pipe0->remain_wlength == 0 || count0 < CFG_TUD_ENDPOINT0_SIZE) { pipe0->state = PIPE0_STATE_STATUS_IN; } dcd_event_xfer_complete(rhport, TU_EP0_OUT, count0, XFER_RESULT_SUCCESS, true); -- cgit v1.3.1 From 148fabb96b16fe0899004ba71d6447ec3995cf55 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 15 Jun 2026 23:24:17 +0700 Subject: dcd/musb: rename pipe0_process_status_isr -> pipe0_process_xfer_state_isr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The helper advances the whole EP0 control state machine on a completion/confirmation IRQ — it dispatches on pipe0->state and also fires the DATA_IN completion, not just the status stage — so "process_status" undersold it. Matches the process_*_isr family. Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 0a2df3e71..e8146f7a7 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -474,7 +474,7 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ // Advance EP0's status-stage state machine on a tail event: the csrl==0 confirmation IRQ, or such a // confirmation combined with a new SETUP (caller sets deferred_setup_valid first). ISR context only. -static void pipe0_process_status_isr(uint8_t rhport, musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr) { +static void pipe0_process_xfer_state_isr(uint8_t rhport, musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr) { pipe0_state_t* pipe0 = &_dcd.pipe0; switch (pipe0->state) { case PIPE0_STATE_DATA_IN: @@ -587,12 +587,12 @@ static void process_ep0_isr(uint8_t rhport) { case PIPE0_STATE_STATUS_OUT_PENDING_IRQ: case PIPE0_STATE_STATUS_IN: // Save it, then finish the old transfer's tail event; deferred_setup_valid makes - // pipe0_process_status_isr() synthesize the coalesced status confirm and replay the SETUP + // pipe0_process_xfer_state_isr() synthesize the coalesced status confirm and replay the SETUP // once the old transfer is retired. Its RXRDY stays parked so a stale IRQ can't re-process it. TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, pipe0->deferred_setup), ); pipe0->deferred_setup_valid = true; pipe0->rxrdy_consumed = true; - pipe0_process_status_isr(rhport, musb_regs, ep_csr); + pipe0_process_xfer_state_isr(rhport, musb_regs, ep_csr); break; default: break; @@ -611,7 +611,7 @@ static void process_ep0_isr(uint8_t rhport) { /* When CSRL0 is zero, it means that either * - completion of sending any length packet TxPktRdy clear * - or status stage is complete (ZLP) after DataEnd is set */ - pipe0_process_status_isr(rhport, musb_regs, ep_csr); + pipe0_process_xfer_state_isr(rhport, musb_regs, ep_csr); } // Upon BUS RESET is detected, hardware havs already done: -- cgit v1.3.1 From ba3b2453e7cbf3572663dd1b7eadafdcc6b0a912 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 16 Jun 2026 11:09:40 +0700 Subject: dcd/musb: extract pipe0_data_stage_done() and fix two EP0 comments Cleanup from a code-review pass, no behavior change: - Replace the open-coded "last DATA packet" test (remain_wlength == 0 || len < CFG_TUD_ENDPOINT0_SIZE), duplicated in the edpt0_xfer DATA IN arm, pipe0_process_xfer_state_isr, and the DATA OUT drain, with one inline pipe0_data_stage_done() so IN and OUT can't drift. - Correct the xact_len comment (only the IN path reports it; OUT reports count0) and the dcd_edpt_stall comment (a deferred SETUP means the old transfer ended on the wire, not that its status stage was "seen"). Co-Authored-By: Claude Fable 5 --- src/portable/mentor/musb/dcd_musb.c | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index e8146f7a7..1d1280bf4 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -93,7 +93,7 @@ enum { // EP0 control-transfer state (own scalars, not a pipe[] slot). typedef struct { uint8_t *buf; // DATA OUT drain target (only valid while EP0 is in DATA OUT stage) - uint16_t xact_len; // chunk length most recently armed via edpt0_xfer; reported in xfer_complete + uint16_t xact_len; // DATA IN chunk length armed via edpt0_xfer; reported in its xfer_complete (OUT reports count0) uint16_t remain_wlength; // bytes remaining in the control transfer's DATA stage uint8_t state; uint8_t pending_addr; // new USB address latched by dcd_set_address; applied when STATUS IN completes @@ -159,6 +159,11 @@ static void pipe0_try_deferred_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, bool pipe0_start_setup(rhport, ep_csr, pipe0->deferred_setup, is_isr); } +// Last DATA packet: wLength satisfied, or a short packet (incl. ZLP) ends the stage. +TU_ATTR_ALWAYS_INLINE static inline bool pipe0_data_stage_done(uint16_t xfer_len) { + return _dcd.pipe0.remain_wlength == 0 || xfer_len < CFG_TUD_ENDPOINT0_SIZE; +} + // EP0 must not call this — it has its own scalars in dcd_data_t. TU_ATTR_ALWAYS_INLINE static inline pipe_state_t* pipe_get(uint8_t epnum, tusb_dir_t epdir) { size_t idx = epnum - 1u; @@ -430,8 +435,8 @@ static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_ } tu_hwfifo_write(&musb_regs->fifo[0], buffer, total_bytes, NULL); pipe0->remain_wlength -= total_bytes; - // DATAEND on the last packet: wLength met, or a short packet (incl. ZLP) ends the data stage. - if (pipe0->remain_wlength == 0 || total_bytes < CFG_TUD_ENDPOINT0_SIZE) { + // Add DATAEND on the last packet to end the data stage. + if (pipe0_data_stage_done(total_bytes)) { ep_csr->csr0l = MUSB_CSRL0_TXRDY | MUSB_CSRL0_DATAEND; } else { ep_csr->csr0l = MUSB_CSRL0_TXRDY; @@ -478,7 +483,7 @@ static void pipe0_process_xfer_state_isr(uint8_t rhport, musb_regs_t* musb_regs, pipe0_state_t* pipe0 = &_dcd.pipe0; switch (pipe0->state) { case PIPE0_STATE_DATA_IN: - if (pipe0->remain_wlength == 0 || pipe0->xact_len < CFG_TUD_ENDPOINT0_SIZE) { // last DATA IN packet + if (pipe0_data_stage_done(pipe0->xact_len)) { if (pipe0->deferred_setup_valid) { pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; // status confirm coalesced with deferred SETUP } else { @@ -571,8 +576,7 @@ static void process_ep0_isr(uint8_t rhport) { // RXRDY stays set until the next edpt0_xfer arm acks it (NAK flow control): // edpt0_xfer(DATA OUT) for a mid-stream packet, edpt0_xfer(STATUS IN) for the last. pipe0->rxrdy_consumed = true; - // Last packet: wLength received, or a short packet (host's end-of-data). - if (pipe0->remain_wlength == 0 || count0 < CFG_TUD_ENDPOINT0_SIZE) { + if (pipe0_data_stage_done(count0)) { pipe0->state = PIPE0_STATE_STATUS_IN; } dcd_event_xfer_complete(rhport, TU_EP0_OUT, count0, XFER_RESULT_SUCCESS, true); @@ -911,9 +915,8 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { pipe0->state = PIPE0_STATE_IDLE; pipe0->buf = NULL; if (pipe0->deferred_setup_valid) { - // The transfer being stalled already completed on the wire (a deferred SETUP can only exist - // once its status stage was seen) and the host's next request was already ACKed — SendStall - // would land on that innocent request. Skip the stall and replay the deferred SETUP instead. + // A deferred SETUP means the stalled transfer already ended on the wire and the host's next + // request was ACKed — SendStall would hit that innocent request. Replay it instead of stalling. pipe0_try_deferred_setup(rhport, ep_csr, false); } else { // Forcing EP0 to IDLE: any RXRDY parked by the aborted transfer's flow control is stale, -- cgit v1.3.1 From 7b791916a702c28f8f39e9bfc5eb8455d0942865 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Tue, 16 Jun 2026 17:36:17 +0700 Subject: device: clamp EP0 OUT data copy to the control transfer buffer (#3705) * device: clamp EP0 OUT data copy to the control transfer buffer usbd_control_xfer_cb() copied xferred_bytes from the EP0 bounce buffer into the requester's buffer with no bound. A non-compliant host that sends an OUT data packet larger than the control transfer's data_len (= min(len, wLength), the buffer capacity) would overflow that buffer and over-count total_xferred. Clamp xferred_bytes to the remaining buffer space before the memcpy and accounting. --- src/device/usbd.c | 2 ++ test/unit-test/test/device/usbd/test_usbd.c | 52 ++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/device/usbd.c b/src/device/usbd.c index 55ad330c1..f87b63111 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -914,6 +914,8 @@ static bool usbd_control_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t // Data stage progress if (ctrl_xfer->request.bmRequestType_bit.direction == TUSB_DIR_OUT) { TU_VERIFY(ctrl_xfer->buffer); + // Clamp host overrun to remaining capacity (data_len) so memcpy can't overflow the caller buffer + xferred_bytes = tu_min32(xferred_bytes, ctrl_xfer->data_len - ctrl_xfer->total_xferred); if (ctrl_xfer->buffer != _ctrl_epbuf.buf) { memcpy(ctrl_xfer->buffer, _ctrl_epbuf.buf, xferred_bytes); } diff --git a/test/unit-test/test/device/usbd/test_usbd.c b/test/unit-test/test/device/usbd/test_usbd.c index 3a2cf3217..7f3c3f5b2 100644 --- a/test/unit-test/test/device/usbd/test_usbd.c +++ b/test/unit-test/test/device/usbd/test_usbd.c @@ -29,7 +29,7 @@ #include "tusb_fifo.h" #include "tusb.h" #include "usbd.h" -TEST_SOURCE_FILE("usbd_control.c") +TEST_SOURCE_FILE("usbd.c") // Mock File #include "mock_dcd.h" @@ -100,6 +100,16 @@ tusb_control_request_t const req_get_desc_configuration = .wLength = 256 }; +// Vendor OUT control request (direction OUT, type Vendor, recipient Device), 8-byte data stage +tusb_control_request_t const req_vendor_out = +{ + .bmRequestType = 0x40, + .bRequest = 0x01, + .wValue = 0x0000, + .wIndex = 0x0000, + .wLength = 8 +}; + uint8_t const* desc_device; uint8_t const* desc_configuration; @@ -120,6 +130,19 @@ uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { return NULL; } +// Backing buffer for the vendor OUT data stage. Sized to EP0 max packet so an (untested) regression +// that drops the clamp can't corrupt memory here; the regression is caught by the expectation below. +static uint8_t vendor_out_buf[CFG_TUD_ENDPOINT0_SIZE]; + +bool tud_vendor_control_xfer_cb(uint8_t rhport_, uint8_t stage, tusb_control_request_t const* request) { + (void) request; + if (stage == CONTROL_STAGE_SETUP) { + // Offer only an 8-byte capacity even though the data stage may receive a larger packet + return tud_control_xfer(rhport_, request, vendor_out_buf, 8); + } + return true; +} + void setUp(void) { dcd_int_disable_Ignore(); dcd_int_enable_Ignore(); @@ -246,3 +269,30 @@ void test_usbd_control_in_zlp(void) tud_task(); } + +//--------------------------------------------------------------------+ +// Control OUT data stage host overrun +//--------------------------------------------------------------------+ + +// A non-compliant host sends an OUT data packet larger than the buffer the class offered: +// wLength = 8, but the DCD reports a full CFG_TUD_ENDPOINT0_SIZE packet. usbd must clamp the +// copy/accounting to the 8-byte capacity so total_xferred reaches wLength, ends the data stage, +// and queues the IN status stage. Without the clamp total_xferred overshoots wLength and usbd +// re-arms an OUT data packet (EDPT_CTRL_OUT) instead, failing the EDPT_CTRL_IN expectation below. +void test_usbd_control_out_overrun_clamp(void) +{ + dcd_event_setup_received(rhport, (uint8_t*) &req_vendor_out, false); + + // Data stage: usbd arms an 8-byte OUT into its internal bounce buffer (buffer ptr is internal) + dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_OUT, NULL, 8, false, true); + dcd_edpt_xfer_IgnoreArg_buffer(); + // Host overrun: DCD reports a full max packet, larger than the 8-byte capacity + dcd_event_xfer_complete(rhport, EDPT_CTRL_OUT, CFG_TUD_ENDPOINT0_SIZE, XFER_RESULT_SUCCESS, false); + + // Clamp -> total_xferred == wLength -> data stage done -> IN status stage queued + dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_IN, NULL, 0, false, true); + dcd_event_xfer_complete(rhport, EDPT_CTRL_IN, 0, 0, false); + dcd_edpt0_status_complete_ExpectWithArray(rhport, &req_vendor_out, 1); + + tud_task(); +} -- cgit v1.3.1 From ad8cbc4668ab8d92e2eebb834c230e9d18ad8e57 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 18 Jun 2026 10:58:58 +0700 Subject: dcd/ch32_usbfs: support CH32V103 combined endpoint control register CH32V103 uses the older USBFS IP: a single combined UEPn_CTRL register per endpoint (IN response in bits [1:0], OUT response in [3:2], shared auto-toggle, separate IN/OUT toggles) instead of the separate UEPn_TX_CTRL/UEPn_RX_CTRL bytes of the newer IP (CH32V20x/V307). The shared driver was written for the newer IP, so EP0 control transfers never worked on V103: the OUT response was written to a reserved byte and the IN write clobbered the OUT bits. - ch32_usbfs_reg.h: annotate the V103 register struct with byte offsets and add a union exposing the combined UEPn_CTRL at the UEPn_TX_CTRL offset; define CH32_USBFS_EP_CTRL_COMBINED and the combined-register bit positions. - dcd_ch32_usbfs.c: abstract EP control access behind ep_tx/rx_ctrl_set() (full write) and ep_tx/rx_set_response() (response-only RMW). The newer-IP path is unchanged; the combined path read-modify-writes the single register and arms the post-SETUP data stage at DATA1. - bsp/ch32v10x: implement board_get_unique_id() (real chip UID) and drop the CSR 0x800 writes that corrupted the QingKe V3 interrupt config and left all interrupts disabled (the USB ISR never ran). Verified on ch32v103r_r1_1v0: enumerates and passes HIL for cdc_msc, hid, msc, midi, mtp, dfu, etc. Co-Authored-By: Claude Opus 4.8 (1M context) --- hw/bsp/ch32v10x/family.c | 39 +++++------ src/portable/wch/ch32_usbfs_reg.h | 140 +++++++++++++++++++++++++------------- src/portable/wch/dcd_ch32_usbfs.c | 95 +++++++++++++++++++------- 3 files changed, 181 insertions(+), 93 deletions(-) (limited to 'src') diff --git a/hw/bsp/ch32v10x/family.c b/hw/bsp/ch32v10x/family.c index 9f5dc5572..aa709b0d8 100644 --- a/hw/bsp/ch32v10x/family.c +++ b/hw/bsp/ch32v10x/family.c @@ -66,26 +66,14 @@ uint32_t tusb_time_millis_api(void) { } #endif -// 0x800 CSR register is writable in U-mode -// according to manual: https://www.wch-ic.com/downloads/QingKeV3_Processor_Manual_PDF.html -__attribute__((always_inline)) RV_STATIC_INLINE -void __wch_vendor_enable_irq(void) -{ - __asm volatile ("csrs 0x800, %0" : : "r" (0x88) ); -} - -__attribute__((always_inline)) RV_STATIC_INLINE -void __wch_vendor_disable_irq(void) -{ - __asm volatile ("csrc 0x800, %0" : : "r" (0x88) ); - __asm volatile ("fence.i"); -} - void board_init(void) { - /* __disable_irq() in CH32V103 EVT attempts to call - * `csrc mstatus, 0x88` in U-mode, which is allowed ONLY in M-mode. - * Replace this with CSR 0x800 to avoid hard-fault. */ - __wch_vendor_disable_irq(); + /* Do NOT toggle the global interrupt enable here. + * CH32V103 startup enters U-mode (mret with mstatus.MPP=0), so: + * - the SDK __disable_irq()/__enable_irq() write mstatus, which faults in U-mode; + * - writing CSR 0x800 (INTSYSCR) corrupts the QingKe V3 interrupt-mode config, + * which made the USB interrupt vector to a bad address (PC=0) and hang. + * The startup already leaves interrupts correctly configured, and machine-mode + * interrupts are globally enabled while running in U-mode regardless of mstatus.MIE. */ #if CFG_TUSB_OS == OPT_OS_NONE SysTick_Config(SystemCoreClock / 1000); @@ -142,8 +130,6 @@ void board_init(void) { USART_Init(USART1, &usart); USART_Cmd(USART1, ENABLE); - __wch_vendor_enable_irq(); - board_led_write(true); } @@ -155,6 +141,17 @@ uint32_t board_button_read(void) { return BUTTON_STATE_ACTIVE == GPIO_ReadInputDataBit(BUTTON_PORT, BUTTON_PIN); } +size_t board_get_unique_id(uint8_t id[], size_t max_len) { + (void) max_len; + volatile uint32_t* ch32_uuid = ((volatile uint32_t*) 0x1FFFF7E8UL); + uint32_t* serial_32 = (uint32_t*) (uintptr_t) id; + serial_32[0] = ch32_uuid[0]; + serial_32[1] = ch32_uuid[1]; + serial_32[2] = ch32_uuid[2]; + + return 12; +} + int board_uart_read(uint8_t *buf, int len) { (void) buf; (void) len; diff --git a/src/portable/wch/ch32_usbfs_reg.h b/src/portable/wch/ch32_usbfs_reg.h index 68be64f5e..7ffdc6cef 100644 --- a/src/portable/wch/ch32_usbfs_reg.h +++ b/src/portable/wch/ch32_usbfs_reg.h @@ -39,59 +39,92 @@ #include #elif CFG_TUSB_MCU == OPT_MCU_CH32V103 #include + // Newer-IP layout (separate UEPn_TX_CTRL/UEPn_RX_CTRL). The older IP (CH32V103) has a single + // combined control register at the UEPn_TX_CTRL offset, with UEPn_RX_CTRL reserved; the union + // exposes that same byte as UEPn_CTRL. Offsets are byte offsets from the peripheral base. + // TODO unify into a single struct shared by all WCH USBFS parts. typedef struct { - __IO uint8_t BASE_CTRL; - __IO uint8_t UDEV_CTRL; - __IO uint8_t INT_EN; - __IO uint8_t DEV_ADDR; - __IO uint8_t Reserve0; - __IO uint8_t MIS_ST; - __IO uint8_t INT_FG; - __IO uint8_t INT_ST; - __IO uint32_t RX_LEN; - __IO uint8_t UEP4_1_MOD; - __IO uint8_t UEP2_3_MOD; - __IO uint8_t UEP5_6_MOD; - __IO uint8_t UEP7_MOD; - __IO uint32_t UEP0_DMA; - __IO uint32_t UEP1_DMA; - __IO uint32_t UEP2_DMA; - __IO uint32_t UEP3_DMA; - __IO uint32_t UEP4_DMA; - __IO uint32_t UEP5_DMA; - __IO uint32_t UEP6_DMA; - __IO uint32_t UEP7_DMA; - __IO uint16_t UEP0_TX_LEN; - __IO uint8_t UEP0_TX_CTRL; - __IO uint8_t UEP0_RX_CTRL; - __IO uint16_t UEP1_TX_LEN; - __IO uint8_t UEP1_TX_CTRL; - __IO uint8_t UEP1_RX_CTRL; - __IO uint16_t UEP2_TX_LEN; - __IO uint8_t UEP2_TX_CTRL; - __IO uint8_t UEP2_RX_CTRL; - __IO uint16_t UEP3_TX_LEN; - __IO uint8_t UEP3_TX_CTRL; - __IO uint8_t UEP3_RX_CTRL; - __IO uint16_t UEP4_TX_LEN; - __IO uint8_t UEP4_TX_CTRL; - __IO uint8_t UEP4_RX_CTRL; - __IO uint16_t UEP5_TX_LEN; - __IO uint8_t UEP5_TX_CTRL; - __IO uint8_t UEP5_RX_CTRL; - __IO uint16_t UEP6_TX_LEN; - __IO uint8_t UEP6_TX_CTRL; - __IO uint8_t UEP6_RX_CTRL; - __IO uint16_t UEP7_TX_LEN; - __IO uint8_t UEP7_TX_CTRL; - __IO uint8_t UEP7_RX_CTRL; - __IO uint32_t Reserve1; - __IO uint32_t OTG_CR; - __IO uint32_t OTG_SR; + __IO uint8_t BASE_CTRL; // 0x00 + __IO uint8_t UDEV_CTRL; // 0x01 + __IO uint8_t INT_EN; // 0x02 + __IO uint8_t DEV_ADDR; // 0x03 + __IO uint8_t Reserve0; // 0x04 + __IO uint8_t MIS_ST; // 0x05 + __IO uint8_t INT_FG; // 0x06 + __IO uint8_t INT_ST; // 0x07 + __IO uint32_t RX_LEN; // 0x08 + __IO uint8_t UEP4_1_MOD; // 0x0C + __IO uint8_t UEP2_3_MOD; // 0x0D + __IO uint8_t UEP5_6_MOD; // 0x0E + __IO uint8_t UEP7_MOD; // 0x0F + __IO uint32_t UEP0_DMA; // 0x10 + __IO uint32_t UEP1_DMA; // 0x14 + __IO uint32_t UEP2_DMA; // 0x18 + __IO uint32_t UEP3_DMA; // 0x1C + __IO uint32_t UEP4_DMA; // 0x20 + __IO uint32_t UEP5_DMA; // 0x24 + __IO uint32_t UEP6_DMA; // 0x28 + __IO uint32_t UEP7_DMA; // 0x2C + __IO uint16_t UEP0_TX_LEN; // 0x30 + union { + __IO uint8_t UEP0_TX_CTRL; + __IO uint8_t UEP0_CTRL; + }; // 0x32 (TX_CTRL: IN | CTRL: combined) + __IO uint8_t UEP0_RX_CTRL; // 0x33 (OUT ctrl; reserved on combined IP) + __IO uint16_t UEP1_TX_LEN; // 0x34 + union { + __IO uint8_t UEP1_TX_CTRL; + __IO uint8_t UEP1_CTRL; + }; // 0x36 + __IO uint8_t UEP1_RX_CTRL; // 0x37 + __IO uint16_t UEP2_TX_LEN; // 0x38 + union { + __IO uint8_t UEP2_TX_CTRL; + __IO uint8_t UEP2_CTRL; + }; // 0x3A + __IO uint8_t UEP2_RX_CTRL; // 0x3B + __IO uint16_t UEP3_TX_LEN; // 0x3C + union { + __IO uint8_t UEP3_TX_CTRL; + __IO uint8_t UEP3_CTRL; + }; // 0x3E + __IO uint8_t UEP3_RX_CTRL; // 0x3F + __IO uint16_t UEP4_TX_LEN; // 0x40 + union { + __IO uint8_t UEP4_TX_CTRL; + __IO uint8_t UEP4_CTRL; + }; // 0x42 + __IO uint8_t UEP4_RX_CTRL; // 0x43 + __IO uint16_t UEP5_TX_LEN; // 0x44 + union { + __IO uint8_t UEP5_TX_CTRL; + __IO uint8_t UEP5_CTRL; + }; // 0x46 + __IO uint8_t UEP5_RX_CTRL; // 0x47 + __IO uint16_t UEP6_TX_LEN; // 0x48 + union { + __IO uint8_t UEP6_TX_CTRL; + __IO uint8_t UEP6_CTRL; + }; // 0x4A + __IO uint8_t UEP6_RX_CTRL; // 0x4B + __IO uint16_t UEP7_TX_LEN; // 0x4C + union { + __IO uint8_t UEP7_TX_CTRL; + __IO uint8_t UEP7_CTRL; + }; // 0x4E + __IO uint8_t UEP7_RX_CTRL; // 0x4F + __IO uint32_t Reserve1; // 0x50 + __IO uint32_t OTG_CR; // 0x54 + __IO uint32_t OTG_SR; // 0x58 } USBOTG_FS_TypeDef; #define USBOTG_FS ((USBOTG_FS_TypeDef *) 0x40023400) + + // CH32V103 has the older USBFS IP: a single combined control register per endpoint + // (UEPn_CTRL) instead of separate TX_CTRL/RX_CTRL bytes. The struct's UEPn_TX_CTRL field + // aliases that combined register (same address); UEPn_RX_CTRL maps to unused padding. + #define CH32_USBFS_EP_CTRL_COMBINED 1 #elif CFG_TUSB_MCU == OPT_MCU_CH32V20X #include #elif CFG_TUSB_MCU == OPT_MCU_CH32V307 @@ -166,6 +199,17 @@ #define USBFS_EP_R_RES_NAK (2 << 0) #define USBFS_EP_R_RES_STALL (3 << 0) +#ifdef CH32_USBFS_EP_CTRL_COMBINED +// Combined per-endpoint control register (older IP, e.g. CH32V103): IN response in +// bits [1:0], OUT response in bits [3:2], shared auto-toggle, separate IN/OUT toggle. +#define USBFS_EPC_T_RES_MASK 0x03 +#define USBFS_EPC_R_RES_MASK 0x0C +#define USBFS_EPC_R_RES_SHIFT 2 +#define USBFS_EPC_AUTO_TOG 0x10 +#define USBFS_EPC_T_TOG 0x40 +#define USBFS_EPC_R_TOG 0x80 +#endif + // token PID #define PID_OUT 0 #define PID_SOF 1 diff --git a/src/portable/wch/dcd_ch32_usbfs.c b/src/portable/wch/dcd_ch32_usbfs.c index af0f17785..dae31da91 100644 --- a/src/portable/wch/dcd_ch32_usbfs.c +++ b/src/portable/wch/dcd_ch32_usbfs.c @@ -40,6 +40,52 @@ #define EP_TX_CTRL(ep) ((&USBOTG_FS->UEP0_TX_CTRL)[4 * ep]) #define EP_RX_CTRL(ep) ((&USBOTG_FS->UEP0_RX_CTRL)[4 * ep]) +// Endpoint control register access. The newer USBFS IP (CH32V20x/V307/X035) has separate +// TX_CTRL and RX_CTRL bytes per endpoint; the older IP (CH32V103) has a single combined +// UEPn_CTRL register. These helpers hide the difference so the rest of the driver is shared. +// Values use the newer-IP encoding (USBFS_EP_T_*/USBFS_EP_R_*); the combined path remaps them. +#ifdef CH32_USBFS_EP_CTRL_COMBINED + #define EP_CTRL(ep) EP_TX_CTRL(ep) // UEPn_TX_CTRL field aliases the combined UEPn_CTRL register + + static inline uint8_t ep_tx_to_comb(uint8_t v) { + uint8_t c = v & USBFS_EP_T_RES_MASK; // IN response: bits [1:0] in both encodings + if (v & USBFS_EP_T_TOG) { c |= USBFS_EPC_T_TOG; } + if (v & USBFS_EP_T_AUTO_TOG) { c |= USBFS_EPC_AUTO_TOG; } + return c; + } + static inline uint8_t ep_rx_to_comb(uint8_t v) { + uint8_t c = (uint8_t) ((v & USBFS_EP_R_RES_MASK) << USBFS_EPC_R_RES_SHIFT); // OUT response -> bits [3:2] + if (v & USBFS_EP_R_TOG) { c |= USBFS_EPC_R_TOG; } + if (v & USBFS_EP_R_AUTO_TOG) { c |= USBFS_EPC_AUTO_TOG; } + return c; + } + // Set IN side (response/toggle/auto-tog), preserving the OUT response + OUT toggle. + static inline void ep_tx_ctrl_set(uint8_t ep, uint8_t v) { + EP_CTRL(ep) = (uint8_t) ((EP_CTRL(ep) & (USBFS_EPC_R_RES_MASK | USBFS_EPC_R_TOG)) | ep_tx_to_comb(v)); + } + // Set OUT side, preserving the IN response + IN toggle. + static inline void ep_rx_ctrl_set(uint8_t ep, uint8_t v) { + EP_CTRL(ep) = (uint8_t) ((EP_CTRL(ep) & (USBFS_EPC_T_RES_MASK | USBFS_EPC_T_TOG)) | ep_rx_to_comb(v)); + } + static inline void ep_tx_set_response(uint8_t ep, uint8_t res) { + EP_CTRL(ep) = (uint8_t) ((EP_CTRL(ep) & ~USBFS_EPC_T_RES_MASK) | (res & USBFS_EP_T_RES_MASK)); + } + static inline void ep_rx_set_response(uint8_t ep, uint8_t res) { + EP_CTRL(ep) = (uint8_t) ((EP_CTRL(ep) & ~USBFS_EPC_R_RES_MASK) | ((res & USBFS_EP_R_RES_MASK) << USBFS_EPC_R_RES_SHIFT)); + } + #define EP0_SETUP_RX_TOG USBFS_EP_R_TOG // combined IP: data/status stage after SETUP is DATA1 +#else + static inline void ep_tx_ctrl_set(uint8_t ep, uint8_t v) { EP_TX_CTRL(ep) = v; } + static inline void ep_rx_ctrl_set(uint8_t ep, uint8_t v) { EP_RX_CTRL(ep) = v; } + static inline void ep_tx_set_response(uint8_t ep, uint8_t res) { + EP_TX_CTRL(ep) = (uint8_t) ((EP_TX_CTRL(ep) & ~USBFS_EP_T_RES_MASK) | res); + } + static inline void ep_rx_set_response(uint8_t ep, uint8_t res) { + EP_RX_CTRL(ep) = (uint8_t) ((EP_RX_CTRL(ep) & ~USBFS_EP_R_RES_MASK) | res); + } + #define EP0_SETUP_RX_TOG 0 +#endif + /* private data */ struct usb_xfer { bool valid; @@ -81,19 +127,19 @@ static void update_in(uint8_t rhport, uint8_t ep, bool force) { EP_TX_LEN(ep) = len; if (ep == 0) { - EP_TX_CTRL(0) = USBFS_EP_T_RES_ACK | (data.ep0_tog ? USBFS_EP_T_TOG : 0); + ep_tx_ctrl_set(0, USBFS_EP_T_RES_ACK | (data.ep0_tog ? USBFS_EP_T_TOG : 0)); data.ep0_tog = !data.ep0_tog; } else if (data.isochronous[ep]) { - EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~(USBFS_EP_T_RES_MASK)) | USBFS_EP_T_RES_NYET; + ep_tx_set_response(ep, USBFS_EP_T_RES_NYET); } else { - EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~(USBFS_EP_T_RES_MASK)) | USBFS_EP_T_RES_ACK; + ep_tx_set_response(ep, USBFS_EP_T_RES_ACK); } } else { xfer->valid = false; if (ep == 0) { - EP_TX_CTRL(0) = USBFS_EP_T_RES_NAK | (data.ep0_tog ? USBFS_EP_T_TOG : 0); + ep_tx_ctrl_set(0, USBFS_EP_T_RES_NAK | (data.ep0_tog ? USBFS_EP_T_TOG : 0)); } else if (!data.isochronous[ep]) { - EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~(USBFS_EP_T_RES_MASK)) | USBFS_EP_T_RES_NAK; + ep_tx_set_response(ep, USBFS_EP_T_RES_NAK); } dcd_event_xfer_complete(rhport, ep | TUSB_DIR_IN_MASK, xfer->processed_len, XFER_RESULT_SUCCESS, true); } @@ -119,11 +165,11 @@ static void update_out(uint8_t rhport, uint8_t ep, size_t rx_len) { } if (ep == 0) { - EP_RX_CTRL(0) = USBFS_EP_R_RES_NAK; + ep_rx_set_response(0, USBFS_EP_R_RES_NAK); } else { uint8_t rx_res = data.isochronous[ep] ? USBFS_EP_R_RES_NYET : (xfer->valid ? USBFS_EP_R_RES_ACK : USBFS_EP_R_RES_NAK); - EP_RX_CTRL(ep) = (EP_RX_CTRL(ep) & ~USBFS_EP_R_RES_MASK) | rx_res; + ep_rx_set_response(ep, rx_res); } } } @@ -132,8 +178,8 @@ static void reset_ep_ctrls(void) { for (uint8_t ep = 1; ep < EP_MAX; ep++) { EP_DMA(ep) = (uint32_t)&data.buffer[ep][0]; EP_TX_LEN(ep) = 0; - EP_TX_CTRL(ep) = USBFS_EP_T_AUTO_TOG | USBFS_EP_T_RES_NYET; - EP_RX_CTRL(ep) = USBFS_EP_R_AUTO_TOG | USBFS_EP_R_RES_NYET; + ep_tx_ctrl_set(ep, USBFS_EP_T_AUTO_TOG | USBFS_EP_T_RES_NYET); + ep_rx_ctrl_set(ep, USBFS_EP_R_AUTO_TOG | USBFS_EP_R_RES_NYET); } EP_DMA(3) = (uint32_t)&data.ep3_buffer.out[0]; } @@ -152,8 +198,8 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t *rh_init) { // setup endpoint 0 EP_DMA(0) = (uint32_t)&data.buffer[0][0]; EP_TX_LEN(0) = 0; - EP_TX_CTRL(0) = USBFS_EP_T_RES_NAK; - EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK; + ep_tx_ctrl_set(0, USBFS_EP_T_RES_NAK); + ep_rx_ctrl_set(0, USBFS_EP_R_RES_ACK); // enable other endpoints but NAK everything USBOTG_FS->UEP4_1_MOD = 0xCC; @@ -188,11 +234,12 @@ void dcd_int_handler(uint8_t rhport) { case PID_SETUP: // setup clears stall - EP_TX_CTRL(0) = USBFS_EP_T_RES_NAK; + ep_tx_ctrl_set(0, USBFS_EP_T_RES_NAK); data.ep0_tog = true; const tusb_control_request_t *setup = (const tusb_control_request_t *)&data.buffer[0][TUSB_DIR_OUT][0]; - EP_RX_CTRL(0) = (setup->wLength == 0) ? USBFS_EP_R_RES_ACK : USBFS_EP_R_RES_NAK; + // EP0_SETUP_RX_TOG arms the data/status stage at DATA1 on the combined-control IP + ep_rx_ctrl_set(0, ((setup->wLength == 0) ? USBFS_EP_R_RES_ACK : USBFS_EP_R_RES_NAK) | EP0_SETUP_RX_TOG); dcd_event_setup_received(rhport, &data.buffer[0][TUSB_DIR_OUT][0], true); break; @@ -210,7 +257,7 @@ void dcd_int_handler(uint8_t rhport) { true); USBOTG_FS->DEV_ADDR = 0x00; - EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK; + ep_rx_ctrl_set(0, USBFS_EP_R_RES_ACK); reset_ep_ctrls(); @@ -277,9 +324,9 @@ bool dcd_edpt_open(uint8_t rhport, const tusb_desc_endpoint_t *desc_ep) { if (ep != 0) { if (dir == TUSB_DIR_OUT) { - EP_RX_CTRL(ep) = USBFS_EP_R_AUTO_TOG | USBFS_EP_T_RES_NAK; + ep_rx_ctrl_set(ep, USBFS_EP_R_AUTO_TOG | USBFS_EP_R_RES_NAK); } else { - EP_TX_CTRL(ep) = USBFS_EP_T_AUTO_TOG | USBFS_EP_T_RES_NAK; + ep_tx_ctrl_set(ep, USBFS_EP_T_AUTO_TOG | USBFS_EP_T_RES_NAK); } } return true; @@ -326,7 +373,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t to update_in(rhport, ep, true); } else { uint8_t rx_res = data.isochronous[ep] ? USBFS_EP_R_RES_NYET : USBFS_EP_R_RES_ACK; - EP_RX_CTRL(ep) = (EP_RX_CTRL(ep) & ~USBFS_EP_R_RES_MASK) | rx_res; + ep_rx_set_response(ep, rx_res); } return true; } @@ -337,16 +384,16 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { uint8_t dir = tu_edpt_dir(ep_addr); if (ep == 0) { if (dir == TUSB_DIR_OUT) { - EP_RX_CTRL(0) = USBFS_EP_R_RES_STALL; + ep_rx_ctrl_set(0, USBFS_EP_R_RES_STALL); } else { EP_TX_LEN(0) = 0; - EP_TX_CTRL(0) = USBFS_EP_T_RES_STALL; + ep_tx_ctrl_set(0, USBFS_EP_T_RES_STALL); } } else { if (dir == TUSB_DIR_OUT) { - EP_RX_CTRL(ep) = (EP_RX_CTRL(ep) & ~USBFS_EP_R_RES_MASK) | USBFS_EP_R_RES_STALL; + ep_rx_set_response(ep, USBFS_EP_R_RES_STALL); } else { - EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~USBFS_EP_T_RES_MASK) | USBFS_EP_T_RES_STALL; + ep_tx_set_response(ep, USBFS_EP_T_RES_STALL); } } } @@ -357,13 +404,13 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) { uint8_t dir = tu_edpt_dir(ep_addr); if (ep == 0) { if (dir == TUSB_DIR_OUT) { - EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK; + ep_rx_ctrl_set(0, USBFS_EP_R_RES_ACK); } } else { if (dir == TUSB_DIR_OUT) { - EP_RX_CTRL(ep) = USBFS_EP_R_AUTO_TOG | USBFS_EP_R_RES_NAK; + ep_rx_ctrl_set(ep, USBFS_EP_R_AUTO_TOG | USBFS_EP_R_RES_NAK); } else { - EP_TX_CTRL(ep) = USBFS_EP_T_AUTO_TOG | USBFS_EP_T_RES_NAK; + ep_tx_ctrl_set(ep, USBFS_EP_T_AUTO_TOG | USBFS_EP_T_RES_NAK); } } } -- cgit v1.3.1