From 2ddd74fada9b2f272923fce9c3b1926a6e9f5c80 Mon Sep 17 00:00:00 2001 From: rppicomidi Date: Fri, 12 Aug 2022 11:06:36 -0700 Subject: Add MIDI host support to tinyusb --- src/host/hcd.h | 2 +- src/host/usbh.c | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) (limited to 'src/host') diff --git a/src/host/hcd.h b/src/host/hcd.h index deebc59d4..97b668d79 100644 --- a/src/host/hcd.h +++ b/src/host/hcd.h @@ -40,7 +40,7 @@ //--------------------------------------------------------------------+ #ifndef CFG_TUH_ENDPOINT_MAX - #define CFG_TUH_ENDPOINT_MAX (CFG_TUH_HUB + CFG_TUH_HID*2 + CFG_TUH_MSC*2 + CFG_TUH_CDC*3) + #define CFG_TUH_ENDPOINT_MAX (CFG_TUH_HUB + CFG_TUH_HID*2 + CFG_TUH_MSC*2 + CFG_TUH_CDC*3 + CFG_TUH_MIDI*2) // #ifdef TUP_HCD_ENDPOINT_MAX // #define CFG_TUH_ENDPPOINT_MAX TUP_HCD_ENDPOINT_MAX // #else diff --git a/src/host/usbh.c b/src/host/usbh.c index 9d618db92..c59f31596 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -166,6 +166,17 @@ static usbh_class_driver_t const usbh_class_drivers[] = }, #endif + #if CFG_TUH_MIDI + { + DRIVER_NAME("MIDI") + .init = midih_init, + .open = midih_open, + .set_config = midih_set_config, + .xfer_cb = midih_xfer_cb, + .close = midih_close + }, + #endif + #if CFG_TUH_HUB { DRIVER_NAME("HUB") -- cgit v1.3.1 From 70eefcb849542f386a1349da7a4944d2d02dcd40 Mon Sep 17 00:00:00 2001 From: rppicomidi Date: Thu, 25 Aug 2022 15:08:00 -0700 Subject: Add hooks to allow cloning an attached USB device descriptor --- src/device/usbd_control.c | 2 +- src/host/usbh.c | 7 +++++-- src/host/usbh.h | 6 +++++- src/tusb_option.h | 6 +++--- 4 files changed, 14 insertions(+), 7 deletions(-) (limited to 'src/host') diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index 0995ef669..187547ae3 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -56,7 +56,7 @@ typedef struct static usbd_control_xfer_t _ctrl_xfer; CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN -static uint8_t _usbd_ctrl_buf[CFG_TUD_ENDPOINT0_SIZE]; +static uint8_t _usbd_ctrl_buf[/*CFG_TUD_ENDPOINT0_SIZE*/ 64]; //--------------------------------------------------------------------+ // Application API diff --git a/src/host/usbh.c b/src/host/usbh.c index c59f31596..44b4d3217 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -1323,7 +1323,7 @@ static void process_enumeration(tuh_xfer_t* xfer) dev->i_product = desc_device->iProduct; dev->i_serial = desc_device->iSerialNumber; - // if (tuh_attach_cb) tuh_attach_cb((tusb_desc_device_t*) _usbh_ctrl_buf); + if (tuh_desc_device_cb) tuh_desc_device_cb(daddr, (tusb_desc_device_t const*) _usbh_ctrl_buf); // Get 9-byte for total length uint8_t const config_idx = CONFIG_NUM - 1; @@ -1350,9 +1350,12 @@ static void process_enumeration(tuh_xfer_t* xfer) break; case ENUM_SET_CONFIG: + // Got the whole configuration descriptor. Make a copy + if (tuh_desc_config_cb) tuh_desc_config_cb(daddr, (const tusb_desc_configuration_t*) _usbh_ctrl_buf); + // Parse configuration & set up drivers // Driver open aren't allowed to make any usb transfer yet - TU_ASSERT( _parse_configuration_descriptor(daddr, (tusb_desc_configuration_t*) _usbh_ctrl_buf), ); + TU_ASSERT( _parse_configuration_descriptor(daddr, (const tusb_desc_configuration_t* ) _usbh_ctrl_buf), ); TU_ASSERT( tuh_configuration_set(daddr, CONFIG_NUM, process_enumeration, ENUM_CONFIG_DRIVER), ); break; diff --git a/src/host/usbh.h b/src/host/usbh.h index 560a1ea23..7355c83ee 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -78,7 +78,11 @@ enum // APPLICATION CALLBACK //--------------------------------------------------------------------+ -//TU_ATTR_WEAK uint8_t tuh_attach_cb (tusb_desc_device_t const *desc_device); +// Give the application an opportunity to grab the device descriptor +TU_ATTR_WEAK void tuh_desc_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device); + +// Give the application an opportunity to grab the configuration descriptor +TU_ATTR_WEAK void tuh_desc_config_cb(uint8_t daddr, const tusb_desc_configuration_t *desc_config); // Invoked when device is mounted (configured) TU_ATTR_WEAK void tuh_mount_cb (uint8_t daddr); diff --git a/src/tusb_option.h b/src/tusb_option.h index f95ae6273..b905fc7ce 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -427,9 +427,9 @@ typedef int make_iso_compilers_happy; //------------------------------------------------------------------ // Configuration Validation //------------------------------------------------------------------ -#if CFG_TUD_ENDPOINT0_SIZE > 64 - #error Control Endpoint Max Packet Size cannot be larger than 64 -#endif +//#if CFG_TUD_ENDPOINT0_SIZE > 64 +// #error Control Endpoint Max Packet Size cannot be larger than 64 +//#endif #endif /* _TUSB_OPTION_H_ */ -- cgit v1.3.1 From 85247e50ddc17347fca1f6c9b9fedb1227eda25f Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 12 Feb 2025 11:34:32 +0700 Subject: clean up --- hw/bsp/rp2040/family.cmake | 30 +++++++++++++++--------------- src/class/midi/midi_device.c | 2 +- src/device/usbd.c | 13 ++++++------- src/host/usbh.c | 8 ++++++-- src/tusb_option.h | 6 +++--- 5 files changed, 31 insertions(+), 28 deletions(-) (limited to 'src/host') diff --git a/hw/bsp/rp2040/family.cmake b/hw/bsp/rp2040/family.cmake index cf5295f22..1cbc0742c 100644 --- a/hw/bsp/rp2040/family.cmake +++ b/hw/bsp/rp2040/family.cmake @@ -100,21 +100,21 @@ target_sources(tinyusb_device_base INTERFACE ${TOP}/src/class/video/video_device.c ) - #------------------------------------ - # Base config for host mode; wrapped by SDK's tinyusb_host - #------------------------------------ - add_library(tinyusb_host_base INTERFACE) - target_sources(tinyusb_host_base INTERFACE - ${TOP}/src/portable/raspberrypi/rp2040/hcd_rp2040.c - ${TOP}/src/portable/raspberrypi/rp2040/rp2040_usb.c - ${TOP}/src/host/usbh.c - ${TOP}/src/host/hub.c - ${TOP}/src/class/cdc/cdc_host.c - ${TOP}/src/class/hid/hid_host.c - ${TOP}/src/class/midi/midi_host.c - ${TOP}/src/class/msc/msc_host.c - ${TOP}/src/class/vendor/vendor_host.c - ) +#------------------------------------ +# Base config for host mode; wrapped by SDK's tinyusb_host +#------------------------------------ +add_library(tinyusb_host_base INTERFACE) +target_sources(tinyusb_host_base INTERFACE + ${TOP}/src/portable/raspberrypi/rp2040/hcd_rp2040.c + ${TOP}/src/portable/raspberrypi/rp2040/rp2040_usb.c + ${TOP}/src/host/usbh.c + ${TOP}/src/host/hub.c + ${TOP}/src/class/cdc/cdc_host.c + ${TOP}/src/class/hid/hid_host.c + ${TOP}/src/class/midi/midi_host.c + ${TOP}/src/class/msc/msc_host.c + ${TOP}/src/class/vendor/vendor_host.c + ) # Sometimes have to do host specific actions in mostly common functions target_compile_definitions(tinyusb_host_base INTERFACE diff --git a/src/class/midi/midi_device.c b/src/class/midi/midi_device.c index 4ae8ea8fa..dd1883e37 100644 --- a/src/class/midi/midi_device.c +++ b/src/class/midi/midi_device.c @@ -440,7 +440,7 @@ uint16_t midid_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uint1 drv_len = tu_desc_len(desc_itf); p_desc = tu_desc_next(desc_itf); // Skip Class Specific descriptors - while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len ) { + while (TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len) { drv_len += tu_desc_len(p_desc); p_desc = tu_desc_next(p_desc); } diff --git a/src/device/usbd.c b/src/device/usbd.c index 20f803563..faf926855 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -1032,14 +1032,13 @@ static bool process_set_config(uint8_t rhport, uint8_t cfg_num) #endif #if CFG_TUD_MIDI - if ( driver->open == midid_open ) - { - // If there is a class-compliant Audio Control Class, then 2 interfaces - // Otherwise, only one + if (driver->open == midid_open) { + // If there is a class-compliant Audio Control Class, then 2 interfaces. Otherwise, only one if (TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass && - AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass && - AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol) - assoc_itf_count = 2; + AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass && + AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol) { + assoc_itf_count = 2; + } } #endif diff --git a/src/host/usbh.c b/src/host/usbh.c index 6f7a8b8bf..30a4f5f63 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -1488,7 +1488,9 @@ static void process_enumeration(tuh_xfer_t* xfer) { dev->i_product = desc_device->iProduct; dev->i_serial = desc_device->iSerialNumber; - if (tuh_desc_device_cb) tuh_desc_device_cb(daddr, (tusb_desc_device_t const*) _usbh_ctrl_buf); + if (tuh_desc_device_cb) { + tuh_desc_device_cb(daddr, (tusb_desc_device_t const*) _usbh_ctrl_buf); + } // Get 9-byte for total length uint8_t const config_idx = CONFIG_NUM - 1; @@ -1517,7 +1519,9 @@ static void process_enumeration(tuh_xfer_t* xfer) { } case ENUM_SET_CONFIG: - if (tuh_desc_config_cb) tuh_desc_config_cb(daddr, (const tusb_desc_configuration_t*) _usbh_ctrl_buf); + if (tuh_desc_config_cb) { + tuh_desc_config_cb(daddr, (const tusb_desc_configuration_t*) _usbh_ctrl_buf); + } TU_ASSERT(tuh_configuration_set(daddr, CONFIG_NUM, process_enumeration, ENUM_CONFIG_DRIVER),); break; diff --git a/src/tusb_option.h b/src/tusb_option.h index 84319939a..29fdcb0d6 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -657,9 +657,9 @@ //------------------------------------------------------------------ // Configuration Validation //------------------------------------------------------------------ -//#if CFG_TUD_ENDPOINT0_SIZE > 64 -// #error Control Endpoint Max Packet Size cannot be larger than 64 -//#endif +#if CFG_TUD_ENDPOINT0_SIZE > 64 + #error Control Endpoint Max Packet Size cannot be larger than 64 +#endif // To avoid GCC compiler warnings when -pedantic option is used (strict ISO C) typedef int make_iso_compilers_happy; -- cgit v1.3.1 From 7c405236cfcf0850032ec0190eea1f01fb631ef9 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 12 Feb 2025 11:50:57 +0700 Subject: fix host midi build --- examples/host/midi_rx/CMakeLists.txt | 25 +++++++++++++++---------- examples/host/midi_rx/Makefile | 12 ++++++++---- examples/host/midi_rx/only.txt | 19 +++++++++++++++++++ examples/host/midi_rx/src/main.c | 4 +--- src/CMakeLists.txt | 1 + src/class/midi/midi_host.c | 5 +++-- src/class/midi/midi_host.h | 2 +- src/host/usbh.c | 4 ++-- src/tinyusb.mk | 1 + 9 files changed, 51 insertions(+), 22 deletions(-) (limited to 'src/host') diff --git a/examples/host/midi_rx/CMakeLists.txt b/examples/host/midi_rx/CMakeLists.txt index b5e5f6bc8..33953233d 100644 --- a/examples/host/midi_rx/CMakeLists.txt +++ b/examples/host/midi_rx/CMakeLists.txt @@ -1,27 +1,32 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) -# gets PROJECT name for the example (e.g. -) +# gets PROJECT name for the example family_get_project_name(PROJECT ${CMAKE_CURRENT_LIST_DIR}) -project(${PROJECT}) +project(${PROJECT} C CXX ASM) # Checks this example is valid for the family and initializes the project family_initialize_project(${PROJECT} ${CMAKE_CURRENT_LIST_DIR}) +# Espressif has its own cmake build system +if(FAMILY STREQUAL "espressif") + return() +endif() + add_executable(${PROJECT}) # Example source target_sources(${PROJECT} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c - ) + ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c + ) # Example include target_include_directories(${PROJECT} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/src - ) + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) -# Configure compilation flags and libraries for the example... see the corresponding function -# in hw/bsp/FAMILY/family.cmake for details. -family_configure_host_example(${PROJECT}) +# Configure compilation flags and libraries for the example without RTOS. +# See the corresponding function in hw/bsp/FAMILY/family.cmake for details. +family_configure_host_example(${PROJECT} noos) diff --git a/examples/host/midi_rx/Makefile b/examples/host/midi_rx/Makefile index af8ef4275..0235e08c3 100644 --- a/examples/host/midi_rx/Makefile +++ b/examples/host/midi_rx/Makefile @@ -1,9 +1,13 @@ -include ../../../tools/top.mk -include ../../make.mk +include ../../build_system/make/make.mk + INC += \ src \ $(TOP)/hw \ + # Example source -EXAMPLE_SOURCE += $(wildcard src/*.c) +EXAMPLE_SOURCE += \ + src/main.c + SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) -include ../../rules.mk + +include ../../build_system/make/rules.mk diff --git a/examples/host/midi_rx/only.txt b/examples/host/midi_rx/only.txt index 2ba4438fd..b6f87f423 100644 --- a/examples/host/midi_rx/only.txt +++ b/examples/host/midi_rx/only.txt @@ -1 +1,20 @@ +mcu:ESP32S2 +mcu:ESP32S3 +mcu:ESP32P4 +mcu:KINETIS_KL +mcu:LPC175X_6X +mcu:LPC177X_8X +mcu:LPC18XX +mcu:LPC40XX +mcu:LPC43XX +mcu:MAX3421 +mcu:MIMXRT1XXX +mcu:MIMXRT10XX +mcu:MIMXRT11XX +mcu:MSP432E4 mcu:RP2040 +mcu:RX65X +mcu:RAXXX +mcu:STM32F4 +mcu:STM32F7 +mcu:STM32H7 diff --git a/examples/host/midi_rx/src/main.c b/examples/host/midi_rx/src/main.c index 6c3311043..8b83977e2 100644 --- a/examples/host/midi_rx/src/main.c +++ b/examples/host/midi_rx/src/main.c @@ -27,10 +27,8 @@ #include #include -#include "bsp/board.h" +#include "bsp/board_api.h" #include "tusb.h" -#include "class/midi/midi_host.h" - #if CFG_TUH_MIDI diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 7b3ab4d42..55c52033c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -29,6 +29,7 @@ function(tinyusb_target_add TARGET) ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/host/hub.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/cdc/cdc_host.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/hid/hid_host.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/midi/midi_host.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/msc/msc_host.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/vendor/vendor_host.c # typec diff --git a/src/class/midi/midi_host.c b/src/class/midi/midi_host.c index 061e17fee..fbb994ade 100644 --- a/src/class/midi/midi_host.c +++ b/src/class/midi/midi_host.c @@ -29,7 +29,7 @@ #if (TUSB_OPT_HOST_ENABLED && CFG_TUH_MIDI) #include "host/usbh.h" -#include "host/usbh_classdriver.h" +#include "host/usbh_pvt.h" #include "midi_host.h" @@ -131,7 +131,7 @@ static uint32_t write_flush(uint8_t dev_addr, midih_interface_t* midi); //--------------------------------------------------------------------+ // USBH API //--------------------------------------------------------------------+ -void midih_init(void) +bool midih_init(void) { tu_memclr(&_midi_host, sizeof(_midi_host)); // config fifos @@ -146,6 +146,7 @@ void midih_init(void) tu_fifo_config_mutex(&p_midi_host->tx_ff, osal_mutex_create(&p_midi_host->tx_ff_mutex), NULL); #endif } + return true; } bool midih_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) diff --git a/src/class/midi/midi_host.h b/src/class/midi/midi_host.h index 292c596e4..edf57bfcb 100644 --- a/src/class/midi/midi_host.h +++ b/src/class/midi/midi_host.h @@ -107,7 +107,7 @@ uint8_t tuh_midi_get_all_istrings(uint8_t dev_addr, const uint8_t** istrings); //--------------------------------------------------------------------+ // Internal Class Driver API //--------------------------------------------------------------------+ -void midih_init (void); +bool midih_init (void); bool midih_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len); bool midih_set_config (uint8_t dev_addr, uint8_t itf_num); bool midih_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); diff --git a/src/host/usbh.c b/src/host/usbh.c index 30a4f5f63..e38ee3187 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -1489,7 +1489,7 @@ static void process_enumeration(tuh_xfer_t* xfer) { dev->i_serial = desc_device->iSerialNumber; if (tuh_desc_device_cb) { - tuh_desc_device_cb(daddr, (tusb_desc_device_t const*) _usbh_ctrl_buf); + tuh_desc_device_cb(daddr, (tusb_desc_device_t const*) _usbh_epbuf.ctrl); } // Get 9-byte for total length @@ -1520,7 +1520,7 @@ static void process_enumeration(tuh_xfer_t* xfer) { case ENUM_SET_CONFIG: if (tuh_desc_config_cb) { - tuh_desc_config_cb(daddr, (const tusb_desc_configuration_t*) _usbh_ctrl_buf); + tuh_desc_config_cb(daddr, (const tusb_desc_configuration_t*) _usbh_epbuf.ctrl); } TU_ASSERT(tuh_configuration_set(daddr, CONFIG_NUM, process_enumeration, ENUM_CONFIG_DRIVER),); diff --git a/src/tinyusb.mk b/src/tinyusb.mk index 89ea0212c..a9f623c24 100644 --- a/src/tinyusb.mk +++ b/src/tinyusb.mk @@ -21,6 +21,7 @@ TINYUSB_SRC_C += \ src/host/hub.c \ src/class/cdc/cdc_host.c \ src/class/hid/hid_host.c \ + src/class/midi/midi_host.c \ src/class/msc/msc_host.c \ src/class/vendor/vendor_host.c \ src/typec/usbc.c \ -- cgit v1.3.1 From e0b192b633e70338ef5ac88c7f5a49f37867b289 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 12 Feb 2025 22:16:08 +0700 Subject: - use CFG_TUH_MIDI as number of midi host instance - comment out tuh_descriptor_device_cb/tuh_desc_configuration_cb since it is unrelated to this PR --- examples/host/midi_rx/src/tusb_config.h | 3 +- src/class/midi/midi_host.c | 289 ++++++++++++++------------------ src/class/midi/midi_host.h | 19 ++- src/host/usbh.c | 8 +- src/host/usbh.h | 8 +- 5 files changed, 151 insertions(+), 176 deletions(-) (limited to 'src/host') diff --git a/examples/host/midi_rx/src/tusb_config.h b/examples/host/midi_rx/src/tusb_config.h index 1afcbbd63..24b3b3ae6 100644 --- a/examples/host/midi_rx/src/tusb_config.h +++ b/examples/host/midi_rx/src/tusb_config.h @@ -107,10 +107,9 @@ extern "C" { #define CFG_TUH_ENUMERATION_BUFSIZE 256 #define CFG_TUH_HUB 1 -#define CFG_TUH_MIDI 1 // there will be at most one MIDIStreaming Interface descriptor - // max device support (excluding hub device): 1 hub typically has 4 ports #define CFG_TUH_DEVICE_MAX (3*CFG_TUH_HUB + 1) +#define CFG_TUH_MIDI CFG_TUH_DEVICE_MAX #define CFG_MIDI_HOST_DEVSTRINGS 1 diff --git a/src/class/midi/midi_host.c b/src/class/midi/midi_host.c index fbb994ade..21fe09143 100644 --- a/src/class/midi/midi_host.c +++ b/src/class/midi/midi_host.c @@ -36,14 +36,6 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -#ifndef CFG_TUH_MAX_CABLES - #define CFG_TUH_MAX_CABLES 16 -#endif -#define CFG_TUH_MIDI_RX_BUFSIZE 64 -#define CFG_TUH_MIDI_TX_BUFSIZE 64 -#ifndef CFG_TUH_MIDI_EP_BUFSIZE - #define CFG_TUH_MIDI_EP_BUFSIZE 64 -#endif // TODO: refactor to share code with the MIDI Device driver typedef struct @@ -117,34 +109,44 @@ typedef struct #endif }midih_interface_t; -static midih_interface_t _midi_host[CFG_TUH_DEVICE_MAX]; - -static midih_interface_t *get_midi_host(uint8_t dev_addr) -{ - TU_VERIFY(dev_addr >0 && dev_addr <= CFG_TUH_DEVICE_MAX); - return (_midi_host + dev_addr - 1); -} +static midih_interface_t _midi_host[CFG_TUH_MIDI]; //------------- Internal prototypes -------------// static uint32_t write_flush(uint8_t dev_addr, midih_interface_t* midi); +//--------------------------------------------------------------------+ +// Helper +//--------------------------------------------------------------------+ + +TU_ATTR_ALWAYS_INLINE static inline midih_interface_t* find_midi_by_daddr(uint8_t dev_addr) { + for (uint8_t i = 0; i < CFG_TUH_MIDI; i++) { + if (_midi_host[i].dev_addr == dev_addr) { + return &_midi_host[i]; + } + } + return NULL; +} + +TU_ATTR_ALWAYS_INLINE static inline midih_interface_t* find_new_midi(void) { + return find_midi_by_daddr(0); +} + + //--------------------------------------------------------------------+ // USBH API //--------------------------------------------------------------------+ -bool midih_init(void) -{ +bool midih_init(void) { tu_memclr(&_midi_host, sizeof(_midi_host)); // config fifos - for (int inst = 0; inst < CFG_TUH_DEVICE_MAX; inst++) - { + for (int inst = 0; inst < CFG_TUH_MIDI; inst++) { midih_interface_t *p_midi_host = &_midi_host[inst]; - tu_fifo_config(&p_midi_host->rx_ff, p_midi_host->rx_ff_buf, CFG_TUH_MIDI_RX_BUFSIZE, 1, false); // true, true - tu_fifo_config(&p_midi_host->tx_ff, p_midi_host->tx_ff_buf, CFG_TUH_MIDI_TX_BUFSIZE, 1, false); // OBVS. + tu_fifo_config(&p_midi_host->rx_ff, p_midi_host->rx_ff_buf, CFG_TUH_MIDI_RX_BUFSIZE, 1, false);// true, true + tu_fifo_config(&p_midi_host->tx_ff, p_midi_host->tx_ff_buf, CFG_TUH_MIDI_TX_BUFSIZE, 1, false);// OBVS. - #if CFG_FIFO_MUTEX + #if CFG_FIFO_MUTEX tu_fifo_config_mutex(&p_midi_host->rx_ff, NULL, osal_mutex_create(&p_midi_host->rx_ff_mutex)); tu_fifo_config_mutex(&p_midi_host->tx_ff, osal_mutex_create(&p_midi_host->tx_ff_mutex), NULL); - #endif + #endif } return true; } @@ -152,7 +154,7 @@ bool midih_init(void) bool midih_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { (void)result; - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); if ( ep_addr == p_midi_host->ep_in) { @@ -211,13 +213,14 @@ bool midih_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint return true; } -void midih_close(uint8_t dev_addr) -{ - midih_interface_t *p_midi_host = get_midi_host(dev_addr); - if (p_midi_host == NULL) +void midih_close(uint8_t dev_addr) { + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); + if (p_midi_host == NULL) { return; - if (tuh_midi_umount_cb) + } + if (tuh_midi_umount_cb) { tuh_midi_umount_cb(dev_addr, 0); + } tu_fifo_clear(&p_midi_host->rx_ff); tu_fifo_clear(&p_midi_host->tx_ff); p_midi_host->ep_in = 0; @@ -240,24 +243,24 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d { (void) rhport; - midih_interface_t *p_midi_host = get_midi_host(dev_addr); - + midih_interface_t *p_midi_host = find_new_midi(); TU_VERIFY(p_midi_host != NULL); + p_midi_host->num_string_indices = 0; TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass); // There can be just a MIDI interface or an audio and a MIDI interface. Only open the MIDI interface uint8_t const *p_desc = (uint8_t const *) desc_itf; uint16_t len_parsed = 0; - if (AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass) - { + if (AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass) { // Keep track of any string descriptor that might be here - if (desc_itf->iInterface != 0) - p_midi_host->all_string_indices[p_midi_host->num_string_indices++] = desc_itf->iInterface; + if (desc_itf->iInterface != 0) { + p_midi_host->all_string_indices[p_midi_host->num_string_indices++] = desc_itf->iInterface; + } // This driver does not support audio streaming. However, if this is the audio control interface // there might be a MIDI interface following it. Search through every descriptor until a MIDI // interface is found or the end of the descriptor is found - while (len_parsed < max_len && (desc_itf->bInterfaceClass != TUSB_CLASS_AUDIO || desc_itf->bInterfaceSubClass != AUDIO_SUBCLASS_MIDI_STREAMING)) - { + while (len_parsed < max_len && + (desc_itf->bInterfaceClass != TUSB_CLASS_AUDIO || desc_itf->bInterfaceSubClass != AUDIO_SUBCLASS_MIDI_STREAMING)) { len_parsed += desc_itf->bLength; p_desc = tu_desc_next(p_desc); desc_itf = (tusb_desc_interface_t const *)p_desc; @@ -269,8 +272,9 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d len_parsed += desc_itf->bLength; // Keep track of any string descriptor that might be here - if (desc_itf->iInterface != 0) - p_midi_host->all_string_indices[p_midi_host->num_string_indices++] = desc_itf->iInterface; + if (desc_itf->iInterface != 0) { + p_midi_host->all_string_indices[p_midi_host->num_string_indices++] = desc_itf->iInterface; + } p_desc = tu_desc_next(p_desc); TU_LOG1("MIDI opening Interface %u (addr = %u)\r\n", desc_itf->bInterfaceNumber, dev_addr); @@ -282,195 +286,169 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d // assume it is an interface header midi_desc_header_t const *p_mdh = (midi_desc_header_t const *)p_desc; TU_VERIFY((p_mdh->bDescriptorType == TUSB_DESC_CS_INTERFACE && p_mdh->bDescriptorSubType == MIDI_CS_INTERFACE_HEADER) || - (p_mdh->bDescriptorType == TUSB_DESC_CS_ENDPOINT && p_mdh->bDescriptorSubType == MIDI_CS_ENDPOINT_GENERAL) || - p_mdh->bDescriptorType == TUSB_DESC_ENDPOINT); + (p_mdh->bDescriptorType == TUSB_DESC_CS_ENDPOINT && p_mdh->bDescriptorSubType == MIDI_CS_ENDPOINT_GENERAL) || + p_mdh->bDescriptorType == TUSB_DESC_ENDPOINT); uint8_t prev_ep_addr = 0; // the CS endpoint descriptor is associated with the previous endpoint descriptor p_midi_host->itf_num = desc_itf->bInterfaceNumber; tusb_desc_endpoint_t const* in_desc = NULL; tusb_desc_endpoint_t const* out_desc = NULL; - while (len_parsed < max_len) - { + while (len_parsed < max_len) { TU_VERIFY((p_mdh->bDescriptorType == TUSB_DESC_CS_INTERFACE) || - (p_mdh->bDescriptorType == TUSB_DESC_CS_ENDPOINT && p_mdh->bDescriptorSubType == MIDI_CS_ENDPOINT_GENERAL) || - p_mdh->bDescriptorType == TUSB_DESC_ENDPOINT); + (p_mdh->bDescriptorType == TUSB_DESC_CS_ENDPOINT && p_mdh->bDescriptorSubType == MIDI_CS_ENDPOINT_GENERAL) || + p_mdh->bDescriptorType == TUSB_DESC_ENDPOINT); if (p_mdh->bDescriptorType == TUSB_DESC_CS_INTERFACE) { // The USB host doesn't really need this information unless it uses // the string descriptor for a jack or Element // assume it is an input jack - midi_desc_in_jack_t const *p_mdij = (midi_desc_in_jack_t const *)p_desc; - if (p_mdij->bDescriptorSubType == MIDI_CS_INTERFACE_HEADER) - { + midi_desc_in_jack_t const *p_mdij = (midi_desc_in_jack_t const *) p_desc; + if (p_mdij->bDescriptorSubType == MIDI_CS_INTERFACE_HEADER) { TU_LOG2("Found MIDI Interface Header\r\b"); - } - else if (p_mdij->bDescriptorSubType == MIDI_CS_INTERFACE_IN_JACK) - { + } else if (p_mdij->bDescriptorSubType == MIDI_CS_INTERFACE_IN_JACK) { // Then it is an in jack. TU_LOG2("Found in jack\r\n"); -#if CFG_MIDI_HOST_DEVSTRINGS - if (p_midi_host->next_in_jack < MAX_IN_JACKS) - { + #if CFG_MIDI_HOST_DEVSTRINGS + if (p_midi_host->next_in_jack < MAX_IN_JACKS) { p_midi_host->in_jack_info[p_midi_host->next_in_jack].jack_id = p_mdij->bJackID; p_midi_host->in_jack_info[p_midi_host->next_in_jack].jack_type = p_mdij->bJackType; p_midi_host->in_jack_info[p_midi_host->next_in_jack].string_index = p_mdij->iJack; ++p_midi_host->next_in_jack; // Keep track of any string descriptor that might be here - if (p_mdij->iJack != 0) + if (p_mdij->iJack != 0) { p_midi_host->all_string_indices[p_midi_host->num_string_indices++] = p_mdij->iJack; - + } } -#endif - } - else if (p_mdij->bDescriptorSubType == MIDI_CS_INTERFACE_OUT_JACK) - { + #endif + } else if (p_mdij->bDescriptorSubType == MIDI_CS_INTERFACE_OUT_JACK) { // then it is an out jack TU_LOG2("Found out jack\r\n"); -#if CFG_MIDI_HOST_DEVSTRINGS - if (p_midi_host->next_out_jack < MAX_OUT_JACKS) - { - midi_desc_out_jack_t const *p_mdoj = (midi_desc_out_jack_t const *)p_desc; + #if CFG_MIDI_HOST_DEVSTRINGS + if (p_midi_host->next_out_jack < MAX_OUT_JACKS) { + midi_desc_out_jack_t const *p_mdoj = (midi_desc_out_jack_t const *) p_desc; p_midi_host->out_jack_info[p_midi_host->next_out_jack].jack_id = p_mdoj->bJackID; p_midi_host->out_jack_info[p_midi_host->next_out_jack].jack_type = p_mdoj->bJackType; p_midi_host->out_jack_info[p_midi_host->next_out_jack].num_source_ids = p_mdoj->bNrInputPins; const struct associated_jack_s { - uint8_t id; - uint8_t pin; - } *associated_jack = (const struct associated_jack_s *)(p_desc+6); + uint8_t id; + uint8_t pin; + } *associated_jack = (const struct associated_jack_s *) (p_desc + 6); int jack; - for (jack = 0; jack < p_mdoj->bNrInputPins; jack++) - { + for (jack = 0; jack < p_mdoj->bNrInputPins; jack++) { p_midi_host->out_jack_info[p_midi_host->next_out_jack].source_ids[jack] = associated_jack->id; } - p_midi_host->out_jack_info[p_midi_host->next_out_jack].string_index = *(p_desc+6+p_mdoj->bNrInputPins*2); + p_midi_host->out_jack_info[p_midi_host->next_out_jack].string_index = *(p_desc + 6 + p_mdoj->bNrInputPins * 2); ++p_midi_host->next_out_jack; - if (p_mdoj->iJack != 0) + if (p_mdoj->iJack != 0) { p_midi_host->all_string_indices[p_midi_host->num_string_indices++] = p_mdoj->iJack; + } } -#endif - } - else if (p_mdij->bDescriptorSubType == MIDI_CS_INTERFACE_ELEMENT) - { + #endif + } else if (p_mdij->bDescriptorSubType == MIDI_CS_INTERFACE_ELEMENT) { // the it is an element; - #if CFG_MIDI_HOST_DEVSTRINGS + #if CFG_MIDI_HOST_DEVSTRINGS TU_LOG1("Found element; strings not supported\r\n"); - #else + #else TU_LOG2("Found element\r\n"); - #endif - } - else - { + #endif + } else { TU_LOG2("Unknown CS Interface sub-type %u\r\n", p_mdij->bDescriptorSubType); - TU_VERIFY(false); // unknown CS Interface sub-type + TU_VERIFY(false);// unknown CS Interface sub-type } len_parsed += p_mdij->bLength; - } - else if (p_mdh->bDescriptorType == TUSB_DESC_CS_ENDPOINT) - { + } else if (p_mdh->bDescriptorType == TUSB_DESC_CS_ENDPOINT) { TU_LOG2("found CS_ENDPOINT Descriptor for %u\r\n", prev_ep_addr); TU_VERIFY(prev_ep_addr != 0); // parse out the mapping between the device's embedded jacks and the endpoints // Each embedded IN jack is associated with an OUT endpoint - midi_cs_desc_endpoint_t const* p_csep = (midi_cs_desc_endpoint_t const*)p_mdh; - if (tu_edpt_dir(prev_ep_addr) == TUSB_DIR_OUT) - { + midi_cs_desc_endpoint_t const *p_csep = (midi_cs_desc_endpoint_t const *) p_mdh; + if (tu_edpt_dir(prev_ep_addr) == TUSB_DIR_OUT) { TU_VERIFY(p_midi_host->ep_out == prev_ep_addr); TU_VERIFY(p_midi_host->num_cables_tx == 0); p_midi_host->num_cables_tx = p_csep->bNumEmbMIDIJack; -#if CFG_MIDI_HOST_DEVSTRINGS + #if CFG_MIDI_HOST_DEVSTRINGS uint8_t jack; uint8_t max_jack = p_midi_host->num_cables_tx; - if (max_jack > sizeof(p_midi_host->ep_out_associated_jacks)) - { - max_jack = sizeof(p_midi_host->ep_out_associated_jacks); + if (max_jack > sizeof(p_midi_host->ep_out_associated_jacks)) { + max_jack = sizeof(p_midi_host->ep_out_associated_jacks); } - for (jack = 0; jack < max_jack; jack++) - { + for (jack = 0; jack < max_jack; jack++) { p_midi_host->ep_out_associated_jacks[jack] = p_csep->baAssocJackID[jack]; } -#endif - } - else - { + #endif + } else { TU_VERIFY(p_midi_host->ep_in == prev_ep_addr); TU_VERIFY(p_midi_host->num_cables_rx == 0); p_midi_host->num_cables_rx = p_csep->bNumEmbMIDIJack; -#if CFG_MIDI_HOST_DEVSTRINGS + #if CFG_MIDI_HOST_DEVSTRINGS uint8_t jack; uint8_t max_jack = p_midi_host->num_cables_rx; - if (max_jack > sizeof(p_midi_host->ep_in_associated_jacks)) - { - max_jack = sizeof(p_midi_host->ep_in_associated_jacks); + if (max_jack > sizeof(p_midi_host->ep_in_associated_jacks)) { + max_jack = sizeof(p_midi_host->ep_in_associated_jacks); } - for (jack = 0; jack < max_jack; jack++) - { + for (jack = 0; jack < max_jack; jack++) { p_midi_host->ep_in_associated_jacks[jack] = p_csep->baAssocJackID[jack]; } -#endif + #endif } len_parsed += p_csep->bLength; prev_ep_addr = 0; - } - else if (p_mdh->bDescriptorType == TUSB_DESC_ENDPOINT) { + } else if (p_mdh->bDescriptorType == TUSB_DESC_ENDPOINT) { // parse out the bulk endpoint info - tusb_desc_endpoint_t const *p_ep = (tusb_desc_endpoint_t const *)p_mdh; + tusb_desc_endpoint_t const *p_ep = (tusb_desc_endpoint_t const *) p_mdh; TU_LOG2("found ENDPOINT Descriptor for %u\r\n", p_ep->bEndpointAddress); - if (tu_edpt_dir(p_ep->bEndpointAddress) == TUSB_DIR_OUT) - { + if (tu_edpt_dir(p_ep->bEndpointAddress) == TUSB_DIR_OUT) { TU_VERIFY(p_midi_host->ep_out == 0); TU_VERIFY(p_midi_host->num_cables_tx == 0); p_midi_host->ep_out = p_ep->bEndpointAddress; p_midi_host->ep_out_max = p_ep->wMaxPacketSize; - if (p_midi_host->ep_out_max > CFG_TUH_MIDI_TX_BUFSIZE) + if (p_midi_host->ep_out_max > CFG_TUH_MIDI_TX_BUFSIZE) { p_midi_host->ep_out_max = CFG_TUH_MIDI_TX_BUFSIZE; + } prev_ep_addr = p_midi_host->ep_out; out_desc = p_ep; - } - else - { + } else { TU_VERIFY(p_midi_host->ep_in == 0); TU_VERIFY(p_midi_host->num_cables_rx == 0); p_midi_host->ep_in = p_ep->bEndpointAddress; p_midi_host->ep_in_max = p_ep->wMaxPacketSize; - if (p_midi_host->ep_in_max > CFG_TUH_MIDI_RX_BUFSIZE) + if (p_midi_host->ep_in_max > CFG_TUH_MIDI_RX_BUFSIZE) { p_midi_host->ep_in_max = CFG_TUH_MIDI_RX_BUFSIZE; + } prev_ep_addr = p_midi_host->ep_in; in_desc = p_ep; } len_parsed += p_mdh->bLength; } p_desc = tu_desc_next(p_desc); - p_mdh = (midi_desc_header_t const *)p_desc; + p_mdh = (midi_desc_header_t const *) p_desc; } TU_VERIFY((p_midi_host->ep_out != 0 && p_midi_host->num_cables_tx != 0) || (p_midi_host->ep_in != 0 && p_midi_host->num_cables_rx != 0)); TU_LOG1("MIDI descriptor parsed successfully\r\n"); // remove duplicate string indices - for (int idx=0; idx < p_midi_host->num_string_indices; idx++) { - for (int jdx = idx+1; jdx < p_midi_host->num_string_indices; jdx++) { - while (jdx < p_midi_host->num_string_indices && p_midi_host->all_string_indices[idx] == p_midi_host->all_string_indices[jdx]) { - // delete the duplicate by overwriting it with the last entry and reducing the number of entries by 1 - p_midi_host->all_string_indices[jdx] = p_midi_host->all_string_indices[p_midi_host->num_string_indices-1]; - --p_midi_host->num_string_indices; - } + for (int idx = 0; idx < p_midi_host->num_string_indices; idx++) { + for (int jdx = idx + 1; jdx < p_midi_host->num_string_indices; jdx++) { + while (jdx < p_midi_host->num_string_indices && p_midi_host->all_string_indices[idx] == p_midi_host->all_string_indices[jdx]) { + // delete the duplicate by overwriting it with the last entry and reducing the number of entries by 1 + p_midi_host->all_string_indices[jdx] = p_midi_host->all_string_indices[p_midi_host->num_string_indices - 1]; + --p_midi_host->num_string_indices; } + } } - if (in_desc) - { + if (in_desc) { TU_ASSERT(tuh_edpt_open(dev_addr, in_desc)); // Some devices always return exactly the request length so transfers won't complete // unless you assume every transfer is the last one. // TODO usbh_edpt_force_last_buffer(dev_addr, p_midi_host->ep_in, true); } - if (out_desc) - { + if (out_desc) { TU_ASSERT(tuh_edpt_open(dev_addr, out_desc)); } p_midi_host->dev_addr = dev_addr; - if (tuh_midi_mount_cb) - { + if (tuh_midi_mount_cb) { tuh_midi_mount_cb(dev_addr, p_midi_host->ep_in, p_midi_host->ep_out, p_midi_host->num_cables_rx, p_midi_host->num_cables_tx); } return true; @@ -478,7 +456,7 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d bool tuh_midi_configured(uint8_t dev_addr) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); return p_midi_host->configured; } @@ -486,7 +464,7 @@ bool tuh_midi_configured(uint8_t dev_addr) bool midih_set_config(uint8_t dev_addr, uint8_t itf_num) { (void) itf_num; - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); p_midi_host->configured = true; @@ -498,43 +476,36 @@ bool midih_set_config(uint8_t dev_addr, uint8_t itf_num) //--------------------------------------------------------------------+ // Stream API //--------------------------------------------------------------------+ -static uint32_t write_flush(uint8_t dev_addr, midih_interface_t* midi) -{ +static uint32_t write_flush(uint8_t dev_addr, midih_interface_t* midi) { // No data to send - if ( !tu_fifo_count(&midi->tx_ff) ) return 0; + if ( !tu_fifo_count(&midi->tx_ff) ) { return 0; } // skip if previous transfer not complete TU_VERIFY( usbh_edpt_claim(dev_addr, midi->ep_out) ); uint16_t count = tu_fifo_read_n(&midi->tx_ff, midi->epout_buf, midi->ep_out_max); - if (count) - { - TU_ASSERT( usbh_edpt_xfer(dev_addr, midi->ep_out, midi->epout_buf, count), 0 ); + if (count) { + TU_ASSERT(usbh_edpt_xfer(dev_addr, midi->ep_out, midi->epout_buf, count), 0); return count; - }else - { + } else { // Release endpoint since we don't make any transfer usbh_edpt_release(dev_addr, midi->ep_out); return 0; } } -bool tuh_midi_read_poll( uint8_t dev_addr ) -{ - midih_interface_t *p_midi_host = get_midi_host(dev_addr); +bool tuh_midi_read_poll(uint8_t dev_addr) { + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); bool result = false; bool in_edpt_not_busy = !usbh_edpt_busy(dev_addr, p_midi_host->ep_in); - if (in_edpt_not_busy) - { + if (in_edpt_not_busy) { TU_LOG2("Requesting poll IN endpoint %d\r\n", p_midi_host->ep_in); TU_ASSERT(usbh_edpt_xfer(p_midi_host->dev_addr, p_midi_host->ep_in, p_midi_host->epin_buf, p_midi_host->ep_in_max), 0); result = true; - } - else - { + } else { // Maybe the IN endpoint is only busy because the RP2040 host hardware // is retrying a NAK'd IN transfer forever. Try aborting the NAK'd // transfer to allow other transfers to happen on the one shared @@ -546,7 +517,7 @@ bool tuh_midi_read_poll( uint8_t dev_addr ) uint32_t tuh_midi_stream_write (uint8_t dev_addr, uint8_t cable_num, uint8_t const* buffer, uint32_t bufsize) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); TU_VERIFY(cable_num < p_midi_host->num_cables_tx); midi_stream_t *stream = &p_midi_host->stream_write; @@ -673,7 +644,7 @@ uint32_t tuh_midi_stream_write (uint8_t dev_addr, uint8_t cable_num, uint8_t con bool tuh_midi_packet_write (uint8_t dev_addr, uint8_t const packet[4]) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); if (tu_fifo_remaining(&p_midi_host->tx_ff) < 4) @@ -688,7 +659,7 @@ bool tuh_midi_packet_write (uint8_t dev_addr, uint8_t const packet[4]) uint32_t tuh_midi_stream_flush( uint8_t dev_addr ) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); uint32_t bytes_flushed = 0; @@ -703,7 +674,7 @@ uint32_t tuh_midi_stream_flush( uint8_t dev_addr ) //--------------------------------------------------------------------+ uint8_t tuh_midih_get_num_tx_cables (uint8_t dev_addr) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); TU_VERIFY(p_midi_host->ep_out != 0); // returns 0 if fails return p_midi_host->num_cables_tx; @@ -711,7 +682,7 @@ uint8_t tuh_midih_get_num_tx_cables (uint8_t dev_addr) uint8_t tuh_midih_get_num_rx_cables (uint8_t dev_addr) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); TU_VERIFY(p_midi_host->ep_in != 0); // returns 0 if fails return p_midi_host->num_cables_rx; @@ -719,7 +690,7 @@ uint8_t tuh_midih_get_num_rx_cables (uint8_t dev_addr) bool tuh_midi_packet_read (uint8_t dev_addr, uint8_t packet[4]) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); TU_VERIFY(tu_fifo_count(&p_midi_host->rx_ff) >= 4); return tu_fifo_read_n(&p_midi_host->rx_ff, packet, 4) == 4; @@ -727,7 +698,7 @@ bool tuh_midi_packet_read (uint8_t dev_addr, uint8_t packet[4]) uint32_t tuh_midi_stream_read (uint8_t dev_addr, uint8_t *p_cable_num, uint8_t *p_buffer, uint16_t bufsize) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); uint32_t bytes_buffered = 0; TU_ASSERT(p_cable_num); @@ -848,7 +819,7 @@ uint32_t tuh_midi_stream_read (uint8_t dev_addr, uint8_t *p_cable_num, uint8_t * uint8_t tuh_midi_get_num_rx_cables(uint8_t dev_addr) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); uint8_t num_cables = 0; if (p_midi_host) @@ -860,7 +831,7 @@ uint8_t tuh_midi_get_num_rx_cables(uint8_t dev_addr) uint8_t tuh_midi_get_num_tx_cables(uint8_t dev_addr) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); uint8_t num_cables = 0; if (p_midi_host) @@ -897,7 +868,7 @@ static uint8_t find_string_index(midih_interface_t *ptr, uint8_t jack_id) uint8_t tuh_midi_get_rx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint8_t max_istrings) { uint8_t nstrings = 0; - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); nstrings = p_midi_host->num_cables_rx; if (nstrings > max_istrings) @@ -916,7 +887,7 @@ uint8_t tuh_midi_get_rx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint uint8_t tuh_midi_get_tx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint8_t max_istrings) { uint8_t nstrings = 0; - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); nstrings = p_midi_host->num_cables_tx; if (nstrings > max_istrings) @@ -935,7 +906,7 @@ uint8_t tuh_midi_get_tx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint uint8_t tuh_midi_get_all_istrings(uint8_t dev_addr, const uint8_t** istrings) { - midih_interface_t *p_midi_host = get_midi_host(dev_addr); + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); uint8_t nstrings = p_midi_host->num_string_indices; if (nstrings) diff --git a/src/class/midi/midi_host.h b/src/class/midi/midi_host.h index edf57bfcb..bf2378168 100644 --- a/src/class/midi/midi_host.h +++ b/src/class/midi/midi_host.h @@ -37,16 +37,25 @@ //--------------------------------------------------------------------+ // Class Driver Configuration //--------------------------------------------------------------------+ +#ifndef CFG_TUH_MAX_CABLES +#define CFG_TUH_MAX_CABLES 16 +#endif + +#ifndef CFG_TUH_MIDI_RX_BUFSIZE +#define CFG_TUH_MIDI_RX_BUFSIZE 64 +#endif -// TODO Highspeed bulk transfer can be up to 512 bytes -#ifndef CFG_TUH_HID_EPIN_BUFSIZE -#define CFG_TUH_HID_EPIN_BUFSIZE 64 +#ifndef CFG_TUH_MIDI_TX_BUFSIZE +#define CFG_TUH_MIDI_TX_BUFSIZE 64 #endif -#ifndef CFG_TUH_HID_EPOUT_BUFSIZE -#define CFG_TUH_HID_EPOUT_BUFSIZE 64 +#ifndef CFG_TUH_MIDI_EP_BUFSIZE +#define CFG_TUH_MIDI_EP_BUFSIZE 64 #endif +#ifndef CFG_MIDI_HOST_DEVSTRINGS +#define CFG_MIDI_HOST_DEVSTRINGS 0 +#endif //--------------------------------------------------------------------+ // Application API (Single Interface) diff --git a/src/host/usbh.c b/src/host/usbh.c index e38ee3187..f874121a3 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -1488,9 +1488,7 @@ static void process_enumeration(tuh_xfer_t* xfer) { dev->i_product = desc_device->iProduct; dev->i_serial = desc_device->iSerialNumber; - if (tuh_desc_device_cb) { - tuh_desc_device_cb(daddr, (tusb_desc_device_t const*) _usbh_epbuf.ctrl); - } + // tuh_descriptor_device_cb(daddr, (tusb_desc_device_t const*) _usbh_epbuf.ctrl); // Get 9-byte for total length uint8_t const config_idx = CONFIG_NUM - 1; @@ -1519,9 +1517,7 @@ static void process_enumeration(tuh_xfer_t* xfer) { } case ENUM_SET_CONFIG: - if (tuh_desc_config_cb) { - tuh_desc_config_cb(daddr, (const tusb_desc_configuration_t*) _usbh_epbuf.ctrl); - } + // tuh_desc_configuration_cb(daddr, CONFIG_NUM-1, (const tusb_desc_configuration_t*) _usbh_epbuf.ctrl); TU_ASSERT(tuh_configuration_set(daddr, CONFIG_NUM, process_enumeration, ENUM_CONFIG_DRIVER),); break; diff --git a/src/host/usbh.h b/src/host/usbh.h index 500b044f8..3bcdd3657 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -96,11 +96,11 @@ typedef union { // APPLICATION CALLBACK //--------------------------------------------------------------------+ -// Give the application an opportunity to grab the device descriptor -TU_ATTR_WEAK void tuh_desc_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device); +// Invoked when enumeration get device descriptor +// TU_ATTR_WEAK void tuh_descriptor_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device); -// Give the application an opportunity to grab the configuration descriptor -TU_ATTR_WEAK void tuh_desc_config_cb(uint8_t daddr, const tusb_desc_configuration_t *desc_config); +// Invoked when enumeration get configuration descriptor +// TU_ATTR_WEAK void tuh_desc_configuration_cb(uint8_t daddr, uint8_t cfg_index, const tusb_desc_configuration_t *desc_config); // Invoked when a device is mounted (configured) TU_ATTR_WEAK void tuh_mount_cb (uint8_t daddr); -- cgit v1.3.1 From bad6cbe48930c0c5250b8a717a46cc1f6d83de56 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 13 Feb 2025 15:52:30 +0700 Subject: update midi host to use endpoint stream API --- src/class/cdc/cdc_host.c | 4 +- src/class/midi/midi_host.c | 445 +++++++++++++++------------------------------ src/class/midi/midi_host.h | 25 +-- src/common/tusb_private.h | 10 +- src/host/usbh.c | 3 +- src/host/usbh.h | 3 + 6 files changed, 174 insertions(+), 316 deletions(-) (limited to 'src/host') diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c index e817ebc7e..4058857c5 100644 --- a/src/class/cdc/cdc_host.c +++ b/src/class/cdc/cdc_host.c @@ -691,10 +691,10 @@ bool cdch_xfer_cb(uint8_t daddr, uint8_t ep_addr, xfer_result_t event, uint32_t } } else if ( ep_addr == p_cdc->stream.rx.ep_addr ) { #if CFG_TUH_CDC_FTDI - if (p_cdc->serial_drid == SERIAL_DRIVER_FTDI) { + if (p_cdc->serial_drid == SERIAL_DRIVER_FTDI && xferred_bytes > 2) { // FTDI reserve 2 bytes for status // uint8_t status[2] = {p_cdc->stream.rx.ep_buf[0], p_cdc->stream.rx.ep_buf[1]}; - tu_edpt_stream_read_xfer_complete_offset(&p_cdc->stream.rx, xferred_bytes, 2); + tu_edpt_stream_read_xfer_complete_with_buf(&p_cdc->stream.rx, p_cdc->stream.rx.ep_buf+2, xferred_bytes-2); }else #endif { diff --git a/src/class/midi/midi_host.c b/src/class/midi/midi_host.c index 21fe09143..eb3f0b070 100644 --- a/src/class/midi/midi_host.c +++ b/src/class/midi/midi_host.c @@ -45,15 +45,12 @@ typedef struct uint8_t total; }midi_stream_t; -typedef struct -{ +typedef struct { uint8_t dev_addr; uint8_t itf_num; uint8_t ep_in; // IN endpoint address uint8_t ep_out; // OUT endpoint address - uint16_t ep_in_max; // min( CFG_TUH_MIDI_RX_BUFSIZE, wMaxPacketSize of the IN endpoint) - uint16_t ep_out_max; // min( CFG_TUH_MIDI_TX_BUFSIZE, wMaxPacketSize of the OUT endpoint) uint8_t num_cables_rx; // IN endpoint CS descriptor bNumEmbMIDIJack value uint8_t num_cables_tx; // OUT endpoint CS descriptor bNumEmbMIDIJack value @@ -65,22 +62,14 @@ typedef struct midi_stream_t stream_read; /*------------- From this point, data is not cleared by bus reset -------------*/ - // Endpoint FIFOs - tu_fifo_t rx_ff; - tu_fifo_t tx_ff; - - - uint8_t rx_ff_buf[CFG_TUH_MIDI_RX_BUFSIZE]; - uint8_t tx_ff_buf[CFG_TUH_MIDI_TX_BUFSIZE]; - - #if CFG_FIFO_MUTEX - osal_mutex_def_t rx_ff_mutex; - osal_mutex_def_t tx_ff_mutex; - #endif + // Endpoint stream + struct { + tu_edpt_stream_t tx; + tu_edpt_stream_t rx; - // Endpoint Transfer buffer - CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUH_MIDI_EP_BUFSIZE]; - CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUH_MIDI_EP_BUFSIZE]; + uint8_t rx_ff_buf[CFG_TUH_MIDI_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUH_MIDI_TX_BUFSIZE]; + } ep_stream; bool configured; @@ -109,15 +98,17 @@ typedef struct #endif }midih_interface_t; -static midih_interface_t _midi_host[CFG_TUH_MIDI]; +typedef struct { + TUH_EPBUF_DEF(tx, TUH_EPSIZE_BULK_MPS); + TUH_EPBUF_DEF(rx, TUH_EPSIZE_BULK_MPS); +} midih_epbuf_t; -//------------- Internal prototypes -------------// -static uint32_t write_flush(uint8_t dev_addr, midih_interface_t* midi); +static midih_interface_t _midi_host[CFG_TUH_MIDI]; +CFG_TUH_MEM_SECTION static midih_epbuf_t _midi_epbuf[CFG_TUH_MIDI]; //--------------------------------------------------------------------+ // Helper //--------------------------------------------------------------------+ - TU_ATTR_ALWAYS_INLINE static inline midih_interface_t* find_midi_by_daddr(uint8_t dev_addr) { for (uint8_t i = 0; i < CFG_TUH_MIDI; i++) { if (_midi_host[i].dev_addr == dev_addr) { @@ -131,85 +122,27 @@ TU_ATTR_ALWAYS_INLINE static inline midih_interface_t* find_new_midi(void) { return find_midi_by_daddr(0); } - //--------------------------------------------------------------------+ // USBH API //--------------------------------------------------------------------+ bool midih_init(void) { tu_memclr(&_midi_host, sizeof(_midi_host)); - // config fifos for (int inst = 0; inst < CFG_TUH_MIDI; inst++) { midih_interface_t *p_midi_host = &_midi_host[inst]; - tu_fifo_config(&p_midi_host->rx_ff, p_midi_host->rx_ff_buf, CFG_TUH_MIDI_RX_BUFSIZE, 1, false);// true, true - tu_fifo_config(&p_midi_host->tx_ff, p_midi_host->tx_ff_buf, CFG_TUH_MIDI_TX_BUFSIZE, 1, false);// OBVS. - - #if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&p_midi_host->rx_ff, NULL, osal_mutex_create(&p_midi_host->rx_ff_mutex)); - tu_fifo_config_mutex(&p_midi_host->tx_ff, osal_mutex_create(&p_midi_host->tx_ff_mutex), NULL); - #endif + tu_edpt_stream_init(&p_midi_host->ep_stream.rx, true, false, false, + p_midi_host->ep_stream.rx_ff_buf, CFG_TUH_MIDI_RX_BUFSIZE, _midi_epbuf->rx, TUH_EPSIZE_BULK_MPS); + tu_edpt_stream_init(&p_midi_host->ep_stream.tx, true, true, false, + p_midi_host->ep_stream.tx_ff_buf, CFG_TUH_MIDI_TX_BUFSIZE, _midi_epbuf->tx, TUH_EPSIZE_BULK_MPS); } return true; } -bool midih_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) -{ - (void)result; - midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); - TU_VERIFY(p_midi_host != NULL); - if ( ep_addr == p_midi_host->ep_in) - { - if (0 == xferred_bytes) - { - return true; // No data to handle - } - - // receive new data if available - uint32_t packets_queued = 0; - if (xferred_bytes) - { - // put in the RX FIFO only non-zero MIDI IN 4-byte packets - uint8_t* buf = p_midi_host->epin_buf; - uint32_t npackets = xferred_bytes / 4; - uint32_t packet_num; - for (packet_num = 0; packet_num < npackets; packet_num++) - { - // some devices send back all zero packets even if there is no data ready - uint32_t packet = (uint32_t)((*buf)<<24) | ((uint32_t)(*(buf+1))<<16) | ((uint32_t)(*(buf+2))<<8) | ((uint32_t)(*(buf+3))); - if (packet != 0) - { - tu_fifo_write_n(&p_midi_host->rx_ff, buf, 4); - ++packets_queued; - TU_LOG3("MIDI RX=%08x\r\n", packet); - } - buf += 4; - } - } - // invoke receive callback if available - if (tuh_midi_rx_cb) - { - tuh_midi_rx_cb(dev_addr, packets_queued); - } - } - else if ( ep_addr == p_midi_host->ep_out ) - { - if (0 == write_flush(dev_addr, p_midi_host)) - { - // If there is no data left, a ZLP should be sent if - // xferred_bytes is multiple of EP size and not zero - if ( !tu_fifo_count(&p_midi_host->tx_ff) && xferred_bytes && (0 == (xferred_bytes % p_midi_host->ep_out_max)) ) - { - if ( usbh_edpt_claim(dev_addr, p_midi_host->ep_out) ) - { - TU_ASSERT(usbh_edpt_xfer(dev_addr, p_midi_host->ep_out, XFER_RESULT_SUCCESS, 0)); - } - } - } - if (tuh_midi_tx_cb) - { - tuh_midi_tx_cb(dev_addr); - } +bool midih_deinit(void) { + for (size_t i = 0; i < CFG_TUH_MIDI; i++) { + midih_interface_t* p_midi = &_midi_host[i]; + tu_edpt_stream_deinit(&p_midi->ep_stream.rx); + tu_edpt_stream_deinit(&p_midi->ep_stream.tx); } - return true; } @@ -221,26 +154,67 @@ void midih_close(uint8_t dev_addr) { if (tuh_midi_umount_cb) { tuh_midi_umount_cb(dev_addr, 0); } - tu_fifo_clear(&p_midi_host->rx_ff); - tu_fifo_clear(&p_midi_host->tx_ff); p_midi_host->ep_in = 0; - p_midi_host->ep_in_max = 0; p_midi_host->ep_out = 0; - p_midi_host->ep_out_max = 0; p_midi_host->itf_num = 0; p_midi_host->num_cables_rx = 0; p_midi_host->num_cables_tx = 0; - p_midi_host->dev_addr = 255; // invalid + p_midi_host->dev_addr = 0; p_midi_host->configured = false; tu_memclr(&p_midi_host->stream_read, sizeof(p_midi_host->stream_read)); tu_memclr(&p_midi_host->stream_write, sizeof(p_midi_host->stream_write)); + + tu_edpt_stream_close(&p_midi_host->ep_stream.rx); + tu_edpt_stream_close(&p_midi_host->ep_stream.tx); +} + +bool midih_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { + (void) result; + midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); + TU_VERIFY(p_midi_host != NULL); + if (ep_addr == p_midi_host->ep_stream.rx.ep_addr) { + // receive new data if available + if (xferred_bytes) { + // put in the RX FIFO only non-zero MIDI IN 4-byte packets + uint32_t packets_queued = 0; + uint8_t *buf = _midi_epbuf->rx; + const uint32_t npackets = xferred_bytes / 4; + for (uint32_t p = 0; p < npackets; p++) { + // some devices send back all zero packets even if there is no data ready + const uint32_t packet = tu_unaligned_read32(buf); + if (packet != 0) { + tu_edpt_stream_read_xfer_complete_with_buf(&p_midi_host->ep_stream.rx, buf, 4); + ++packets_queued; + TU_LOG3("MIDI RX=%08x\r\n", packet); + } + buf += 4; + } + + if (tuh_midi_rx_cb) { + tuh_midi_rx_cb(dev_addr, packets_queued); // invoke receive callback + } + } + + // prepare for next transfer if needed + tu_edpt_stream_read_xfer(dev_addr, &p_midi_host->ep_stream.rx); + } else if (ep_addr == p_midi_host->ep_stream.tx.ep_addr) { + if (tuh_midi_tx_cb) { + tuh_midi_tx_cb(dev_addr); + } + if (0 == tu_edpt_stream_write_xfer(dev_addr, &p_midi_host->ep_stream.tx)) { + // If there is no data left, a ZLP should be sent if + // xferred_bytes is multiple of EP size and not zero + tu_edpt_stream_write_zlp_if_needed(dev_addr, &p_midi_host->ep_stream.tx, xferred_bytes); + } + } + + return true; } //--------------------------------------------------------------------+ // Enumeration //--------------------------------------------------------------------+ -bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len) -{ +bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len) { (void) rhport; midih_interface_t *p_midi_host = find_new_midi(); @@ -402,20 +376,12 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d TU_VERIFY(p_midi_host->ep_out == 0); TU_VERIFY(p_midi_host->num_cables_tx == 0); p_midi_host->ep_out = p_ep->bEndpointAddress; - p_midi_host->ep_out_max = p_ep->wMaxPacketSize; - if (p_midi_host->ep_out_max > CFG_TUH_MIDI_TX_BUFSIZE) { - p_midi_host->ep_out_max = CFG_TUH_MIDI_TX_BUFSIZE; - } prev_ep_addr = p_midi_host->ep_out; out_desc = p_ep; } else { TU_VERIFY(p_midi_host->ep_in == 0); TU_VERIFY(p_midi_host->num_cables_rx == 0); p_midi_host->ep_in = p_ep->bEndpointAddress; - p_midi_host->ep_in_max = p_ep->wMaxPacketSize; - if (p_midi_host->ep_in_max > CFG_TUH_MIDI_RX_BUFSIZE) { - p_midi_host->ep_in_max = CFG_TUH_MIDI_RX_BUFSIZE; - } prev_ep_addr = p_midi_host->ep_in; in_desc = p_ep; } @@ -439,36 +405,34 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d } if (in_desc) { TU_ASSERT(tuh_edpt_open(dev_addr, in_desc)); - // Some devices always return exactly the request length so transfers won't complete - // unless you assume every transfer is the last one. - // TODO usbh_edpt_force_last_buffer(dev_addr, p_midi_host->ep_in, true); + tu_edpt_stream_open(&p_midi_host->ep_stream.rx, in_desc); } if (out_desc) { TU_ASSERT(tuh_edpt_open(dev_addr, out_desc)); + tu_edpt_stream_open(&p_midi_host->ep_stream.tx, out_desc); } p_midi_host->dev_addr = dev_addr; - if (tuh_midi_mount_cb) { - tuh_midi_mount_cb(dev_addr, p_midi_host->ep_in, p_midi_host->ep_out, p_midi_host->num_cables_rx, p_midi_host->num_cables_tx); - } return true; } -bool tuh_midi_configured(uint8_t dev_addr) -{ +bool tuh_midi_configured(uint8_t dev_addr) { midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); return p_midi_host->configured; } -bool midih_set_config(uint8_t dev_addr, uint8_t itf_num) -{ +bool midih_set_config(uint8_t dev_addr, uint8_t itf_num) { (void) itf_num; midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); p_midi_host->configured = true; - // TODO I don't think there are any special config things to do for MIDI + if (tuh_midi_mount_cb) { + tuh_midi_mount_cb(dev_addr, p_midi_host->ep_in, p_midi_host->ep_out, p_midi_host->num_cables_rx, p_midi_host->num_cables_tx); + } + + // No special config things to do for MIDI usbh_driver_set_config_complete(dev_addr, p_midi_host->itf_num); return true; } @@ -476,71 +440,32 @@ bool midih_set_config(uint8_t dev_addr, uint8_t itf_num) //--------------------------------------------------------------------+ // Stream API //--------------------------------------------------------------------+ -static uint32_t write_flush(uint8_t dev_addr, midih_interface_t* midi) { - // No data to send - if ( !tu_fifo_count(&midi->tx_ff) ) { return 0; } - - // skip if previous transfer not complete - TU_VERIFY( usbh_edpt_claim(dev_addr, midi->ep_out) ); - - uint16_t count = tu_fifo_read_n(&midi->tx_ff, midi->epout_buf, midi->ep_out_max); - - if (count) { - TU_ASSERT(usbh_edpt_xfer(dev_addr, midi->ep_out, midi->epout_buf, count), 0); - return count; - } else { - // Release endpoint since we don't make any transfer - usbh_edpt_release(dev_addr, midi->ep_out); - return 0; - } -} - bool tuh_midi_read_poll(uint8_t dev_addr) { midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); - bool result = false; - - bool in_edpt_not_busy = !usbh_edpt_busy(dev_addr, p_midi_host->ep_in); - if (in_edpt_not_busy) { - TU_LOG2("Requesting poll IN endpoint %d\r\n", p_midi_host->ep_in); - TU_ASSERT(usbh_edpt_xfer(p_midi_host->dev_addr, p_midi_host->ep_in, p_midi_host->epin_buf, p_midi_host->ep_in_max), 0); - result = true; - } else { - // Maybe the IN endpoint is only busy because the RP2040 host hardware - // is retrying a NAK'd IN transfer forever. Try aborting the NAK'd - // transfer to allow other transfers to happen on the one shared - // epx endpoint. - // TODO for RP2040 USB shared endpoint: usbh_edpt_clear_in_on_nak(p_midi_host->dev_addr, p_midi_host->ep_in); - } - return result; + return tu_edpt_stream_read_xfer(dev_addr, &p_midi_host->ep_stream.rx) > 0; } -uint32_t tuh_midi_stream_write (uint8_t dev_addr, uint8_t cable_num, uint8_t const* buffer, uint32_t bufsize) -{ +uint32_t tuh_midi_stream_write(uint8_t dev_addr, uint8_t cable_num, uint8_t const *buffer, uint32_t bufsize) { midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); TU_VERIFY(cable_num < p_midi_host->num_cables_tx); midi_stream_t *stream = &p_midi_host->stream_write; uint32_t i = 0; - while ( (i < bufsize) && (tu_fifo_remaining(&p_midi_host->tx_ff) >= 4) ) - { + while ((i < bufsize) && (tu_edpt_stream_write_available(dev_addr, &p_midi_host->ep_stream.tx) >= 4)) { uint8_t const data = buffer[i]; i++; - if (data >= MIDI_STATUS_SYSREAL_TIMING_CLOCK) - { + if (data >= MIDI_STATUS_SYSREAL_TIMING_CLOCK) { // real-time messages need to be sent right away midi_stream_t streamrt; streamrt.buffer[0] = MIDI_CIN_SYSEX_END_1BYTE; streamrt.buffer[1] = data; streamrt.index = 2; streamrt.total = 2; - uint16_t const count = tu_fifo_write_n(&p_midi_host->tx_ff, streamrt.buffer, 4); - // FIFO overflown, since we already check fifo remaining. It is probably race condition - TU_ASSERT(count == 4, i); - } - else if ( stream->index == 0 ) - { + uint32_t const count = tu_edpt_stream_write(dev_addr, &p_midi_host->ep_stream.tx, streamrt.buffer, 4); + TU_ASSERT(count == 4, i); // Check FIFO overflown, since we already check fifo remaining. It is probably race condition + } else if (stream->index == 0) { //------------- New event packet -------------// uint8_t const msg = data >> 4; @@ -549,56 +474,37 @@ uint32_t tuh_midi_stream_write (uint8_t dev_addr, uint8_t cable_num, uint8_t con stream->buffer[1] = data; // Check to see if we're still in a SysEx transmit. - if ( stream->buffer[0] == MIDI_CIN_SYSEX_START ) - { - if ( data == MIDI_STATUS_SYSEX_END ) - { + if (stream->buffer[0] == MIDI_CIN_SYSEX_START) { + if (data == MIDI_STATUS_SYSEX_END) { stream->buffer[0] = MIDI_CIN_SYSEX_END_1BYTE; stream->total = 2; - } - else - { + } else { stream->total = 4; } - } - else if ( (msg >= 0x8 && msg <= 0xB) || msg == 0xE ) - { + } else if ((msg >= 0x8 && msg <= 0xB) || msg == 0xE) { // Channel Voice Messages stream->buffer[0] = (uint8_t) ((cable_num << 4) | msg); stream->total = 4; - } - else if ( msg == 0xC || msg == 0xD) - { + } else if (msg == 0xC || msg == 0xD) { // Channel Voice Messages, two-byte variants (Program Change and Channel Pressure) stream->buffer[0] = (uint8_t) ((cable_num << 4) | msg); stream->total = 3; - } - else if ( msg == 0xf ) - { + } else if (msg == 0xf) { // System message - if ( data == MIDI_STATUS_SYSEX_START ) - { + if (data == MIDI_STATUS_SYSEX_START) { stream->buffer[0] = MIDI_CIN_SYSEX_START; stream->total = 4; - } - else if ( data == MIDI_STATUS_SYSCOM_TIME_CODE_QUARTER_FRAME || data == MIDI_STATUS_SYSCOM_SONG_SELECT ) - { + } else if (data == MIDI_STATUS_SYSCOM_TIME_CODE_QUARTER_FRAME || data == MIDI_STATUS_SYSCOM_SONG_SELECT) { stream->buffer[0] = MIDI_CIN_SYSCOM_2BYTE; stream->total = 3; - } - else if ( data == MIDI_STATUS_SYSCOM_SONG_POSITION_POINTER ) - { + } else if (data == MIDI_STATUS_SYSCOM_SONG_POSITION_POINTER) { stream->buffer[0] = MIDI_CIN_SYSCOM_3BYTE; stream->total = 4; - } - else - { + } else { stream->buffer[0] = MIDI_CIN_SYSEX_END_1BYTE; stream->total = 2; } - } - else - { + } else { // Pack individual bytes if we don't support packing them into words. stream->buffer[0] = (uint8_t) (cable_num << 4 | 0xf); stream->buffer[2] = 0; @@ -606,30 +512,25 @@ uint32_t tuh_midi_stream_write (uint8_t dev_addr, uint8_t cable_num, uint8_t con stream->index = 2; stream->total = 2; } - } - else - { + } else { //------------- On-going (buffering) packet -------------// - TU_ASSERT(stream->index < 4, i); stream->buffer[stream->index] = data; stream->index++; // See if this byte ends a SysEx. - if ( stream->buffer[0] == MIDI_CIN_SYSEX_START && data == MIDI_STATUS_SYSEX_END ) - { + if (stream->buffer[0] == MIDI_CIN_SYSEX_START && data == MIDI_STATUS_SYSEX_END) { stream->buffer[0] = MIDI_CIN_SYSEX_START + (stream->index - 1); stream->total = stream->index; } } // Send out packet - if ( stream->index >= 2 && stream->index == stream->total ) - { + if (stream->index >= 2 && stream->index == stream->total) { // zeroes unused bytes - for(uint8_t idx = stream->total; idx < 4; idx++) stream->buffer[idx] = 0; + for (uint8_t idx = stream->total; idx < 4; idx++) { stream->buffer[idx] = 0; } TU_LOG3_MEM(stream->buffer, 4, 2); - uint16_t const count = tu_fifo_write_n(&p_midi_host->tx_ff, stream->buffer, 4); + uint32_t const count = tu_edpt_stream_write(dev_addr, &p_midi_host->ep_stream.tx, stream->buffer, 4); // complete current event packet, reset stream stream->index = 0; @@ -642,32 +543,16 @@ uint32_t tuh_midi_stream_write (uint8_t dev_addr, uint8_t cable_num, uint8_t con return i; } -bool tuh_midi_packet_write (uint8_t dev_addr, uint8_t const packet[4]) -{ +bool tuh_midi_packet_write (uint8_t dev_addr, uint8_t const packet[4]) { midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); - - if (tu_fifo_remaining(&p_midi_host->tx_ff) < 4) - { - return false; - } - - tu_fifo_write_n(&p_midi_host->tx_ff, packet, 4); - - return true; + return 4 == tu_edpt_stream_write(dev_addr, &p_midi_host->ep_stream.tx, packet, 4); } -uint32_t tuh_midi_stream_flush( uint8_t dev_addr ) -{ - midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); - TU_VERIFY(p_midi_host != NULL); - - uint32_t bytes_flushed = 0; - if (!usbh_edpt_busy(p_midi_host->dev_addr, p_midi_host->ep_out)) - { - bytes_flushed = write_flush(dev_addr, p_midi_host); - } - return bytes_flushed; +uint32_t tuh_midi_stream_flush(uint8_t dev_addr) { + midih_interface_t *p_midi = find_midi_by_daddr(dev_addr); + TU_VERIFY(p_midi != NULL); + return tu_edpt_stream_write_xfer(p_midi->dev_addr, &p_midi->ep_stream.tx); } //--------------------------------------------------------------------+ // Helper @@ -692,12 +577,11 @@ bool tuh_midi_packet_read (uint8_t dev_addr, uint8_t packet[4]) { midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); - TU_VERIFY(tu_fifo_count(&p_midi_host->rx_ff) >= 4); - return tu_fifo_read_n(&p_midi_host->rx_ff, packet, 4) == 4; + TU_VERIFY(tu_edpt_stream_read_available(&p_midi_host->ep_stream.rx) >= 4); + return 4 == tu_edpt_stream_read(dev_addr, &p_midi_host->ep_stream.rx, packet, 4); } -uint32_t tuh_midi_stream_read (uint8_t dev_addr, uint8_t *p_cable_num, uint8_t *p_buffer, uint16_t bufsize) -{ +uint32_t tuh_midi_stream_read(uint8_t dev_addr, uint8_t *p_cable_num, uint8_t *p_buffer, uint16_t bufsize) { midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); uint32_t bytes_buffered = 0; @@ -705,54 +589,40 @@ uint32_t tuh_midi_stream_read (uint8_t dev_addr, uint8_t *p_cable_num, uint8_t * TU_ASSERT(p_buffer); TU_ASSERT(bufsize); uint8_t one_byte; - if (!tu_fifo_peek(&p_midi_host->rx_ff, &one_byte)) - { + if (!tu_edpt_stream_peek(&p_midi_host->ep_stream.rx, &one_byte)) { return 0; } *p_cable_num = (one_byte >> 4) & 0xf; - uint32_t nread = tu_fifo_read_n(&p_midi_host->rx_ff, p_midi_host->stream_read.buffer, 4); + uint32_t nread = tu_edpt_stream_read(dev_addr, &p_midi_host->ep_stream.rx, p_midi_host->stream_read.buffer, 4); static uint16_t cable_sysex_in_progress; // bit i is set if received MIDI_STATUS_SYSEX_START but not MIDI_STATUS_SYSEX_END - while (nread == 4 && bytes_buffered < bufsize) - { - *p_cable_num=(p_midi_host->stream_read.buffer[0] >> 4) & 0x0f; + while (nread == 4 && bytes_buffered < bufsize) { + *p_cable_num = (p_midi_host->stream_read.buffer[0] >> 4) & 0x0f; uint8_t bytes_to_add_to_stream = 0; - if (*p_cable_num < p_midi_host->num_cables_rx) - { + if (*p_cable_num < p_midi_host->num_cables_rx) { // ignore the CIN field; too many devices out there encode this wrong uint8_t status = p_midi_host->stream_read.buffer[1]; uint16_t cable_mask = (uint16_t) (1 << *p_cable_num); - if (status <= MIDI_MAX_DATA_VAL || status == MIDI_STATUS_SYSEX_START) - { - if (status == MIDI_STATUS_SYSEX_START) - { + if (status <= MIDI_MAX_DATA_VAL || status == MIDI_STATUS_SYSEX_START) { + if (status == MIDI_STATUS_SYSEX_START) { cable_sysex_in_progress |= cable_mask; } // only add the packet if a sysex message is in progress - if (cable_sysex_in_progress & cable_mask) - { + if (cable_sysex_in_progress & cable_mask) { ++bytes_to_add_to_stream; - uint8_t idx; - for (idx = 2; idx < 4; idx++) - { - if (p_midi_host->stream_read.buffer[idx] <= MIDI_MAX_DATA_VAL) - { + for (uint8_t idx = 2; idx < 4; idx++) { + if (p_midi_host->stream_read.buffer[idx] <= MIDI_MAX_DATA_VAL) { ++bytes_to_add_to_stream; - } - else if (p_midi_host->stream_read.buffer[idx] == MIDI_STATUS_SYSEX_END) - { + } else if (p_midi_host->stream_read.buffer[idx] == MIDI_STATUS_SYSEX_END) { ++bytes_to_add_to_stream; cable_sysex_in_progress &= (uint16_t) ~cable_mask; - idx = 4; // force the loop to exit; I hate break statements in loops + idx = 4;// force the loop to exit; I hate break statements in loops } } } - } - else if (status < MIDI_STATUS_SYSEX_START) - { + } else if (status < MIDI_STATUS_SYSEX_START) { // then it is a channel message either three bytes or two uint8_t fake_cin = (status & 0xf0) >> 4; - switch (fake_cin) - { + switch (fake_cin) { case MIDI_CIN_NOTE_OFF: case MIDI_CIN_NOTE_ON: case MIDI_CIN_POLY_KEYPRESS: @@ -765,14 +635,11 @@ uint32_t tuh_midi_stream_read (uint8_t dev_addr, uint8_t *p_cable_num, uint8_t * bytes_to_add_to_stream = 2; break; default: - break; // Should not get this + break;// Should not get this } - cable_sysex_in_progress &= (uint16_t)~cable_mask; - } - else if (status < MIDI_STATUS_SYSREAL_TIMING_CLOCK) - { - switch (status) - { + cable_sysex_in_progress &= (uint16_t) ~cable_mask; + } else if (status < MIDI_STATUS_SYSREAL_TIMING_CLOCK) { + switch (status) { case MIDI_STATUS_SYSCOM_TIME_CODE_QUARTER_FRAME: case MIDI_STATUS_SYSCOM_SONG_SELECT: bytes_to_add_to_stream = 2; @@ -786,30 +653,24 @@ uint32_t tuh_midi_stream_read (uint8_t dev_addr, uint8_t *p_cable_num, uint8_t * break; default: break; - cable_sysex_in_progress &= (uint16_t)~cable_mask; + cable_sysex_in_progress &= (uint16_t) ~cable_mask; } - } - else - { + } else { // Real-time message: can be inserted into a sysex message, // so do don't clear cable_sysex_in_progress bit bytes_to_add_to_stream = 1; } } - uint8_t idx; - for (idx = 1; idx <= bytes_to_add_to_stream; idx++) - { + for (uint8_t idx = 1; idx <= bytes_to_add_to_stream; idx++) { *p_buffer++ = p_midi_host->stream_read.buffer[idx]; } bytes_buffered += bytes_to_add_to_stream; nread = 0; - if (tu_fifo_peek(&p_midi_host->rx_ff, &one_byte)) - { + if (tu_edpt_stream_peek(&p_midi_host->ep_stream.rx, &one_byte)) { uint8_t new_cable = (one_byte >> 4) & 0xf; - if (new_cable == *p_cable_num) - { + if (new_cable == *p_cable_num) { // still on the same cable. Continue reading the stream - nread = tu_fifo_read_n(&p_midi_host->rx_ff, p_midi_host->stream_read.buffer, 4); + nread = tu_edpt_stream_read(dev_addr, &p_midi_host->ep_stream.rx, p_midi_host->stream_read.buffer, 4); } } } @@ -865,19 +726,14 @@ static uint8_t find_string_index(midih_interface_t *ptr, uint8_t jack_id) #endif #if CFG_MIDI_HOST_DEVSTRINGS -uint8_t tuh_midi_get_rx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint8_t max_istrings) -{ - uint8_t nstrings = 0; +uint8_t tuh_midi_get_rx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint8_t max_istrings) { midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); - TU_VERIFY(p_midi_host != NULL); - nstrings = p_midi_host->num_cables_rx; - if (nstrings > max_istrings) - { - nstrings = max_istrings; + TU_VERIFY(p_midi_host != NULL, 0); + uint8_t nstrings = p_midi_host->num_cables_rx; + if (nstrings > max_istrings) { + nstrings = max_istrings; } - uint8_t jack; - for (jack=0; jackep_in_associated_jacks[jack]; istrings[jack] = find_string_index(p_midi_host, jack_id); } @@ -886,17 +742,13 @@ uint8_t tuh_midi_get_rx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint uint8_t tuh_midi_get_tx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint8_t max_istrings) { - uint8_t nstrings = 0; midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); - TU_VERIFY(p_midi_host != NULL); - nstrings = p_midi_host->num_cables_tx; - if (nstrings > max_istrings) - { - nstrings = max_istrings; + TU_VERIFY(p_midi_host != NULL, 0); + uint8_t nstrings = p_midi_host->num_cables_tx; + if (nstrings > max_istrings) { + nstrings = max_istrings; } - uint8_t jack; - for (jack=0; jackep_out_associated_jacks[jack]; istrings[jack] = find_string_index(p_midi_host, jack_id); } @@ -909,8 +761,7 @@ uint8_t tuh_midi_get_all_istrings(uint8_t dev_addr, const uint8_t** istrings) midih_interface_t *p_midi_host = find_midi_by_daddr(dev_addr); TU_VERIFY(p_midi_host != NULL); uint8_t nstrings = p_midi_host->num_string_indices; - if (nstrings) - *istrings = p_midi_host->all_string_indices; + if (nstrings) { *istrings = p_midi_host->all_string_indices; } return nstrings; } #endif diff --git a/src/class/midi/midi_host.h b/src/class/midi/midi_host.h index bf2378168..6401eb0c3 100644 --- a/src/class/midi/midi_host.h +++ b/src/class/midi/midi_host.h @@ -42,15 +42,15 @@ #endif #ifndef CFG_TUH_MIDI_RX_BUFSIZE -#define CFG_TUH_MIDI_RX_BUFSIZE 64 +#define CFG_TUH_MIDI_RX_BUFSIZE TUH_EPSIZE_BULK_MPS #endif #ifndef CFG_TUH_MIDI_TX_BUFSIZE -#define CFG_TUH_MIDI_TX_BUFSIZE 64 +#define CFG_TUH_MIDI_TX_BUFSIZE TUH_EPSIZE_BULK_MPS #endif #ifndef CFG_TUH_MIDI_EP_BUFSIZE -#define CFG_TUH_MIDI_EP_BUFSIZE 64 +#define CFG_TUH_MIDI_EP_BUFSIZE TUH_EPSIZE_BULK_MPS #endif #ifndef CFG_MIDI_HOST_DEVSTRINGS @@ -113,14 +113,6 @@ uint8_t tuh_midi_get_rx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint uint8_t tuh_midi_get_tx_cable_istrings(uint8_t dev_addr, uint8_t* istrings, uint8_t max_istrings); uint8_t tuh_midi_get_all_istrings(uint8_t dev_addr, const uint8_t** istrings); #endif -//--------------------------------------------------------------------+ -// Internal Class Driver API -//--------------------------------------------------------------------+ -bool midih_init (void); -bool midih_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len); -bool midih_set_config (uint8_t dev_addr, uint8_t itf_num); -bool midih_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); -void midih_close (uint8_t dev_addr); //--------------------------------------------------------------------+ // Callbacks (Weak is optional) @@ -138,6 +130,17 @@ TU_ATTR_WEAK void tuh_midi_umount_cb(uint8_t dev_addr, uint8_t instance); TU_ATTR_WEAK void tuh_midi_rx_cb(uint8_t dev_addr, uint32_t num_packets); TU_ATTR_WEAK void tuh_midi_tx_cb(uint8_t dev_addr); + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +bool midih_init (void); +bool midih_deinit (void); +bool midih_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len); +bool midih_set_config (uint8_t dev_addr, uint8_t itf_num); +bool midih_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); +void midih_close (uint8_t dev_addr); + #ifdef __cplusplus } #endif diff --git a/src/common/tusb_private.h b/src/common/tusb_private.h index c71775abb..445882243 100644 --- a/src/common/tusb_private.h +++ b/src/common/tusb_private.h @@ -138,7 +138,7 @@ uint32_t tu_edpt_stream_read(uint8_t hwid, tu_edpt_stream_t* s, void* buffer, ui // Start an usb transfer if endpoint is not busy uint32_t tu_edpt_stream_read_xfer(uint8_t hwid, tu_edpt_stream_t* s); -// Must be called in the transfer complete callback +// Complete read transfer by writing EP -> FIFO. Must be called in the transfer complete callback TU_ATTR_ALWAYS_INLINE static inline void tu_edpt_stream_read_xfer_complete(tu_edpt_stream_t* s, uint32_t xferred_bytes) { if (tu_fifo_depth(&s->ff)) { @@ -146,11 +146,11 @@ void tu_edpt_stream_read_xfer_complete(tu_edpt_stream_t* s, uint32_t xferred_byt } } -// Same as tu_edpt_stream_read_xfer_complete but skip the first n bytes +// Complete read transfer with provided buffer TU_ATTR_ALWAYS_INLINE static inline -void tu_edpt_stream_read_xfer_complete_offset(tu_edpt_stream_t* s, uint32_t xferred_bytes, uint32_t skip_offset) { - if (tu_fifo_depth(&s->ff) && (skip_offset < xferred_bytes)) { - tu_fifo_write_n(&s->ff, s->ep_buf + skip_offset, (uint16_t) (xferred_bytes - skip_offset)); +void tu_edpt_stream_read_xfer_complete_with_buf(tu_edpt_stream_t* s, const void * buf, uint32_t xferred_bytes) { + if (tu_fifo_depth(&s->ff)) { + tu_fifo_write_n(&s->ff, buf, (uint16_t) xferred_bytes); } } diff --git a/src/host/usbh.c b/src/host/usbh.c index f874121a3..e6b6cd91c 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -192,6 +192,7 @@ static usbh_class_driver_t const usbh_class_drivers[] = { { .name = DRIVER_NAME("MIDI"), .init = midih_init, + .deinit = midih_deinit, .open = midih_open, .set_config = midih_set_config, .xfer_cb = midih_xfer_cb, @@ -1672,7 +1673,7 @@ static bool _parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configur if ( 0 == tu_desc_len(p_desc) ) { // A zero length descriptor indicates that the device is off spec (e.g. wrong wTotalLength). // Parsed interfaces should still be usable - TU_LOG_USBH("Encountered a zero-length descriptor after %u bytes\r\n", (uint32_t)p_desc - (uint32_t)desc_cfg); + TU_LOG_USBH("Encountered a zero-length descriptor after %" PRIu32 " bytes\r\n", (uint32_t)p_desc - (uint32_t)desc_cfg); break; } diff --git a/src/host/usbh.h b/src/host/usbh.h index 3bcdd3657..7fc8ea826 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -37,6 +37,9 @@ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ +// Endpoint Bulk size depending on host mx speed +#define TUH_EPSIZE_BULK_MPS (TUD_OPT_HIGH_SPEED ? TUSB_EPSIZE_BULK_HS : TUSB_EPSIZE_BULK_FS) + // forward declaration struct tuh_xfer_s; typedef struct tuh_xfer_s tuh_xfer_t; -- cgit v1.3.1 From 18d566b94c8f17d9df04914979997d589b905290 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 17 Feb 2025 17:06:51 +0700 Subject: improve hub: retry if hub interrupt endpoint failed bump up pio-usb to latest --- src/host/hub.c | 180 +++++++++++++++++++++++++----------------------------- src/host/hub.h | 51 ++++++++-------- src/host/usbh.c | 8 +-- tools/get_deps.py | 9 ++- 4 files changed, 118 insertions(+), 130 deletions(-) (limited to 'src/host') diff --git a/src/host/hub.c b/src/host/hub.c index e97014443..611bf71be 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -40,29 +40,37 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -typedef struct -{ +typedef struct { uint8_t itf_num; uint8_t ep_in; - uint8_t port_count; + + // from hub descriptor + uint8_t bNbrPorts; + // uint8_t bPwrOn2PwrGood; + // uint16_t wHubCharacteristics; CFG_TUH_MEM_ALIGN uint8_t status_change; CFG_TUH_MEM_ALIGN hub_port_status_response_t port_status; CFG_TUH_MEM_ALIGN hub_status_response_t hub_status; } hub_interface_t; -CFG_TUH_MEM_SECTION static hub_interface_t hub_data[CFG_TUH_HUB]; -CFG_TUH_MEM_SECTION CFG_TUH_MEM_ALIGN static uint8_t _hub_buffer[sizeof(descriptor_hub_desc_t)]; +typedef struct { + TUH_EPBUF_DEF(buf, CFG_TUH_HUB_BUFSIZE); +} hub_epbuf_t; -TU_ATTR_ALWAYS_INLINE -static inline hub_interface_t* get_itf(uint8_t dev_addr) -{ - return &hub_data[dev_addr-1-CFG_TUH_DEVICE_MAX]; +CFG_TUH_MEM_SECTION static hub_interface_t hub_itfs[CFG_TUH_HUB]; +CFG_TUH_MEM_SECTION static hub_epbuf_t hub_epbufs[CFG_TUH_HUB]; + +TU_ATTR_ALWAYS_INLINE static inline hub_interface_t* get_hub_itf(uint8_t daddr) { + return &hub_itfs[daddr-1-CFG_TUH_DEVICE_MAX]; } -#if CFG_TUSB_DEBUG >= 2 -static char const* const _hub_feature_str[] = -{ +TU_ATTR_ALWAYS_INLINE static inline uint8_t* get_hub_epbuf(uint8_t daddr) { + return hub_epbufs[daddr-1-CFG_TUH_DEVICE_MAX].buf; +} + +#if CFG_TUSB_DEBUG >= HUB_DEBUG +static char const* const _hub_feature_str[] = { [HUB_FEATURE_PORT_CONNECTION ] = "PORT_CONNECTION", [HUB_FEATURE_PORT_ENABLE ] = "PORT_ENABLE", [HUB_FEATURE_PORT_SUSPEND ] = "PORT_SUSPEND", @@ -84,12 +92,9 @@ static char const* const _hub_feature_str[] = // HUB //--------------------------------------------------------------------+ bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) -{ - tusb_control_request_t const request = - { - .bmRequestType_bit = - { + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + tusb_control_request_t const request = { + .bmRequestType_bit = { .recipient = (hub_port == 0) ? TUSB_REQ_RCPT_DEVICE : TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT @@ -100,8 +105,7 @@ bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, .wLength = 0 }; - tuh_xfer_t xfer = - { + tuh_xfer_t xfer = { .daddr = hub_addr, .ep_addr = 0, .setup = &request, @@ -110,7 +114,7 @@ bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, .user_data = user_data }; - TU_LOG2("HUB Clear Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); + TU_LOG_DRV("HUB Clear Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); TU_ASSERT( tuh_control_xfer(&xfer) ); return true; } @@ -142,7 +146,7 @@ bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, .user_data = user_data }; - TU_LOG2("HUB Set Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); + TU_LOG_DRV("HUB Set Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); TU_ASSERT( tuh_control_xfer(&xfer) ); return true; } @@ -174,7 +178,7 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, .user_data = user_data }; - TU_LOG2("HUB Get Port Status: addr = %u port = %u\r\n", hub_addr, hub_port); + TU_LOG_DRV("HUB Get Port Status: addr = %u port = %u\r\n", hub_addr, hub_port); TU_VERIFY( tuh_control_xfer(&xfer) ); return true; } @@ -183,7 +187,7 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, // CLASS-USBH API (don't require to verify parameters) //--------------------------------------------------------------------+ bool hub_init(void) { - tu_memclr(hub_data, sizeof(hub_data)); + tu_memclr(hub_itfs, sizeof(hub_itfs)); return true; } @@ -191,40 +195,32 @@ bool hub_deinit(void) { return true; } -bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) -{ +bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) { (void) rhport; TU_VERIFY(TUSB_CLASS_HUB == itf_desc->bInterfaceClass && 0 == itf_desc->bInterfaceSubClass); + TU_VERIFY(itf_desc->bInterfaceProtocol <= 1); // not support multiple TT yet - // hub driver does not support multiple TT yet - TU_VERIFY(itf_desc->bInterfaceProtocol <= 1); - - // msc driver length is fixed uint16_t const drv_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_desc_endpoint_t); TU_ASSERT(drv_len <= max_len); - //------------- Interrupt Status endpoint -------------// + // Interrupt Status endpoint tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); - TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType && TUSB_XFER_INTERRUPT == desc_ep->bmAttributes.xfer, 0); - TU_ASSERT(tuh_edpt_open(dev_addr, desc_ep)); - hub_interface_t* p_hub = get_itf(dev_addr); - + hub_interface_t* p_hub = get_hub_itf(dev_addr); p_hub->itf_num = itf_desc->bInterfaceNumber; p_hub->ep_in = desc_ep->bEndpointAddress; return true; } -void hub_close(uint8_t dev_addr) -{ +void hub_close(uint8_t dev_addr) { TU_VERIFY(dev_addr > CFG_TUH_DEVICE_MAX, ); - hub_interface_t* p_hub = get_itf(dev_addr); + hub_interface_t* p_hub = get_hub_itf(dev_addr); if (p_hub->ep_in) { TU_LOG_DRV(" HUB close addr = %d\r\n", dev_addr); @@ -232,30 +228,24 @@ void hub_close(uint8_t dev_addr) } } -bool hub_edpt_status_xfer(uint8_t dev_addr) -{ - hub_interface_t* hub_itf = get_itf(dev_addr); +bool hub_edpt_status_xfer(uint8_t dev_addr) { + hub_interface_t* hub_itf = get_hub_itf(dev_addr); return usbh_edpt_xfer(dev_addr, hub_itf->ep_in, &hub_itf->status_change, 1); } - //--------------------------------------------------------------------+ // Set Configure //--------------------------------------------------------------------+ - static void config_set_port_power (tuh_xfer_t* xfer); static void config_port_power_complete (tuh_xfer_t* xfer); -bool hub_set_config(uint8_t dev_addr, uint8_t itf_num) -{ - hub_interface_t* p_hub = get_itf(dev_addr); +bool hub_set_config(uint8_t dev_addr, uint8_t itf_num) { + hub_interface_t* p_hub = get_hub_itf(dev_addr); TU_ASSERT(itf_num == p_hub->itf_num); // Get Hub Descriptor - tusb_control_request_t const request = - { - .bmRequestType_bit = - { + tusb_control_request_t const request = { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN @@ -263,34 +253,31 @@ bool hub_set_config(uint8_t dev_addr, uint8_t itf_num) .bRequest = HUB_REQUEST_GET_DESCRIPTOR, .wValue = 0, .wIndex = 0, - .wLength = sizeof(descriptor_hub_desc_t) + .wLength = sizeof(hub_desc_cs_t) }; - tuh_xfer_t xfer = - { + tuh_xfer_t xfer = { .daddr = dev_addr, .ep_addr = 0, .setup = &request, - .buffer = _hub_buffer, + .buffer = get_hub_epbuf(dev_addr), .complete_cb = config_set_port_power, .user_data = 0 }; - TU_ASSERT( tuh_control_xfer(&xfer) ); - + TU_ASSERT(tuh_control_xfer(&xfer)); return true; } -static void config_set_port_power (tuh_xfer_t* xfer) -{ +static void config_set_port_power (tuh_xfer_t* xfer) { TU_ASSERT(XFER_RESULT_SUCCESS == xfer->result, ); uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); + hub_interface_t* p_hub = get_hub_itf(daddr); // only use number of ports in hub descriptor - descriptor_hub_desc_t const* desc_hub = (descriptor_hub_desc_t const*) _hub_buffer; - p_hub->port_count = desc_hub->bNbrPorts; + hub_desc_cs_t const* desc_hub = (hub_desc_cs_t const*) get_hub_epbuf(daddr); + p_hub->bNbrPorts = desc_hub->bNbrPorts; // May need to GET_STATUS @@ -299,14 +286,13 @@ static void config_set_port_power (tuh_xfer_t* xfer) hub_port_set_feature(daddr, hub_port, HUB_FEATURE_PORT_POWER, config_port_power_complete, 0); } -static void config_port_power_complete (tuh_xfer_t* xfer) -{ +static void config_port_power_complete (tuh_xfer_t* xfer) { TU_ASSERT(XFER_RESULT_SUCCESS == xfer->result, ); uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); + hub_interface_t* p_hub = get_hub_itf(daddr); - if (xfer->setup->wIndex == p_hub->port_count) + if (xfer->setup->wIndex == p_hub->bNbrPorts) { // All ports are power -> queue notification status endpoint and // complete the SET CONFIGURATION @@ -334,46 +320,48 @@ static void connection_port_reset_complete (tuh_xfer_t* xfer); bool hub_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { (void) xferred_bytes; // TODO can be more than 1 for hub with lots of ports (void) ep_addr; - TU_VERIFY(result == XFER_RESULT_SUCCESS); - hub_interface_t* p_hub = get_itf(dev_addr); + if (result == XFER_RESULT_SUCCESS) { + hub_interface_t* p_hub = get_hub_itf(dev_addr); - uint8_t const status_change = p_hub->status_change; - TU_LOG2(" Hub Status Change = 0x%02X\r\n", status_change); + uint8_t const status_change = p_hub->status_change; + TU_LOG_DRV(" Hub Status Change = 0x%02X\r\n", status_change); - if ( status_change == 0 ) { - // The status change event was neither for the hub, nor for any of its ports. - // This shouldn't happen, but it does with some devices. - // Initiate the next interrupt poll here. - return hub_edpt_status_xfer(dev_addr); - } + if ( status_change == 0 ) { + // The status change event was neither for the hub, nor for any of its ports. + // This shouldn't happen, but it does with some devices. Initiate the next interrupt poll here. + return hub_edpt_status_xfer(dev_addr); + } - if (tu_bit_test(status_change, 0)) { - // Hub bit 0 is for the hub device events - if (hub_port_get_status(dev_addr, 0, &p_hub->hub_status, hub_get_status_complete, 0) == false) { - //Hub status control transfer failed, retry - hub_edpt_status_xfer(dev_addr); + if (tu_bit_test(status_change, 0)) { + // Hub bit 0 is for the hub device events + if (hub_port_get_status(dev_addr, 0, &p_hub->hub_status, hub_get_status_complete, 0) == false) { + //Hub status control transfer failed, retry + hub_edpt_status_xfer(dev_addr); + } } - } - else { - // Hub bits 1 to n are hub port events - for (uint8_t port=1; port <= p_hub->port_count; port++) { - if ( tu_bit_test(status_change, port) ) { - if (hub_port_get_status(dev_addr, port, &p_hub->port_status, hub_port_get_status_complete, 0) == false) { - //Hub status control transfer failed, retry - hub_edpt_status_xfer(dev_addr); + else { + // Hub bits 1 to n are hub port events + for (uint8_t port=1; port <= p_hub->bNbrPorts; port++) { + if ( tu_bit_test(status_change, port) ) { + if (hub_port_get_status(dev_addr, port, &p_hub->port_status, hub_port_get_status_complete, 0) == false) { + //Hub status control transfer failed, retry + hub_edpt_status_xfer(dev_addr); + } + break; } - break; } } + } else { + TU_LOG_DRV(" Hub Status Change: failed, retry\r\n"); + hub_edpt_status_xfer(dev_addr); // retry } // NOTE: next status transfer is queued by usbh.c after handling this request return true; } -static void hub_clear_feature_complete_stub(tuh_xfer_t* xfer) -{ +static void hub_clear_feature_complete_stub(tuh_xfer_t* xfer) { TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); hub_edpt_status_xfer(xfer->daddr); } @@ -383,15 +371,15 @@ static void hub_get_status_complete (tuh_xfer_t* xfer) TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); + hub_interface_t* p_hub = get_hub_itf(daddr); uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); TU_ASSERT(port_num == 0 , ); - TU_LOG2("HUB Got hub status, addr = %u, status = %04x\r\n", daddr, p_hub->hub_status.change.value); + TU_LOG_DRV("HUB Got hub status, addr = %u, status = %04x\r\n", daddr, p_hub->hub_status.change.value); if (p_hub->hub_status.change.local_power_source) { - TU_LOG2("HUB Local Power Change, addr = %u\r\n", daddr); + TU_LOG_DRV("HUB Local Power Change, addr = %u\r\n", daddr); hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, hub_clear_feature_complete_stub, 0); } else if (p_hub->hub_status.change.over_current) @@ -406,7 +394,7 @@ static void hub_port_get_status_complete (tuh_xfer_t* xfer) TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); + hub_interface_t* p_hub = get_hub_itf(daddr); uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); // Connection change @@ -453,7 +441,7 @@ static void connection_clear_conn_change_complete (tuh_xfer_t* xfer) TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); + hub_interface_t* p_hub = get_hub_itf(daddr); uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); if ( p_hub->port_status.status.connection ) diff --git a/src/host/hub.h b/src/host/hub.h index 385efe6b2..59097fb0a 100644 --- a/src/host/hub.h +++ b/src/host/hub.h @@ -24,17 +24,8 @@ * This file is part of the TinyUSB stack. */ -/** \ingroup group_class - * \defgroup ClassDriver_Hub Hub (Host only) - * \details Like most PC's OS, Hub support is completely hidden from Application. In fact, application cannot determine whether - * a device is mounted directly via roothub or via a hub's port. All Hub-related procedures are performed and managed - * by tinyusb stack. Unless you are trying to develop the stack itself, there are nothing else can be used by Application. - * \note Due to my laziness, only 1-level of Hub is supported. In other way, the stack cannot mount a hub via another hub. - * @{ - */ - -#ifndef _TUSB_HUB_H_ -#define _TUSB_HUB_H_ +#ifndef TUSB_HUB_H_ +#define TUSB_HUB_H_ #include "common/tusb_common.h" @@ -42,6 +33,14 @@ extern "C" { #endif +//--------------------------------------------------------------------+ +// Configuration +//--------------------------------------------------------------------+ + +#ifndef CFG_TUH_HUB_BUFSIZE + #define CFG_TUH_HUB_BUFSIZE 12 +#endif + //D1...D0: Logical Power Switching Mode //00: Ganged power switching (all ports’power at //once) @@ -89,16 +88,17 @@ typedef struct TU_ATTR_PACKED{ uint8_t bHubContrCurrent; uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1) uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff -} descriptor_hub_desc_t; +} hub_desc_cs_t; -TU_VERIFY_STATIC( sizeof(descriptor_hub_desc_t) == 9, "size is not correct"); +TU_VERIFY_STATIC(sizeof(hub_desc_cs_t) == 9, "size is not correct"); +TU_VERIFY_STATIC(CFG_TUH_HUB_BUFSIZE >= sizeof(hub_desc_cs_t), "buffer is not big enough"); enum { HUB_REQUEST_GET_STATUS = 0 , HUB_REQUEST_CLEAR_FEATURE = 1 , - + // 2 is reserved HUB_REQUEST_SET_FEATURE = 3 , - + // 4-5 are reserved HUB_REQUEST_GET_DESCRIPTOR = 6 , HUB_REQUEST_SET_DESCRIPTOR = 7 , HUB_REQUEST_CLEAR_TT_BUFFER = 8 , @@ -118,10 +118,10 @@ enum{ HUB_FEATURE_PORT_SUSPEND = 2, HUB_FEATURE_PORT_OVER_CURRENT = 3, HUB_FEATURE_PORT_RESET = 4, - + // 5-7 are reserved HUB_FEATURE_PORT_POWER = 8, HUB_FEATURE_PORT_LOW_SPEED = 9, - + // 10-15 are reserved HUB_FEATURE_PORT_CONNECTION_CHANGE = 16, HUB_FEATURE_PORT_ENABLE_CHANGE = 17, HUB_FEATURE_PORT_SUSPEND_CHANGE = 18, @@ -172,16 +172,16 @@ typedef struct { TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct"); // Clear feature -bool hub_port_clear_feature (uint8_t hub_addr, uint8_t hub_port, uint8_t feature, - tuh_xfer_cb_t complete_cb, uintptr_t user_data); +bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, + tuh_xfer_cb_t complete_cb, uintptr_t user_data); // Set feature -bool hub_port_set_feature (uint8_t hub_addr, uint8_t hub_port, uint8_t feature, - tuh_xfer_cb_t complete_cb, uintptr_t user_data); +bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, + tuh_xfer_cb_t complete_cb, uintptr_t user_data); // Get port status -bool hub_port_get_status (uint8_t hub_addr, uint8_t hub_port, void* resp, - tuh_xfer_cb_t complete_cb, uintptr_t user_data); +bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void *resp, + tuh_xfer_cb_t complete_cb, uintptr_t user_data); // Get status from Interrupt endpoint bool hub_edpt_status_xfer(uint8_t dev_addr); @@ -198,7 +198,6 @@ bool hub_port_clear_reset_change(uint8_t hub_addr, uint8_t hub_port, tuh_xfer_cb return hub_port_clear_feature(hub_addr, hub_port, HUB_FEATURE_PORT_RESET_CHANGE, complete_cb, user_data); } - //--------------------------------------------------------------------+ // Internal Class Driver API //--------------------------------------------------------------------+ @@ -213,6 +212,4 @@ void hub_close (uint8_t dev_addr); } #endif -#endif /* _TUSB_HUB_H_ */ - -/** @} */ +#endif diff --git a/src/host/usbh.c b/src/host/usbh.c index a2994cde7..5f4f17167 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -467,13 +467,11 @@ bool tuh_task_event_ready(void) { * This should be called periodically within the mainloop or rtos thread. * @code - int main(void) - { + int main(void) { application_init(); tusb_init(0, TUSB_ROLE_HOST); - while(1) // the mainloop - { + while(1) { // the mainloop application_code(); tuh_task(); // tinyusb host task } @@ -1657,7 +1655,7 @@ static bool _parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configur if ( 0 == tu_desc_len(p_desc) ) { // A zero length descriptor indicates that the device is off spec (e.g. wrong wTotalLength). // Parsed interfaces should still be usable - TU_LOG_USBH("Encountered a zero-length descriptor after %u bytes\r\n", (uint32_t)p_desc - (uint32_t)desc_cfg); + TU_LOG_USBH("Encountered a zero-length descriptor after %" PRIu32 "bytes\r\n", (uint32_t)p_desc - (uint32_t)desc_cfg); break; } diff --git a/tools/get_deps.py b/tools/get_deps.py index c8459c1f1..3665904b3 100755 --- a/tools/get_deps.py +++ b/tools/get_deps.py @@ -59,7 +59,7 @@ deps_optional = { '144f1eb7ea8c06512e12f12b27383601c0272410', 'kinetis_k kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx imxrt'], 'hw/mcu/raspberry_pi/Pico-PIO-USB': ['https://github.com/sekigon-gonnoc/Pico-PIO-USB.git', - 'fe9133fc513b82cc3dc62c67cb51f2339cf29ef7', + '442af432568f25fb72c5784d9d67b8e85465cb28', 'rp2040'], 'hw/mcu/renesas/fsp': ['https://github.com/renesas/fsp.git', 'edcc97d684b6f716728a60d7a6fea049d9870bd6', @@ -217,7 +217,12 @@ TOP = Path(__file__).parent.parent.resolve() def run_cmd(cmd): - return subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + r = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + title = f'Command Error: {cmd}' + if r.returncode != 0: + print(title) + print(r.stdout.decode("utf-8")) + return r def get_a_dep(d): -- cgit v1.3.1 From 792a44640509661b11065a8d6ee038d9362a2b9f Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 17 Feb 2025 22:40:19 +0700 Subject: usbh always retry control transfer (max 3) in case of XFER_RESULT_FAILED. added tuh_connected() --- src/common/tusb_types.h | 6 +- src/host/hub.c | 76 ++++++++++--------------- src/host/hub.h | 2 +- src/host/usbh.c | 144 +++++++++++++++++++++++++++++------------------- src/host/usbh.h | 4 ++ src/host/usbh_pvt.h | 4 +- 6 files changed, 126 insertions(+), 110 deletions(-) (limited to 'src/host') diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 9e4d9380c..42ce5fc12 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -302,9 +302,9 @@ typedef enum { enum { CONTROL_STAGE_IDLE = 0, - CONTROL_STAGE_SETUP, - CONTROL_STAGE_DATA, - CONTROL_STAGE_ACK + CONTROL_STAGE_SETUP, // 1 + CONTROL_STAGE_DATA, // 2 + CONTROL_STAGE_ACK // 3 }; enum { diff --git a/src/host/hub.c b/src/host/hub.c index 611bf71be..1d3e9ae1d 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -120,12 +120,9 @@ bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, } bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) -{ - tusb_control_request_t const request = - { - .bmRequestType_bit = - { + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + tusb_control_request_t const request = { + .bmRequestType_bit = { .recipient = (hub_port == 0) ? TUSB_REQ_RCPT_DEVICE : TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT @@ -136,8 +133,7 @@ bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, .wLength = 0 }; - tuh_xfer_t xfer = - { + tuh_xfer_t xfer = { .daddr = hub_addr, .ep_addr = 0, .setup = &request, @@ -152,12 +148,9 @@ bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, } bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) -{ - tusb_control_request_t const request = - { - .bmRequestType_bit = - { + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + tusb_control_request_t const request = { + .bmRequestType_bit = { .recipient = (hub_port == 0) ? TUSB_REQ_RCPT_DEVICE : TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN @@ -168,8 +161,7 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, .wLength = 4 }; - tuh_xfer_t xfer = - { + tuh_xfer_t xfer = { .daddr = hub_addr, .ep_addr = 0, .setup = &request, @@ -228,9 +220,9 @@ void hub_close(uint8_t dev_addr) { } } -bool hub_edpt_status_xfer(uint8_t dev_addr) { - hub_interface_t* hub_itf = get_hub_itf(dev_addr); - return usbh_edpt_xfer(dev_addr, hub_itf->ep_in, &hub_itf->status_change, 1); +bool hub_edpt_status_xfer(uint8_t daddr) { + hub_interface_t* hub_itf = get_hub_itf(daddr); + return usbh_edpt_xfer(daddr, hub_itf->ep_in, &hub_itf->status_change, 1); } //--------------------------------------------------------------------+ @@ -292,15 +284,15 @@ static void config_port_power_complete (tuh_xfer_t* xfer) { uint8_t const daddr = xfer->daddr; hub_interface_t* p_hub = get_hub_itf(daddr); - if (xfer->setup->wIndex == p_hub->bNbrPorts) - { + if (xfer->setup->wIndex == p_hub->bNbrPorts) { // All ports are power -> queue notification status endpoint and // complete the SET CONFIGURATION - TU_ASSERT( usbh_edpt_xfer(daddr, p_hub->ep_in, &p_hub->status_change, 1), ); - + if (!hub_edpt_status_xfer(daddr)) { + TU_MESS_FAILED(); + TU_BREAKPOINT(); + } usbh_driver_set_config_complete(daddr, p_hub->itf_num); - }else - { + } else { // power next port uint8_t const hub_port = (uint8_t) (xfer->setup->wIndex + 1); hub_port_set_feature(daddr, hub_port, HUB_FEATURE_PORT_POWER, config_port_power_complete, 0); @@ -310,7 +302,6 @@ static void config_port_power_complete (tuh_xfer_t* xfer) { //--------------------------------------------------------------------+ // Connection Changes //--------------------------------------------------------------------+ - static void hub_port_get_status_complete (tuh_xfer_t* xfer); static void hub_get_status_complete (tuh_xfer_t* xfer); static void connection_clear_conn_change_complete (tuh_xfer_t* xfer); @@ -389,46 +380,35 @@ static void hub_get_status_complete (tuh_xfer_t* xfer) } } -static void hub_port_get_status_complete (tuh_xfer_t* xfer) -{ +static void hub_port_get_status_complete(tuh_xfer_t *xfer) { TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_hub_itf(daddr); + hub_interface_t *p_hub = get_hub_itf(daddr); uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); // Connection change - if (p_hub->port_status.change.connection) - { + if (p_hub->port_status.change.connection) { // Port is powered and enabled //TU_VERIFY(port_status.status_current.port_power && port_status.status_current.port_enable, ); // Acknowledge Port Connection Change hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_CONNECTION_CHANGE, connection_clear_conn_change_complete, 0); - }else - { + } else { // Clear other port status change interrupts. TODO Not currently handled - just cleared. - if (p_hub->port_status.change.port_enable) - { + if (p_hub->port_status.change.port_enable) { hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_ENABLE_CHANGE, hub_clear_feature_complete_stub, 0); - } - else if (p_hub->port_status.change.suspend) - { + } else if (p_hub->port_status.change.suspend) { hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_SUSPEND_CHANGE, hub_clear_feature_complete_stub, 0); - } - else if (p_hub->port_status.change.over_current) - { + } else if (p_hub->port_status.change.over_current) { hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_OVER_CURRENT_CHANGE, hub_clear_feature_complete_stub, 0); - } - else if (p_hub->port_status.change.reset) - { + } else if (p_hub->port_status.change.reset) { hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_RESET_CHANGE, hub_clear_feature_complete_stub, 0); } - // Other changes are: L1 state - // TODO clear change + else { + // Other changes are: L1 state + // TODO clear change - else - { // prepare for next hub status // TODO continue with status_change, or maybe we can do it again with status hub_edpt_status_xfer(daddr); diff --git a/src/host/hub.h b/src/host/hub.h index 59097fb0a..3b19e9838 100644 --- a/src/host/hub.h +++ b/src/host/hub.h @@ -184,7 +184,7 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void *resp, tuh_xfer_cb_t complete_cb, uintptr_t user_data); // Get status from Interrupt endpoint -bool hub_edpt_status_xfer(uint8_t dev_addr); +bool hub_edpt_status_xfer(uint8_t daddr); // Reset a port TU_ATTR_ALWAYS_INLINE static inline diff --git a/src/host/usbh.c b/src/host/usbh.c index 5f4f17167..ac920f533 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -44,6 +44,10 @@ #define CFG_TUH_INTERFACE_MAX 8 #endif +enum { + USBH_CONTROL_RETRY_MAX = 3, +}; + //--------------------------------------------------------------------+ // Weak stubs: invoked if no strong implementation is available //--------------------------------------------------------------------+ @@ -272,9 +276,10 @@ static struct { tuh_xfer_cb_t complete_cb; uintptr_t user_data; - uint8_t daddr; volatile uint8_t stage; + uint8_t daddr; volatile uint16_t actual_len; + uint8_t failed_count; } _ctrl_xfer; typedef struct { @@ -285,7 +290,6 @@ typedef struct { CFG_TUH_MEM_SECTION static usbh_epbuf_t _usbh_epbuf; //------------- Helper Function -------------// - 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); return &_usbh_devices[dev_addr-1]; @@ -312,6 +316,15 @@ bool tuh_mounted(uint8_t dev_addr) { return dev->configured; } +bool tuh_connected(uint8_t daddr) { + if (daddr == 0) { + return _dev0.enumerating; // dev0 is connected if still enumerating + } else { + const usbh_device_t* dev = get_device(daddr); + return dev && dev->connected; + } +} + bool tuh_vid_pid_get(uint8_t dev_addr, uint16_t *vid, uint16_t *pid) { *vid = *pid = 0; @@ -421,7 +434,9 @@ bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { } bool tuh_deinit(uint8_t rhport) { - if (!tuh_rhport_is_active(rhport)) return true; + if (!tuh_rhport_is_active(rhport)) { + return true; + } // deinit host controller hcd_int_disable(rhport); @@ -482,7 +497,9 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { (void) in_isr; // not implemented yet // Skip if stack is not initialized - if (!tuh_inited()) return; + if (!tuh_inited()) { + return; + } // Loop until there is no more events in the queue while (1) { @@ -616,17 +633,9 @@ static void _control_blocking_complete_cb(tuh_xfer_t* xfer) { // TODO timeout_ms is not supported yet bool tuh_control_xfer (tuh_xfer_t* xfer) { - // EP0 with setup packet - TU_VERIFY(xfer->ep_addr == 0 && xfer->setup); - - // Check if device is still connected (enumerating for dev0) + TU_VERIFY(xfer->ep_addr == 0 && xfer->setup); // EP0 with setup packet const uint8_t daddr = xfer->daddr; - if (daddr == 0) { - TU_VERIFY(_dev0.enumerating); - } else { - const usbh_device_t* dev = get_device(daddr); - TU_VERIFY(dev && dev->connected); - } + TU_VERIFY(tuh_connected(daddr)); // Check if device is still connected (enumerating for dev0) // pre-check to help reducing mutex lock TU_VERIFY(_ctrl_xfer.stage == CONTROL_STAGE_IDLE); @@ -634,14 +643,15 @@ bool tuh_control_xfer (tuh_xfer_t* xfer) { bool const is_idle = (_ctrl_xfer.stage == CONTROL_STAGE_IDLE); if (is_idle) { - _ctrl_xfer.stage = CONTROL_STAGE_SETUP; - _ctrl_xfer.daddr = daddr; - _ctrl_xfer.actual_len = 0; - - _ctrl_xfer.buffer = xfer->buffer; - _ctrl_xfer.complete_cb = xfer->complete_cb; - _ctrl_xfer.user_data = xfer->user_data; - _usbh_epbuf.request = (*xfer->setup); + _ctrl_xfer.stage = CONTROL_STAGE_SETUP; + _ctrl_xfer.daddr = daddr; + _ctrl_xfer.actual_len = 0; + _ctrl_xfer.failed_count = 0; + + _ctrl_xfer.buffer = xfer->buffer; + _ctrl_xfer.complete_cb = xfer->complete_cb; + _ctrl_xfer.user_data = xfer->user_data; + _usbh_epbuf.request = (*xfer->setup); } (void) osal_mutex_unlock(_usbh_mutex); @@ -655,7 +665,7 @@ bool tuh_control_xfer (tuh_xfer_t* xfer) { TU_LOG_BUF_USBH(xfer->setup, 8); if (xfer->complete_cb) { - TU_ASSERT( hcd_setup_send(rhport, daddr, (uint8_t const*) &_usbh_epbuf.request) ); + TU_ASSERT(hcd_setup_send(rhport, 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 @@ -665,7 +675,7 @@ bool tuh_control_xfer (tuh_xfer_t* xfer) { _ctrl_xfer.user_data = (uintptr_t) &result; _ctrl_xfer.complete_cb = _control_blocking_complete_cb; - TU_ASSERT( hcd_setup_send(rhport, daddr, (uint8_t*) &_usbh_epbuf.request) ); + TU_ASSERT(hcd_setup_send(rhport, daddr, (uint8_t *) &_usbh_epbuf.request)); while (result == XFER_RESULT_INVALID) { // Note: this can be called within an callback ie. part of tuh_task() @@ -722,28 +732,46 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t const uint8_t rhport = usbh_get_rhport(daddr); tusb_control_request_t const * request = &_usbh_epbuf.request; - if (XFER_RESULT_SUCCESS != result) { - TU_LOG_USBH("[%u:%u] Control %s, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, result == XFER_RESULT_STALLED ? "STALLED" : "FAILED", xferred_bytes); - TU_LOG_BUF_USBH(request, 8); + 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); + break; - // terminate transfer if any stage failed - _control_xfer_complete(daddr, result); - }else { - switch(_ctrl_xfer.stage) { - case CONTROL_STAGE_SETUP: - if (request->wLength) { - // DATA stage: initial data toggle is always 1 - _set_control_xfer_stage(CONTROL_STAGE_DATA); - TU_ASSERT( hcd_edpt_xfer(rhport, daddr, tu_edpt_addr(0, request->bmRequestType_bit.direction), _ctrl_xfer.buffer, request->wLength) ); - return true; - } + case XFER_RESULT_FAILED: + if (tuh_connected(daddr) && _ctrl_xfer.failed_count < USBH_CONTROL_RETRY_MAX) { + TU_LOG_USBH("[%u:%u] Control FAILED %u/%u, retrying\r\n", rhport, daddr, _ctrl_xfer.failed_count+1, USBH_CONTROL_RETRY_MAX); + (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); + _ctrl_xfer.stage = CONTROL_STAGE_SETUP; + _ctrl_xfer.failed_count++; + _ctrl_xfer.actual_len = 0; // reset actual_len + (void) osal_mutex_unlock(_usbh_mutex); + + TU_ASSERT(hcd_setup_send(rhport, daddr, (uint8_t const *) request)); + } 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); + } + break; + + case XFER_RESULT_SUCCESS: + switch(_ctrl_xfer.stage) { + case CONTROL_STAGE_SETUP: + if (request->wLength) { + // DATA stage: initial data toggle is always 1 + _set_control_xfer_stage(CONTROL_STAGE_DATA); + TU_ASSERT( hcd_edpt_xfer(rhport, daddr, tu_edpt_addr(0, request->bmRequestType_bit.direction), _ctrl_xfer.buffer, request->wLength) ); + return true; + } TU_ATTR_FALLTHROUGH; - case CONTROL_STAGE_DATA: - if (request->wLength) { - TU_LOG_USBH("[%u:%u] Control data:\r\n", rhport, daddr); - TU_LOG_MEM_USBH(_ctrl_xfer.buffer, xferred_bytes, 2); - } + case CONTROL_STAGE_DATA: + if (request->wLength) { + TU_LOG_USBH("[%u:%u] Control data:\r\n", rhport, daddr); + TU_LOG_MEM_USBH(_ctrl_xfer.buffer, xferred_bytes, 2); + } _ctrl_xfer.actual_len = (uint16_t) xferred_bytes; @@ -752,23 +780,26 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t TU_ASSERT( hcd_edpt_xfer(rhport, daddr, tu_edpt_addr(0, 1 - request->bmRequestType_bit.direction), NULL, 0) ); break; - case CONTROL_STAGE_ACK: { - // Abort all pending transfers if SET_CONFIGURATION request - // NOTE: should we force closing all non-control endpoints in the future? - if (request->bRequest == TUSB_REQ_SET_CONFIGURATION && request->bmRequestType == 0x00) { - for(uint8_t epnum=1; epnumbRequest == TUSB_REQ_SET_CONFIGURATION && request->bmRequestType == 0x00) { + for(uint8_t epnum=1; epnum Date: Wed, 19 Feb 2025 11:27:33 +0700 Subject: move status_change to epbuf improve hub_xfer_cb() rename internal complete function --- src/host/hub.c | 88 ++++++++++++++++++++++++++++++---------------------------- 1 file changed, 46 insertions(+), 42 deletions(-) (limited to 'src/host') diff --git a/src/host/hub.c b/src/host/hub.c index 1d3e9ae1d..1acea8828 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -49,13 +49,13 @@ typedef struct { // uint8_t bPwrOn2PwrGood; // uint16_t wHubCharacteristics; - CFG_TUH_MEM_ALIGN uint8_t status_change; CFG_TUH_MEM_ALIGN hub_port_status_response_t port_status; CFG_TUH_MEM_ALIGN hub_status_response_t hub_status; } hub_interface_t; typedef struct { - TUH_EPBUF_DEF(buf, CFG_TUH_HUB_BUFSIZE); + TUH_EPBUF_DEF(status_change, 4); // interrupt endpoint + TUH_EPBUF_DEF(ctrl_buf, CFG_TUH_HUB_BUFSIZE); } hub_epbuf_t; CFG_TUH_MEM_SECTION static hub_interface_t hub_itfs[CFG_TUH_HUB]; @@ -65,8 +65,8 @@ TU_ATTR_ALWAYS_INLINE static inline hub_interface_t* get_hub_itf(uint8_t daddr) return &hub_itfs[daddr-1-CFG_TUH_DEVICE_MAX]; } -TU_ATTR_ALWAYS_INLINE static inline uint8_t* get_hub_epbuf(uint8_t daddr) { - return hub_epbufs[daddr-1-CFG_TUH_DEVICE_MAX].buf; +TU_ATTR_ALWAYS_INLINE static inline hub_epbuf_t* get_hub_epbuf(uint8_t daddr) { + return &hub_epbufs[daddr-1-CFG_TUH_DEVICE_MAX]; } #if CFG_TUSB_DEBUG >= HUB_DEBUG @@ -175,6 +175,10 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, return true; } +bool hub_get_status(uint8_t hub_addr, void* resp, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return hub_port_get_status(hub_addr, 0, resp, complete_cb, user_data); +} + //--------------------------------------------------------------------+ // CLASS-USBH API (don't require to verify parameters) //--------------------------------------------------------------------+ @@ -222,7 +226,8 @@ void hub_close(uint8_t dev_addr) { bool hub_edpt_status_xfer(uint8_t daddr) { hub_interface_t* hub_itf = get_hub_itf(daddr); - return usbh_edpt_xfer(daddr, hub_itf->ep_in, &hub_itf->status_change, 1); + hub_epbuf_t* p_epbuf = get_hub_epbuf(daddr); + return usbh_edpt_xfer(daddr, hub_itf->ep_in, p_epbuf->status_change, 1); } //--------------------------------------------------------------------+ @@ -234,6 +239,7 @@ static void config_port_power_complete (tuh_xfer_t* xfer); bool hub_set_config(uint8_t dev_addr, uint8_t itf_num) { hub_interface_t* p_hub = get_hub_itf(dev_addr); TU_ASSERT(itf_num == p_hub->itf_num); + hub_epbuf_t* p_epbuf = get_hub_epbuf(dev_addr); // Get Hub Descriptor tusb_control_request_t const request = { @@ -252,7 +258,7 @@ bool hub_set_config(uint8_t dev_addr, uint8_t itf_num) { .daddr = dev_addr, .ep_addr = 0, .setup = &request, - .buffer = get_hub_epbuf(dev_addr), + .buffer = p_epbuf->ctrl_buf, .complete_cb = config_set_port_power, .user_data = 0 }; @@ -266,9 +272,10 @@ static void config_set_port_power (tuh_xfer_t* xfer) { uint8_t const daddr = xfer->daddr; hub_interface_t* p_hub = get_hub_itf(daddr); + hub_epbuf_t* p_epbuf = get_hub_epbuf(daddr); // only use number of ports in hub descriptor - hub_desc_cs_t const* desc_hub = (hub_desc_cs_t const*) get_hub_epbuf(daddr); + hub_desc_cs_t const* desc_hub = (hub_desc_cs_t const*) p_epbuf->ctrl_buf; p_hub->bNbrPorts = desc_hub->bNbrPorts; // May need to GET_STATUS @@ -302,62 +309,59 @@ static void config_port_power_complete (tuh_xfer_t* xfer) { //--------------------------------------------------------------------+ // Connection Changes //--------------------------------------------------------------------+ -static void hub_port_get_status_complete (tuh_xfer_t* xfer); -static void hub_get_status_complete (tuh_xfer_t* xfer); +static void port_get_status_complete (tuh_xfer_t* xfer); +static void get_status_complete (tuh_xfer_t* xfer); static void connection_clear_conn_change_complete (tuh_xfer_t* xfer); static void connection_port_reset_complete (tuh_xfer_t* xfer); // callback as response of interrupt endpoint polling bool hub_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { - (void) xferred_bytes; // TODO can be more than 1 for hub with lots of ports + (void) xferred_bytes; (void) ep_addr; + bool processed = false; // true if new status is processed + if (result == XFER_RESULT_SUCCESS) { hub_interface_t* p_hub = get_hub_itf(dev_addr); - - uint8_t const status_change = p_hub->status_change; + hub_epbuf_t* p_epbuf = get_hub_epbuf(dev_addr); + uint8_t const status_change = p_epbuf->status_change[0]; TU_LOG_DRV(" Hub Status Change = 0x%02X\r\n", status_change); - if ( status_change == 0 ) { + if (status_change == 0) { // The status change event was neither for the hub, nor for any of its ports. - // This shouldn't happen, but it does with some devices. Initiate the next interrupt poll here. - return hub_edpt_status_xfer(dev_addr); - } - - if (tu_bit_test(status_change, 0)) { + // This shouldn't happen, but it does with some devices. Re-Initiate the interrupt poll. + processed = false; + } else if (tu_bit_test(status_change, 0)) { // Hub bit 0 is for the hub device events - if (hub_port_get_status(dev_addr, 0, &p_hub->hub_status, hub_get_status_complete, 0) == false) { - //Hub status control transfer failed, retry - hub_edpt_status_xfer(dev_addr); - } - } - else { + processed = hub_get_status(dev_addr, &p_hub->hub_status, get_status_complete, 0); + } else { // Hub bits 1 to n are hub port events for (uint8_t port=1; port <= p_hub->bNbrPorts; port++) { - if ( tu_bit_test(status_change, port) ) { - if (hub_port_get_status(dev_addr, port, &p_hub->port_status, hub_port_get_status_complete, 0) == false) { - //Hub status control transfer failed, retry - hub_edpt_status_xfer(dev_addr); - } - break; + if (tu_bit_test(status_change, port)) { + processed = hub_port_get_status(dev_addr, port, &p_hub->port_status, port_get_status_complete, 0); + break; // after completely processed one port, we will re-queue the status poll and handle next one } } } } else { - TU_LOG_DRV(" Hub Status Change: failed, retry\r\n"); - hub_edpt_status_xfer(dev_addr); // retry + processed = false; + } + + // If new status event is processed: next status pool is queued by usbh.c after handled this request + // Otherwise re-queue the status poll here + if (!processed) { + TU_ASSERT(hub_edpt_status_xfer(dev_addr)); } - // NOTE: next status transfer is queued by usbh.c after handling this request return true; } -static void hub_clear_feature_complete_stub(tuh_xfer_t* xfer) { +static void port_clear_feature_complete_stub(tuh_xfer_t* xfer) { TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); hub_edpt_status_xfer(xfer->daddr); } -static void hub_get_status_complete (tuh_xfer_t* xfer) +static void get_status_complete (tuh_xfer_t* xfer) { TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); @@ -371,16 +375,16 @@ static void hub_get_status_complete (tuh_xfer_t* xfer) if (p_hub->hub_status.change.local_power_source) { TU_LOG_DRV("HUB Local Power Change, addr = %u\r\n", daddr); - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, hub_clear_feature_complete_stub, 0); + hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, port_clear_feature_complete_stub, 0); } else if (p_hub->hub_status.change.over_current) { TU_LOG1("HUB Over Current, addr = %u\r\n", daddr); - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_OVER_CURRENT_CHANGE, hub_clear_feature_complete_stub, 0); + hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); } } -static void hub_port_get_status_complete(tuh_xfer_t *xfer) { +static void port_get_status_complete(tuh_xfer_t *xfer) { TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); uint8_t const daddr = xfer->daddr; @@ -397,13 +401,13 @@ static void hub_port_get_status_complete(tuh_xfer_t *xfer) { } else { // Clear other port status change interrupts. TODO Not currently handled - just cleared. if (p_hub->port_status.change.port_enable) { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_ENABLE_CHANGE, hub_clear_feature_complete_stub, 0); + hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_ENABLE_CHANGE, port_clear_feature_complete_stub, 0); } else if (p_hub->port_status.change.suspend) { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_SUSPEND_CHANGE, hub_clear_feature_complete_stub, 0); + hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_SUSPEND_CHANGE, port_clear_feature_complete_stub, 0); } else if (p_hub->port_status.change.over_current) { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_OVER_CURRENT_CHANGE, hub_clear_feature_complete_stub, 0); + hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); } else if (p_hub->port_status.change.reset) { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_RESET_CHANGE, hub_clear_feature_complete_stub, 0); + hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_RESET_CHANGE, port_clear_feature_complete_stub, 0); } else { // Other changes are: L1 state -- cgit v1.3.1 From 27a4895b79065340c031850b7031eea5b2f60a9b Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 19 Feb 2025 12:58:03 +0700 Subject: complete separate hub epbuf from itf add hub_get_status(), hub_clear_feature() --- src/host/hub.c | 59 ++++++++++++++++++++++++---------------------------------- src/host/hub.h | 49 +++++++++++++++++++++++++++++++----------------- 2 files changed, 56 insertions(+), 52 deletions(-) (limited to 'src/host') diff --git a/src/host/hub.c b/src/host/hub.c index 1acea8828..41aefc1a7 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -49,8 +49,7 @@ typedef struct { // uint8_t bPwrOn2PwrGood; // uint16_t wHubCharacteristics; - CFG_TUH_MEM_ALIGN hub_port_status_response_t port_status; - CFG_TUH_MEM_ALIGN hub_status_response_t hub_status; + hub_port_status_response_t port_status; } hub_interface_t; typedef struct { @@ -58,7 +57,7 @@ typedef struct { TUH_EPBUF_DEF(ctrl_buf, CFG_TUH_HUB_BUFSIZE); } hub_epbuf_t; -CFG_TUH_MEM_SECTION static hub_interface_t hub_itfs[CFG_TUH_HUB]; +static hub_interface_t hub_itfs[CFG_TUH_HUB]; CFG_TUH_MEM_SECTION static hub_epbuf_t hub_epbufs[CFG_TUH_HUB]; TU_ATTR_ALWAYS_INLINE static inline hub_interface_t* get_hub_itf(uint8_t daddr) { @@ -158,7 +157,7 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, .bRequest = HUB_REQUEST_GET_STATUS, .wValue = 0, .wIndex = hub_port, - .wLength = 4 + .wLength = tu_htole16(4) }; tuh_xfer_t xfer = { @@ -175,10 +174,6 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, return true; } -bool hub_get_status(uint8_t hub_addr, void* resp, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - return hub_port_get_status(hub_addr, 0, resp, complete_cb, user_data); -} - //--------------------------------------------------------------------+ // CLASS-USBH API (don't require to verify parameters) //--------------------------------------------------------------------+ @@ -309,8 +304,9 @@ static void config_port_power_complete (tuh_xfer_t* xfer) { //--------------------------------------------------------------------+ // Connection Changes //--------------------------------------------------------------------+ -static void port_get_status_complete (tuh_xfer_t* xfer); static void get_status_complete (tuh_xfer_t* xfer); +static void port_get_status_complete (tuh_xfer_t* xfer); +static void port_clear_feature_complete_stub(tuh_xfer_t* xfer); static void connection_clear_conn_change_complete (tuh_xfer_t* xfer); static void connection_port_reset_complete (tuh_xfer_t* xfer); @@ -323,8 +319,8 @@ bool hub_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32 if (result == XFER_RESULT_SUCCESS) { hub_interface_t* p_hub = get_hub_itf(dev_addr); - hub_epbuf_t* p_epbuf = get_hub_epbuf(dev_addr); - uint8_t const status_change = p_epbuf->status_change[0]; + hub_epbuf_t *p_epbuf = get_hub_epbuf(dev_addr); + const uint8_t status_change = p_epbuf->status_change[0]; TU_LOG_DRV(" Hub Status Change = 0x%02X\r\n", status_change); if (status_change == 0) { @@ -333,12 +329,12 @@ bool hub_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32 processed = false; } else if (tu_bit_test(status_change, 0)) { // Hub bit 0 is for the hub device events - processed = hub_get_status(dev_addr, &p_hub->hub_status, get_status_complete, 0); + processed = hub_get_status(dev_addr, p_epbuf->ctrl_buf, get_status_complete, 0); } else { // Hub bits 1 to n are hub port events for (uint8_t port=1; port <= p_hub->bNbrPorts; port++) { if (tu_bit_test(status_change, port)) { - processed = hub_port_get_status(dev_addr, port, &p_hub->port_status, port_get_status_complete, 0); + processed = hub_port_get_status(dev_addr, port, p_epbuf->ctrl_buf, port_get_status_complete, 0); break; // after completely processed one port, we will re-queue the status poll and handle next one } } @@ -361,38 +357,32 @@ static void port_clear_feature_complete_stub(tuh_xfer_t* xfer) { hub_edpt_status_xfer(xfer->daddr); } -static void get_status_complete (tuh_xfer_t* xfer) -{ +static void get_status_complete(tuh_xfer_t *xfer) { TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); + const uint8_t daddr = xfer->daddr; + hub_status_response_t hub_status = *((const hub_status_response_t *) (uintptr_t) xfer->buffer); - uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_hub_itf(daddr); - uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - TU_ASSERT(port_num == 0 , ); - - TU_LOG_DRV("HUB Got hub status, addr = %u, status = %04x\r\n", daddr, p_hub->hub_status.change.value); + TU_LOG_DRV("HUB Got hub status, addr = %u, status = %04x\r\n", daddr, hub_status.change.value); - if (p_hub->hub_status.change.local_power_source) - { - TU_LOG_DRV("HUB Local Power Change, addr = %u\r\n", daddr); - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, port_clear_feature_complete_stub, 0); - } - else if (p_hub->hub_status.change.over_current) - { - TU_LOG1("HUB Over Current, addr = %u\r\n", daddr); - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); + if (hub_status.change.local_power_source) { + TU_LOG_DRV(" Local Power Change\r\n"); + hub_clear_feature(daddr, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, port_clear_feature_complete_stub, 0); + } else if (hub_status.change.over_current) { + TU_LOG_DRV(" Over Current\r\n"); + hub_clear_feature(daddr, HUB_FEATURE_HUB_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); } } static void port_get_status_complete(tuh_xfer_t *xfer) { TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); - uint8_t const daddr = xfer->daddr; + const uint8_t port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); + const uint8_t daddr = xfer->daddr; hub_interface_t *p_hub = get_hub_itf(daddr); - uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); + p_hub->port_status = *((const hub_port_status_response_t *) (uintptr_t) xfer->buffer); - // Connection change if (p_hub->port_status.change.connection) { + // Connection change // Port is powered and enabled //TU_VERIFY(port_status.status_current.port_power && port_status.status_current.port_enable, ); @@ -408,8 +398,7 @@ static void port_get_status_complete(tuh_xfer_t *xfer) { hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); } else if (p_hub->port_status.change.reset) { hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_RESET_CHANGE, port_clear_feature_complete_stub, 0); - } - else { + } else { // Other changes are: L1 state // TODO clear change diff --git a/src/host/hub.h b/src/host/hub.h index 3b19e9838..8e1852601 100644 --- a/src/host/hub.h +++ b/src/host/hub.h @@ -148,21 +148,21 @@ TU_VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct"); // data in response of HUB_REQUEST_GET_STATUS, wIndex = Port num typedef struct { - union { + union TU_ATTR_PACKED { struct TU_ATTR_PACKED { - uint16_t connection : 1; - uint16_t port_enable : 1; - uint16_t suspend : 1; - uint16_t over_current : 1; - uint16_t reset : 1; - - uint16_t : 3; - uint16_t port_power : 1; - uint16_t low_speed : 1; - uint16_t high_speed : 1; - uint16_t port_test_mode : 1; - uint16_t port_indicator_control : 1; - uint16_t TU_RESERVED : 3; + uint16_t connection : 1; // [0] 0 = no device, 1 = device connected + uint16_t port_enable : 1; // [1] port is enabled + uint16_t suspend : 1; // [2] + uint16_t over_current : 1; // [3] over-current exists + uint16_t reset : 1; // [4] 0 = no reset, 1 = resetting + + uint16_t rsv5_7 : 3; // [5..7] reserved + uint16_t port_power : 1; // [8] 0 = port is off, 1 = port is on + uint16_t low_speed : 1; // [9] low speed device attached + uint16_t high_speed : 1; // [10] high speed device attached + uint16_t port_test_mode : 1; // [11] port in test mode + uint16_t port_indicator_control : 1; // [12] 0: default color, 1: indicator is software controlled + uint16_t TU_RESERVED : 3; // [13..15] reserved }; uint16_t value; @@ -171,11 +171,15 @@ typedef struct { TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct"); -// Clear feature +//--------------------------------------------------------------------+ +// HUB API +//--------------------------------------------------------------------+ + +// Clear port feature bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -// Set feature +// Set port feature bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, tuh_xfer_cb_t complete_cb, uintptr_t user_data); @@ -192,12 +196,23 @@ bool hub_port_reset(uint8_t hub_addr, uint8_t hub_port, tuh_xfer_cb_t complete_c return hub_port_set_feature(hub_addr, hub_port, HUB_FEATURE_PORT_RESET, complete_cb, user_data); } -// Clear Reset Change +// Clear Port Reset Change TU_ATTR_ALWAYS_INLINE static inline bool hub_port_clear_reset_change(uint8_t hub_addr, uint8_t hub_port, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return hub_port_clear_feature(hub_addr, hub_port, HUB_FEATURE_PORT_RESET_CHANGE, complete_cb, user_data); } +// Get Hub status +TU_ATTR_ALWAYS_INLINE static inline +bool hub_get_status(uint8_t hub_addr, void* resp, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return hub_port_get_status(hub_addr, 0, resp, complete_cb, user_data); +} + +// Clear Hub feature +TU_ATTR_ALWAYS_INLINE static inline +bool hub_clear_feature(uint8_t hub_addr, uint8_t feature, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return hub_port_clear_feature(hub_addr, 0, feature, complete_cb, user_data); +} //--------------------------------------------------------------------+ // Internal Class Driver API //--------------------------------------------------------------------+ -- cgit v1.3.1 From 70ddb7a8672bb523db79baf090469932127989d2 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 19 Feb 2025 15:50:42 +0700 Subject: more hub improve, handle more failed transfer with polling interrupt status endpoint --- src/host/hub.c | 158 ++++++++++++++++++++++++++++++-------------------------- src/host/hub.h | 94 ++++++++++++++------------------- src/host/usbh.c | 1 - 3 files changed, 124 insertions(+), 129 deletions(-) (limited to 'src/host') diff --git a/src/host/hub.c b/src/host/hub.c index 41aefc1a7..93b4a3a84 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -46,7 +46,7 @@ typedef struct { // from hub descriptor uint8_t bNbrPorts; - // uint8_t bPwrOn2PwrGood; + uint8_t bPwrOn2PwrGood; // port power on to good, in 2ms unit // uint16_t wHubCharacteristics; hub_port_status_response_t port_status; @@ -114,7 +114,7 @@ bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, }; TU_LOG_DRV("HUB Clear Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); - TU_ASSERT( tuh_control_xfer(&xfer) ); + TU_ASSERT(tuh_control_xfer(&xfer)); return true; } @@ -220,9 +220,16 @@ void hub_close(uint8_t dev_addr) { } bool hub_edpt_status_xfer(uint8_t daddr) { - hub_interface_t* hub_itf = get_hub_itf(daddr); + hub_interface_t* p_hub = get_hub_itf(daddr); hub_epbuf_t* p_epbuf = get_hub_epbuf(daddr); - return usbh_edpt_xfer(daddr, hub_itf->ep_in, p_epbuf->status_change, 1); + + TU_VERIFY(usbh_edpt_claim(daddr, p_hub->ep_in)); + if (!usbh_edpt_xfer(daddr, p_hub->ep_in, p_epbuf->status_change, 1)) { + usbh_edpt_release(daddr, p_hub->ep_in); + return false; + } + + return true; } //--------------------------------------------------------------------+ @@ -272,6 +279,7 @@ static void config_set_port_power (tuh_xfer_t* xfer) { // only use number of ports in hub descriptor hub_desc_cs_t const* desc_hub = (hub_desc_cs_t const*) p_epbuf->ctrl_buf; p_hub->bNbrPorts = desc_hub->bNbrPorts; + p_hub->bPwrOn2PwrGood = desc_hub->bPwrOn2PwrGood; // May need to GET_STATUS @@ -293,6 +301,7 @@ static void config_port_power_complete (tuh_xfer_t* xfer) { TU_MESS_FAILED(); TU_BREAKPOINT(); } + // delay bPwrOn2PwrGood * 2 ms before set configuration complete usbh_driver_set_config_complete(daddr, p_hub->itf_num); } else { // power next port @@ -311,15 +320,15 @@ static void connection_clear_conn_change_complete (tuh_xfer_t* xfer); static void connection_port_reset_complete (tuh_xfer_t* xfer); // callback as response of interrupt endpoint polling -bool hub_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { +bool hub_xfer_cb(uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { (void) xferred_bytes; (void) ep_addr; bool processed = false; // true if new status is processed if (result == XFER_RESULT_SUCCESS) { - hub_interface_t* p_hub = get_hub_itf(dev_addr); - hub_epbuf_t *p_epbuf = get_hub_epbuf(dev_addr); + hub_interface_t* p_hub = get_hub_itf(daddr); + hub_epbuf_t *p_epbuf = get_hub_epbuf(daddr); const uint8_t status_change = p_epbuf->status_change[0]; TU_LOG_DRV(" Hub Status Change = 0x%02X\r\n", status_change); @@ -329,136 +338,137 @@ bool hub_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32 processed = false; } else if (tu_bit_test(status_change, 0)) { // Hub bit 0 is for the hub device events - processed = hub_get_status(dev_addr, p_epbuf->ctrl_buf, get_status_complete, 0); + processed = hub_get_status(daddr, p_epbuf->ctrl_buf, get_status_complete, 0); } else { // Hub bits 1 to n are hub port events for (uint8_t port=1; port <= p_hub->bNbrPorts; port++) { if (tu_bit_test(status_change, port)) { - processed = hub_port_get_status(dev_addr, port, p_epbuf->ctrl_buf, port_get_status_complete, 0); + processed = hub_port_get_status(daddr, port, p_epbuf->ctrl_buf, port_get_status_complete, 0); break; // after completely processed one port, we will re-queue the status poll and handle next one } } } - } else { - processed = false; } // If new status event is processed: next status pool is queued by usbh.c after handled this request // Otherwise re-queue the status poll here if (!processed) { - TU_ASSERT(hub_edpt_status_xfer(dev_addr)); + TU_ASSERT(hub_edpt_status_xfer(daddr)); } return true; } static void port_clear_feature_complete_stub(tuh_xfer_t* xfer) { - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); hub_edpt_status_xfer(xfer->daddr); } static void get_status_complete(tuh_xfer_t *xfer) { - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); const uint8_t daddr = xfer->daddr; - hub_status_response_t hub_status = *((const hub_status_response_t *) (uintptr_t) xfer->buffer); - TU_LOG_DRV("HUB Got hub status, addr = %u, status = %04x\r\n", daddr, hub_status.change.value); + bool processed = false; // true if new status is processed + if (xfer->result == XFER_RESULT_SUCCESS) { + hub_status_response_t hub_status = *((const hub_status_response_t *) (uintptr_t) xfer->buffer); - if (hub_status.change.local_power_source) { - TU_LOG_DRV(" Local Power Change\r\n"); - hub_clear_feature(daddr, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, port_clear_feature_complete_stub, 0); - } else if (hub_status.change.over_current) { - TU_LOG_DRV(" Over Current\r\n"); - hub_clear_feature(daddr, HUB_FEATURE_HUB_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); + TU_LOG_DRV("HUB Got hub status, addr = %u, status = %04x\r\n", daddr, hub_status.change.value); + + if (hub_status.change.local_power_source) { + TU_LOG_DRV(" Local Power Change\r\n"); + processed = hub_clear_feature(daddr, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, port_clear_feature_complete_stub, 0); + } else if (hub_status.change.over_current) { + TU_LOG_DRV(" Over Current\r\n"); + processed = hub_clear_feature(daddr, HUB_FEATURE_HUB_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); + } + } + + if (!processed) { + TU_ASSERT(hub_edpt_status_xfer(daddr), ); } } static void port_get_status_complete(tuh_xfer_t *xfer) { - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); - - const uint8_t port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); const uint8_t daddr = xfer->daddr; - hub_interface_t *p_hub = get_hub_itf(daddr); - p_hub->port_status = *((const hub_port_status_response_t *) (uintptr_t) xfer->buffer); - - if (p_hub->port_status.change.connection) { - // Connection change - // Port is powered and enabled - //TU_VERIFY(port_status.status_current.port_power && port_status.status_current.port_enable, ); + bool processed = false; // true if new status is processed - // Acknowledge Port Connection Change - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_CONNECTION_CHANGE, connection_clear_conn_change_complete, 0); - } else { - // Clear other port status change interrupts. TODO Not currently handled - just cleared. - if (p_hub->port_status.change.port_enable) { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_ENABLE_CHANGE, port_clear_feature_complete_stub, 0); + if (xfer->result == XFER_RESULT_SUCCESS) { + const uint8_t port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); + hub_interface_t *p_hub = get_hub_itf(daddr); + p_hub->port_status = *((const hub_port_status_response_t *) (uintptr_t) xfer->buffer); + + // Clear port status change interrupts + if (p_hub->port_status.change.connection) { + // Connection change + // Port is powered and enabled + //TU_VERIFY(port_status.status_current.port_power && port_status.status_current.port_enable, ); + + // Acknowledge Port Connection Change + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_CONNECTION_CHANGE, connection_clear_conn_change_complete, 0); + } else if (p_hub->port_status.change.port_enable) { + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_ENABLE_CHANGE, port_clear_feature_complete_stub, 0); } else if (p_hub->port_status.change.suspend) { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_SUSPEND_CHANGE, port_clear_feature_complete_stub, 0); + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_SUSPEND_CHANGE, port_clear_feature_complete_stub, 0); } else if (p_hub->port_status.change.over_current) { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_OVER_CURRENT_CHANGE, port_clear_feature_complete_stub, 0); } else if (p_hub->port_status.change.reset) { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_RESET_CHANGE, port_clear_feature_complete_stub, 0); - } else { - // Other changes are: L1 state - // TODO clear change - - // prepare for next hub status - // TODO continue with status_change, or maybe we can do it again with status - hub_edpt_status_xfer(daddr); + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_RESET_CHANGE, port_clear_feature_complete_stub, 0); } } + + if (!processed) { + TU_ASSERT(hub_edpt_status_xfer(daddr), ); + } } -static void connection_clear_conn_change_complete (tuh_xfer_t* xfer) -{ - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); +static void connection_clear_conn_change_complete (tuh_xfer_t* xfer) { + const uint8_t daddr = xfer->daddr; + + if (xfer->result != XFER_RESULT_SUCCESS) { + TU_ASSERT(hub_edpt_status_xfer(daddr), ); + return; + } - uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_hub_itf(daddr); - uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); + hub_interface_t *p_hub = get_hub_itf(daddr); + const uint8_t port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - if ( p_hub->port_status.status.connection ) - { + if (p_hub->port_status.status.connection) { // Reset port if attach event hub_port_reset(daddr, port_num, connection_port_reset_complete, 0); - }else - { + } else { // submit detach event - hcd_event_t event = - { + const hcd_event_t event = { .rhport = usbh_get_rhport(daddr), .event_id = HCD_EVENT_DEVICE_REMOVE, - .connection = - { + .connection = { .hub_addr = daddr, .hub_port = port_num } }; - hcd_event_handler(&event, false); } } -static void connection_port_reset_complete (tuh_xfer_t* xfer) -{ - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); +static void connection_port_reset_complete (tuh_xfer_t* xfer) { + const uint8_t daddr = xfer->daddr; - uint8_t const daddr = xfer->daddr; - // hub_interface_t* p_hub = get_itf(daddr); - uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); + if (xfer->result != XFER_RESULT_SUCCESS) { + // retry port reset if failed + if (!tuh_control_xfer(xfer)) { + TU_ASSERT(hub_edpt_status_xfer(daddr), ); // back to status poll if failed to queue request + } + return; + } + + const uint8_t port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); // submit attach event - hcd_event_t event = - { + hcd_event_t event = { .rhport = usbh_get_rhport(daddr), .event_id = HCD_EVENT_DEVICE_ATTACH, - .connection = - { + .connection = { .hub_addr = daddr, .hub_port = port_num } }; - hcd_event_handler(&event, false); } diff --git a/src/host/hub.h b/src/host/hub.h index 8e1852601..e4e576661 100644 --- a/src/host/hub.h +++ b/src/host/hub.h @@ -41,58 +41,9 @@ #define CFG_TUH_HUB_BUFSIZE 12 #endif -//D1...D0: Logical Power Switching Mode -//00: Ganged power switching (all ports’power at -//once) -//01: Individual port power switching -//1X: Reserved. Used only on 1.0 compliant hubs -//that implement no power switching -//D2: Identifies a Compound Device -//0: Hub is not part of a compound device. -//1: Hub is part of a compound device. -//D4...D3: Over-current Protection Mode -//00: Global Over-current Protection. The hub -//reports over-current as a summation of all -//ports’current draw, without a breakdown of -//individual port over-current status. -//01: Individual Port Over-current Protection. The -//hub reports over-current on a per-port basis. -//Each port has an over-current status. -//1X: No Over-current Protection. This option is -//allowed only for bus-powered hubs that do not -//implement over-current protection. +//--------------------------------------------------------------------+ // -//D6...D5: TT Think TIme -//00: TT requires at most 8 FS bit times of inter -//transaction gap on a full-/low-speed -//downstream bus. -//01: TT requires at most 16 FS bit times. -//10: TT requires at most 24 FS bit times. -//11: TT requires at most 32 FS bit times. -//D7: Port Indicators Supported -//0: Port Indicators are not supported on its -//downstream facing ports and the -//PORT_INDICATOR request has no effect. -//1: Port Indicators are supported on its -//downstream facing ports and the -//PORT_INDICATOR request controls the -//indicators. See Section 11.5.3. -//D15...D8: Reserved - -typedef struct TU_ATTR_PACKED{ - uint8_t bLength ; ///< Size of descriptor - uint8_t bDescriptorType ; ///< Other_speed_Configuration Type - uint8_t bNbrPorts; - uint16_t wHubCharacteristics; - uint8_t bPwrOn2PwrGood; - uint8_t bHubContrCurrent; - uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1) - uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff -} hub_desc_cs_t; - -TU_VERIFY_STATIC(sizeof(hub_desc_cs_t) == 9, "size is not correct"); -TU_VERIFY_STATIC(CFG_TUH_HUB_BUFSIZE >= sizeof(hub_desc_cs_t), "buffer is not big enough"); - +//--------------------------------------------------------------------+ enum { HUB_REQUEST_GET_STATUS = 0 , HUB_REQUEST_CLEAR_FEATURE = 1 , @@ -131,6 +82,41 @@ enum{ HUB_FEATURE_PORT_INDICATOR = 22 }; +enum { + HUB_CHARS_POWER_GANGED_SWITCHING = 0, + HUB_CHARS_POWER_INDIVIDUAL_SWITCHING = 1, +}; + +enum { + HUB_CHARS_OVER_CURRENT_GLOBAL = 0, + HUB_CHARS_OVER_CURRENT_INDIVIDUAL = 1, +}; + +typedef struct TU_ATTR_PACKED{ + uint8_t bLength ; ///< Size of descriptor + uint8_t bDescriptorType ; ///< Other_speed_Configuration Type + uint8_t bNbrPorts; + uint16_t wHubCharacteristics; + uint8_t bPwrOn2PwrGood; + uint8_t bHubContrCurrent; + uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1) + uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff +} hub_desc_cs_t; +TU_VERIFY_STATIC(sizeof(hub_desc_cs_t) == 9, "size is not correct"); +TU_VERIFY_STATIC(CFG_TUH_HUB_BUFSIZE >= sizeof(hub_desc_cs_t), "buffer is not big enough"); + +typedef struct TU_ATTR_PACKED { + struct TU_ATTR_PACKED { + uint8_t logical_power_switching_mode : 2; // [0..1] gannged or individual power switching + uint8_t compound_device : 1; // [2] hub is part of compound device + uint8_t over_current_protect_mode : 2; // [3..4] global or individual port over-current protection + uint8_t tt_think_time : 2; // [5..6] TT think time + uint8_t port_indicator_supported : 1; // [7] port indicator supported + }; + uint8_t rsv1; +} hub_characteristics_t; +TU_VERIFY_STATIC(sizeof(hub_characteristics_t) == 2, "size is not correct"); + // data in response of HUB_REQUEST_GET_STATUS, wIndex = 0 (hub) typedef struct { union{ @@ -143,19 +129,20 @@ typedef struct { uint16_t value; } status, change; } hub_status_response_t; - TU_VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct"); // data in response of HUB_REQUEST_GET_STATUS, wIndex = Port num typedef struct { union TU_ATTR_PACKED { struct TU_ATTR_PACKED { + // Bit 0-4 are for change & status uint16_t connection : 1; // [0] 0 = no device, 1 = device connected uint16_t port_enable : 1; // [1] port is enabled uint16_t suspend : 1; // [2] uint16_t over_current : 1; // [3] over-current exists uint16_t reset : 1; // [4] 0 = no reset, 1 = resetting + // From Bit 5 are for status only uint16_t rsv5_7 : 3; // [5..7] reserved uint16_t port_power : 1; // [8] 0 = port is off, 1 = port is on uint16_t low_speed : 1; // [9] low speed device attached @@ -168,7 +155,6 @@ typedef struct { uint16_t value; } status, change; } hub_port_status_response_t; - TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct"); //--------------------------------------------------------------------+ @@ -220,7 +206,7 @@ bool hub_init (void); bool hub_deinit (void); bool hub_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t max_len); bool hub_set_config (uint8_t dev_addr, uint8_t itf_num); -bool hub_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); +bool hub_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); void hub_close (uint8_t dev_addr); #ifdef __cplusplus diff --git a/src/host/usbh.c b/src/host/usbh.c index ac920f533..c7a9a868f 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -920,7 +920,6 @@ bool usbh_edpt_release(uint8_t dev_addr, uint8_t ep_addr) { } // Submit an transfer -// TODO call usbh_edpt_release if failed bool usbh_edpt_xfer_with_callback(uint8_t dev_addr, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { (void) complete_cb; -- cgit v1.3.1 From d132044b7587f7e846bbec6e7b897d0842a21d13 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 24 Feb 2025 15:40:48 +0700 Subject: add tuh_midi_mount_cb_t struct for tuh_midi_mount_cb() change tuh_midi_rx/tx_cb() to have xferred_bytes rename tuh_midi_get_num_rx/tx_cables() to tuh_midi_get_rx/tx_cable_count() use default empty callback instead of weak null to be compatible with keil compiler --- examples/host/cdc_msc_hid/src/main.c | 4 +- examples/host/midi_rx/src/main.c | 13 +++--- src/class/cdc/cdc_host.h | 8 ++-- src/class/midi/midi_device.c | 5 --- src/class/midi/midi_host.c | 81 ++++++++++++++++-------------------- src/class/midi/midi_host.h | 34 +++++++++------ src/host/usbh_pvt.h | 4 -- 7 files changed, 70 insertions(+), 79 deletions(-) (limited to 'src/host') diff --git a/examples/host/cdc_msc_hid/src/main.c b/examples/host/cdc_msc_hid/src/main.c index 71257c0fe..2d5df23f9 100644 --- a/examples/host/cdc_msc_hid/src/main.c +++ b/examples/host/cdc_msc_hid/src/main.c @@ -82,12 +82,12 @@ int main(void) { void tuh_mount_cb(uint8_t dev_addr) { // application set-up - printf("A device with address %d is mounted\r\n", dev_addr); + printf("A device with address %u is mounted\r\n", dev_addr); } void tuh_umount_cb(uint8_t dev_addr) { // application tear-down - printf("A device with address %d is unmounted \r\n", dev_addr); + printf("A device with address %u is unmounted \r\n", dev_addr); } diff --git a/examples/host/midi_rx/src/main.c b/examples/host/midi_rx/src/main.c index 6db329ab5..d26321e5d 100644 --- a/examples/host/midi_rx/src/main.c +++ b/examples/host/midi_rx/src/main.c @@ -91,9 +91,9 @@ void midi_host_rx_task(void) { //--------------------------------------------------------------------+ // Invoked when device with MIDI interface is mounted. -void tuh_midi_mount_cb(uint8_t idx, uint8_t num_cables_rx, uint16_t num_cables_tx) { - printf("MIDI Interface Index = %u, Number of RX cables = %u, Number of TX cables = %u\r\n", - idx, num_cables_rx, num_cables_tx); +void tuh_midi_mount_cb(uint8_t idx, const tuh_midi_mount_cb_t* mount_cb_data) { + printf("MIDI Interface Index = %u, Address = %u, Number of RX cables = %u, Number of TX cables = %u\r\n", + idx, mount_cb_data->daddr, mount_cb_data->rx_cable_count, mount_cb_data->tx_cable_count); } // Invoked when device with hid interface is un-mounted @@ -101,8 +101,8 @@ void tuh_midi_umount_cb(uint8_t idx) { printf("MIDI Interface Index = %u is unmounted\r\n", idx); } -void tuh_midi_rx_cb(uint8_t idx, uint32_t num_packets) { - if (num_packets == 0) { +void tuh_midi_rx_cb(uint8_t idx, uint32_t xferred_bytes) { + if (xferred_bytes == 0) { return; } @@ -117,6 +117,7 @@ void tuh_midi_rx_cb(uint8_t idx, uint32_t num_packets) { printf("\r\n"); } -void tuh_midi_tx_cb(uint8_t idx) { +void tuh_midi_tx_cb(uint8_t idx, uint32_t xferred_bytes) { (void) idx; + (void) xferred_bytes; } diff --git a/src/class/cdc/cdc_host.h b/src/class/cdc/cdc_host.h index df975b2f0..8c5399534 100644 --- a/src/class/cdc/cdc_host.h +++ b/src/class/cdc/cdc_host.h @@ -49,22 +49,22 @@ // RX FIFO size #ifndef CFG_TUH_CDC_RX_BUFSIZE -#define CFG_TUH_CDC_RX_BUFSIZE USBH_EPSIZE_BULK_MAX +#define CFG_TUH_CDC_RX_BUFSIZE TUH_EPSIZE_BULK_MPS #endif // RX Endpoint size #ifndef CFG_TUH_CDC_RX_EPSIZE -#define CFG_TUH_CDC_RX_EPSIZE USBH_EPSIZE_BULK_MAX +#define CFG_TUH_CDC_RX_EPSIZE TUH_EPSIZE_BULK_MPS #endif // TX FIFO size #ifndef CFG_TUH_CDC_TX_BUFSIZE -#define CFG_TUH_CDC_TX_BUFSIZE USBH_EPSIZE_BULK_MAX +#define CFG_TUH_CDC_TX_BUFSIZE TUH_EPSIZE_BULK_MPS #endif // TX Endpoint size #ifndef CFG_TUH_CDC_TX_EPSIZE -#define CFG_TUH_CDC_TX_EPSIZE USBH_EPSIZE_BULK_MAX +#define CFG_TUH_CDC_TX_EPSIZE TUH_EPSIZE_BULK_MPS #endif //--------------------------------------------------------------------+ diff --git a/src/class/midi/midi_device.c b/src/class/midi/midi_device.c index 7b6705640..0bbb3caf4 100644 --- a/src/class/midi/midi_device.c +++ b/src/class/midi/midi_device.c @@ -39,9 +39,6 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ - - - typedef struct { uint8_t itf_num; uint8_t ep_in; @@ -440,8 +437,6 @@ uint16_t midid_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uint1 drv_len += tu_desc_len(p_desc); p_desc = tu_desc_next(p_desc); } - } else { - TU_LOG2("Warning: MIDI Device has no Audio Control Interface"); } // 2nd Interface is MIDI Streaming diff --git a/src/class/midi/midi_host.c b/src/class/midi/midi_host.c index 770a39a8d..a4b1ebd2e 100644 --- a/src/class/midi/midi_host.c +++ b/src/class/midi/midi_host.c @@ -40,6 +40,15 @@ #define TU_LOG_DRV(...) TU_LOG(CFG_TUH_MIDI_LOG_LEVEL, __VA_ARGS__) +//--------------------------------------------------------------------+ +// Weak stubs: invoked if no strong implementation is available +//--------------------------------------------------------------------+ +TU_ATTR_WEAK void tuh_midi_descriptor_cb(uint8_t idx, const tuh_midi_descriptor_cb_t * desc_cb_data) { (void) idx; (void) desc_cb_data; } +TU_ATTR_WEAK void tuh_midi_mount_cb(uint8_t idx, const tuh_midi_mount_cb_t* mount_cb_data) { (void) idx; (void) mount_cb_data; } +TU_ATTR_WEAK void tuh_midi_umount_cb(uint8_t idx) { (void) idx; } +TU_ATTR_WEAK void tuh_midi_rx_cb(uint8_t idx, uint32_t xferred_bytes) { (void) idx; (void) xferred_bytes; } +TU_ATTR_WEAK void tuh_midi_tx_cb(uint8_t idx, uint32_t xferred_bytes) { (void) idx; (void) xferred_bytes; } + //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ @@ -52,8 +61,8 @@ typedef struct { uint8_t ep_in; // IN endpoint address uint8_t ep_out; // OUT endpoint address - uint8_t num_cables_rx; // IN endpoint CS descriptor bNumEmbMIDIJack value - uint8_t num_cables_tx; // OUT endpoint CS descriptor bNumEmbMIDIJack value + uint8_t rx_cable_count; // IN endpoint CS descriptor bNumEmbMIDIJack value + uint8_t tx_cable_count; // OUT endpoint CS descriptor bNumEmbMIDIJack value #if CFG_TUH_MIDI_STREAM_API // For Stream read()/write() API @@ -135,16 +144,13 @@ void midih_close(uint8_t daddr) { midih_interface_t* p_midi = &_midi_host[idx]; if (p_midi->daddr == daddr) { TU_LOG_DRV(" MIDI close addr = %u index = %u\r\n", daddr, idx); - - if (tuh_midi_umount_cb) { - tuh_midi_umount_cb(idx); - } + tuh_midi_umount_cb(idx); p_midi->ep_in = 0; p_midi->ep_out = 0; p_midi->bInterfaceNumber = 0; - p_midi->num_cables_rx = 0; - p_midi->num_cables_tx = 0; + p_midi->rx_cable_count = 0; + p_midi->tx_cable_count = 0; p_midi->daddr = 0; p_midi->mounted = false; tu_memclr(&p_midi->stream_read, sizeof(p_midi->stream_read)); @@ -163,33 +169,16 @@ bool midih_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint midih_interface_t *p_midi_host = &_midi_host[idx]; if (ep_addr == p_midi_host->ep_stream.rx.ep_addr) { - // receive new data if available + // receive new data, put it into FIFO and invoke callback if available if (xferred_bytes) { - // put in the RX FIFO only non-zero MIDI IN 4-byte packets - uint32_t packets_queued = 0; - uint8_t *buf = _midi_epbuf->rx; - const uint32_t npackets = xferred_bytes / 4; - for (uint32_t p = 0; p < npackets; p++) { - // some devices send back all zero packets even if there is no data ready - const uint32_t packet = tu_unaligned_read32(buf); - if (packet != 0) { - tu_edpt_stream_read_xfer_complete_with_buf(&p_midi_host->ep_stream.rx, buf, 4); - ++packets_queued; - TU_LOG3("MIDI RX=%08x\r\n", packet); - } - buf += 4; - } - - if (tuh_midi_rx_cb) { - tuh_midi_rx_cb(idx, packets_queued); - } + tu_edpt_stream_read_xfer_complete(&p_midi_host->ep_stream.rx, xferred_bytes); + tuh_midi_rx_cb(idx, xferred_bytes); } tu_edpt_stream_read_xfer(dev_addr, &p_midi_host->ep_stream.rx); // prepare for next transfer } else if (ep_addr == p_midi_host->ep_stream.tx.ep_addr) { - if (tuh_midi_tx_cb) { - tuh_midi_tx_cb(idx); - } + tuh_midi_tx_cb(idx, xferred_bytes); + if (0 == tu_edpt_stream_write_xfer(dev_addr, &p_midi_host->ep_stream.tx)) { // If there is no data left, a ZLP should be sent if // xferred_bytes is multiple of EP size and not zero @@ -207,7 +196,6 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d (void) rhport; TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass); - // const uint8_t* p_start = ((uint8_t const*) desc_itf); const uint8_t *p_end = ((const uint8_t *) desc_itf) + max_len; const uint8_t *p_desc = (const uint8_t *) desc_itf; @@ -286,14 +274,14 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d TU_LOG_DRV(" Endpoint and CS_Endpoint descriptor %02x\r\n", p_ep->bEndpointAddress); if (tu_edpt_dir(p_ep->bEndpointAddress) == TUSB_DIR_OUT) { p_midi->ep_out = p_ep->bEndpointAddress; - p_midi->num_cables_tx = p_csep->bNumEmbMIDIJack; + p_midi->tx_cable_count = p_csep->bNumEmbMIDIJack; desc_cb.desc_epout = p_ep; TU_ASSERT(tuh_edpt_open(dev_addr, p_ep)); tu_edpt_stream_open(&p_midi->ep_stream.tx, p_ep); } else { p_midi->ep_in = p_ep->bEndpointAddress; - p_midi->num_cables_rx = p_csep->bNumEmbMIDIJack; + p_midi->rx_cable_count = p_csep->bNumEmbMIDIJack; desc_cb.desc_epin = p_ep; TU_ASSERT(tuh_edpt_open(dev_addr, p_ep)); @@ -309,10 +297,7 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d desc_cb.desc_midi_total_len = (uint16_t) ((uintptr_t)p_desc - (uintptr_t) desc_itf); p_midi->daddr = dev_addr; - - if (tuh_midi_descriptor_cb) { - tuh_midi_descriptor_cb(idx, &desc_cb); - } + tuh_midi_descriptor_cb(idx, &desc_cb); return true; } @@ -323,9 +308,13 @@ bool midih_set_config(uint8_t dev_addr, uint8_t itf_num) { midih_interface_t *p_midi = &_midi_host[idx]; p_midi->mounted = true; - if (tuh_midi_mount_cb) { - tuh_midi_mount_cb(idx, p_midi->num_cables_rx, p_midi->num_cables_tx); - } + const tuh_midi_mount_cb_t mount_cb_data = { + .daddr = dev_addr, + .bInterfaceNumber = itf_num, + .rx_cable_count = p_midi->rx_cable_count, + .tx_cable_count = p_midi->tx_cable_count, + }; + tuh_midi_mount_cb(idx, &mount_cb_data); tu_edpt_stream_read_xfer(dev_addr, &p_midi->ep_stream.rx); // prepare for incoming data @@ -355,18 +344,18 @@ uint8_t tuh_midi_itf_get_index(uint8_t daddr, uint8_t itf_num) { return TUSB_INDEX_INVALID_8; } -uint8_t tuh_midi_get_num_tx_cables (uint8_t idx) { +uint8_t tuh_midi_get_tx_cable_count (uint8_t idx) { TU_VERIFY(idx < CFG_TUH_MIDI); midih_interface_t *p_midi = &_midi_host[idx]; TU_VERIFY(p_midi->ep_stream.tx.ep_addr != 0, 0); - return p_midi->num_cables_tx; + return p_midi->tx_cable_count; } -uint8_t tuh_midi_get_num_rx_cables (uint8_t idx) { +uint8_t tuh_midi_get_rx_cable_count (uint8_t idx) { TU_VERIFY(idx < CFG_TUH_MIDI); midih_interface_t *p_midi = &_midi_host[idx]; TU_VERIFY(p_midi->ep_stream.rx.ep_addr != 0, 0); - return p_midi->num_cables_rx; + return p_midi->rx_cable_count; } uint32_t tuh_midi_read_available(uint8_t idx) { @@ -410,7 +399,7 @@ uint32_t tuh_midi_packet_write_n(uint8_t idx, const uint8_t* buffer, uint32_t bu uint32_t tuh_midi_stream_write(uint8_t idx, uint8_t cable_num, uint8_t const *buffer, uint32_t bufsize) { TU_VERIFY(idx < CFG_TUH_MIDI && buffer && bufsize > 0); midih_interface_t *p_midi = &_midi_host[idx]; - TU_VERIFY(cable_num < p_midi->num_cables_tx); + TU_VERIFY(cable_num < p_midi->tx_cable_count); midi_driver_stream_t *stream = &p_midi->stream_write; uint32_t byte_count = 0; @@ -520,7 +509,7 @@ uint32_t tuh_midi_stream_read(uint8_t idx, uint8_t *p_cable_num, uint8_t *p_buff while (nread == 4 && bytes_buffered < bufsize) { *p_cable_num = (p_midi->stream_read.buffer[0] >> 4) & 0x0f; uint8_t bytes_to_add_to_stream = 0; - if (*p_cable_num < p_midi->num_cables_rx) { + if (*p_cable_num < p_midi->rx_cable_count) { // ignore the CIN field; too many devices out there encode this wrong uint8_t status = p_midi->stream_read.buffer[1]; uint16_t cable_mask = (uint16_t) (1 << *p_cable_num); diff --git a/src/class/midi/midi_host.h b/src/class/midi/midi_host.h index 717e6ba67..b06bb43d7 100644 --- a/src/class/midi/midi_host.h +++ b/src/class/midi/midi_host.h @@ -37,10 +37,6 @@ //--------------------------------------------------------------------+ // Class Driver Configuration //--------------------------------------------------------------------+ -#ifndef CFG_TUH_MAX_CABLES -#define CFG_TUH_MAX_CABLES 16 -#endif - #ifndef CFG_TUH_MIDI_RX_BUFSIZE #define CFG_TUH_MIDI_RX_BUFSIZE TUH_EPSIZE_BULK_MPS #endif @@ -60,7 +56,7 @@ #endif //--------------------------------------------------------------------+ -// Application API +// Application Types //--------------------------------------------------------------------+ typedef struct { const tusb_desc_interface_t* desc_audio_control; @@ -76,6 +72,17 @@ typedef struct { const uint8_t* desc_jack[16]; // list of jack descriptors (embedded + external) } tuh_midi_descriptor_cb_t; +typedef struct { + uint8_t daddr; + uint8_t bInterfaceNumber; // interface number of MIDI streaming + uint8_t rx_cable_count; + uint8_t tx_cable_count; +} tuh_midi_mount_cb_t; + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + // Check if MIDI interface is mounted bool tuh_midi_mounted(uint8_t idx); @@ -84,10 +91,10 @@ bool tuh_midi_mounted(uint8_t idx); uint8_t tuh_midi_itf_get_index(uint8_t daddr, uint8_t itf_num); // return the number of virtual midi cables on the device's IN endpoint -uint8_t tuh_midi_get_num_rx_cables(uint8_t idx); +uint8_t tuh_midi_get_rx_cable_count(uint8_t idx); // return the number of virtual midi cables on the device's OUT endpoint -uint8_t tuh_midi_get_num_tx_cables(uint8_t idx); +uint8_t tuh_midi_get_tx_cable_count(uint8_t idx); // return the raw number of bytes available. // Note: this is related but not the same as number of stream bytes available. @@ -151,16 +158,19 @@ uint32_t tuh_midi_stream_read(uint8_t idx, uint8_t *p_cable_num, uint8_t *p_buff // Invoked when MIDI interface is detected in enumeration. Application can copy/parse descriptor if needed. // Note: may be fired before tuh_midi_mount_cb(), therefore midi interface is not mounted/ready. -TU_ATTR_WEAK void tuh_midi_descriptor_cb(uint8_t idx, const tuh_midi_descriptor_cb_t * desc_cb); +void tuh_midi_descriptor_cb(uint8_t idx, const tuh_midi_descriptor_cb_t * desc_cb_data); // Invoked when device with MIDI interface is mounted. -TU_ATTR_WEAK void tuh_midi_mount_cb(uint8_t idx, uint8_t num_cables_rx, uint16_t num_cables_tx); +void tuh_midi_mount_cb(uint8_t idx, const tuh_midi_mount_cb_t* mount_cb_data); // Invoked when device with MIDI interface is un-mounted -TU_ATTR_WEAK void tuh_midi_umount_cb(uint8_t idx); +void tuh_midi_umount_cb(uint8_t idx); + +// Invoked when received new data +void tuh_midi_rx_cb(uint8_t idx, uint32_t xferred_bytes); -TU_ATTR_WEAK void tuh_midi_rx_cb(uint8_t idx, uint32_t num_packets); -TU_ATTR_WEAK void tuh_midi_tx_cb(uint8_t idx); +// Invoked when a TX is complete and therefore space becomes available in TX buffer +void tuh_midi_tx_cb(uint8_t idx, uint32_t xferred_bytes); //--------------------------------------------------------------------+ // Internal Class Driver API diff --git a/src/host/usbh_pvt.h b/src/host/usbh_pvt.h index d27c4baa2..bfa1fb2ba 100644 --- a/src/host/usbh_pvt.h +++ b/src/host/usbh_pvt.h @@ -41,10 +41,6 @@ #define TU_LOG_INT_USBH(...) TU_LOG_INT(CFG_TUH_LOG_LEVEL, __VA_ARGS__) #define TU_LOG_HEX_USBH(...) TU_LOG_HEX(CFG_TUH_LOG_LEVEL, __VA_ARGS__) -enum { - USBH_EPSIZE_BULK_MAX = (TUH_OPT_HIGH_SPEED ? TUSB_EPSIZE_BULK_HS : TUSB_EPSIZE_BULK_FS) -}; - //--------------------------------------------------------------------+ // Class Driver API //--------------------------------------------------------------------+ -- cgit v1.3.1 From 5f447b76ad23e8c977a5167b0b4dce93cd2980de Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 3 Mar 2025 23:22:23 +0700 Subject: - add tuh_descriptor_get_string_langid() API - host enumeration always get language id, manufacturer, product and serial string. Which is required by some device such as 8bitdo --- examples/host/cdc_msc_hid/src/hid_app.c | 80 +++++++++++---------------- src/common/tusb_types.h | 2 +- src/host/hub.c | 5 +- src/host/usbh.c | 95 ++++++++++++++++++++++++++------- src/host/usbh.h | 13 +++++ 5 files changed, 123 insertions(+), 72 deletions(-) (limited to 'src/host') diff --git a/examples/host/cdc_msc_hid/src/hid_app.c b/examples/host/cdc_msc_hid/src/hid_app.c index 3f98ec89f..5bae250cf 100644 --- a/examples/host/cdc_msc_hid/src/hid_app.c +++ b/examples/host/cdc_msc_hid/src/hid_app.c @@ -39,18 +39,16 @@ static uint8_t const keycode2ascii[128][2] = { HID_KEYCODE_TO_ASCII }; // Each HID instance can has multiple reports -static struct -{ +static struct { uint8_t report_count; tuh_hid_report_info_t report_info[MAX_REPORT]; -}hid_info[CFG_TUH_HID]; +} hid_info[CFG_TUH_HID]; static void process_kbd_report(hid_keyboard_report_t const *report); static void process_mouse_report(hid_mouse_report_t const * report); static void process_generic_report(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len); -void hid_app_task(void) -{ +void hid_app_task(void) { // nothing to do } @@ -63,64 +61,57 @@ void hid_app_task(void) // can be used to parse common/simple enough descriptor. // Note: if report descriptor length > CFG_TUH_ENUMERATION_BUFSIZE, it will be skipped // therefore report_desc = NULL, desc_len = 0 -void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) -{ +void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const *desc_report, uint16_t desc_len) { printf("HID device address = %d, instance = %d is mounted\r\n", dev_addr, instance); // Interface protocol (hid_interface_protocol_enum_t) - const char* protocol_str[] = { "None", "Keyboard", "Mouse" }; + const char *protocol_str[] = {"None", "Keyboard", "Mouse"}; uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance); printf("HID Interface Protocol = %s\r\n", protocol_str[itf_protocol]); // By default host stack will use activate boot protocol on supported interface. // Therefore for this simple example, we only need to parse generic report descriptor (with built-in parser) - if ( itf_protocol == HID_ITF_PROTOCOL_NONE ) - { + if (itf_protocol == HID_ITF_PROTOCOL_NONE) { hid_info[instance].report_count = tuh_hid_parse_report_descriptor(hid_info[instance].report_info, MAX_REPORT, desc_report, desc_len); printf("HID has %u reports \r\n", hid_info[instance].report_count); } // request to receive report // tuh_hid_report_received_cb() will be invoked when report is available - if ( !tuh_hid_receive_report(dev_addr, instance) ) - { + if (!tuh_hid_receive_report(dev_addr, instance)) { printf("Error: cannot request to receive report\r\n"); } } // Invoked when device with hid interface is un-mounted -void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) -{ +void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) { printf("HID device address = %d, instance = %d is unmounted\r\n", dev_addr, instance); } // Invoked when received report from device via interrupt endpoint -void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) -{ +void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const *report, uint16_t len) { uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance); - switch (itf_protocol) - { + switch (itf_protocol) { case HID_ITF_PROTOCOL_KEYBOARD: TU_LOG2("HID receive boot keyboard report\r\n"); - process_kbd_report( (hid_keyboard_report_t const*) report ); - break; + process_kbd_report((hid_keyboard_report_t const *) report); + break; case HID_ITF_PROTOCOL_MOUSE: TU_LOG2("HID receive boot mouse report\r\n"); - process_mouse_report( (hid_mouse_report_t const*) report ); - break; + process_mouse_report((hid_mouse_report_t const *) report); + break; default: // Generic report requires matching ReportID and contents with previous parsed report info process_generic_report(dev_addr, instance, report, len); - break; + break; } // continue to request to receive report - if ( !tuh_hid_receive_report(dev_addr, instance) ) - { + if (!tuh_hid_receive_report(dev_addr, instance)) { printf("Error: cannot request to receive report\r\n"); } } @@ -231,29 +222,24 @@ static void process_mouse_report(hid_mouse_report_t const * report) //--------------------------------------------------------------------+ // Generic Report //--------------------------------------------------------------------+ -static void process_generic_report(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) -{ +static void process_generic_report(uint8_t dev_addr, uint8_t instance, uint8_t const *report, uint16_t len) { (void) dev_addr; (void) len; uint8_t const rpt_count = hid_info[instance].report_count; - tuh_hid_report_info_t* rpt_info_arr = hid_info[instance].report_info; - tuh_hid_report_info_t* rpt_info = NULL; + tuh_hid_report_info_t *rpt_info_arr = hid_info[instance].report_info; + tuh_hid_report_info_t *rpt_info = NULL; - if ( rpt_count == 1 && rpt_info_arr[0].report_id == 0) - { + if (rpt_count == 1 && rpt_info_arr[0].report_id == 0) { // Simple report without report ID as 1st byte rpt_info = &rpt_info_arr[0]; - }else - { + } else { // Composite report, 1st byte is report ID, data starts from 2nd byte uint8_t const rpt_id = report[0]; // Find report id in the array - for(uint8_t i=0; iusage_page == HID_USAGE_PAGE_DESKTOP ) - { - switch (rpt_info->usage) - { + if (rpt_info->usage_page == HID_USAGE_PAGE_DESKTOP) { + switch (rpt_info->usage) { case HID_USAGE_DESKTOP_KEYBOARD: TU_LOG1("HID receive keyboard report\r\n"); // Assume keyboard follow boot report layout - process_kbd_report( (hid_keyboard_report_t const*) report ); - break; + process_kbd_report((hid_keyboard_report_t const *) report); + break; case HID_USAGE_DESKTOP_MOUSE: TU_LOG1("HID receive mouse report\r\n"); // Assume mouse follow boot report layout - process_mouse_report( (hid_mouse_report_t const*) report ); - break; + process_mouse_report((hid_mouse_report_t const *) report); + break; - default: break; + default: + break; } } } diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 42ce5fc12..71af132af 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -462,7 +462,7 @@ TU_VERIFY_STATIC( sizeof(tusb_desc_interface_assoc_t) == 8, "size is not correct typedef struct TU_ATTR_PACKED { uint8_t bLength ; ///< Size of this descriptor in bytes uint8_t bDescriptorType ; ///< Descriptor Type - uint16_t unicode_string[]; + uint16_t utf16le[]; } tusb_desc_string_t; // USB Binary Device Object Store (BOS) diff --git a/src/host/hub.c b/src/host/hub.c index 93b4a3a84..61efa8ba5 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -46,7 +46,7 @@ typedef struct { // from hub descriptor uint8_t bNbrPorts; - uint8_t bPwrOn2PwrGood; // port power on to good, in 2ms unit + uint8_t bPwrOn2PwrGood_2ms; // port power on to good, in 2ms unit // uint16_t wHubCharacteristics; hub_port_status_response_t port_status; @@ -279,7 +279,7 @@ static void config_set_port_power (tuh_xfer_t* xfer) { // only use number of ports in hub descriptor hub_desc_cs_t const* desc_hub = (hub_desc_cs_t const*) p_epbuf->ctrl_buf; p_hub->bNbrPorts = desc_hub->bNbrPorts; - p_hub->bPwrOn2PwrGood = desc_hub->bPwrOn2PwrGood; + p_hub->bPwrOn2PwrGood_2ms = desc_hub->bPwrOn2PwrGood; // May need to GET_STATUS @@ -301,7 +301,6 @@ static void config_port_power_complete (tuh_xfer_t* xfer) { TU_MESS_FAILED(); TU_BREAKPOINT(); } - // delay bPwrOn2PwrGood * 2 ms before set configuration complete usbh_driver_set_config_complete(daddr, p_hub->itf_num); } else { // power next port diff --git a/src/host/usbh.c b/src/host/usbh.c index c7a9a868f..dcd22ee31 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -1282,13 +1282,17 @@ static void process_removing_device(uint8_t rhport, uint8_t hub_addr, uint8_t hu removing_hubs |= TU_BIT(dev_id - CFG_TUH_DEVICE_MAX); } else { // Invoke callback before closing driver (maybe call it later ?) - if (tuh_umount_cb) tuh_umount_cb(daddr); + if (tuh_umount_cb) { + tuh_umount_cb(daddr); + } } // Close class driver for (uint8_t drv_id = 0; drv_id < TOTAL_DRIVER_COUNT; drv_id++) { usbh_class_driver_t const* driver = get_driver(drv_id); - if (driver) driver->close(daddr); + if (driver) { + driver->close(daddr); + } } hcd_device_close(rhport, daddr); @@ -1345,8 +1349,11 @@ enum { ENUM_HUB_GET_STATUS_2, ENUM_HUB_CLEAR_RESET_2, ENUM_SET_ADDR, - ENUM_GET_DEVICE_DESC, + ENUM_GET_STRING_LANGUAGE_ID, + ENUM_GET_STRING_MANUFACTURER, + ENUM_GET_STRING_PRODUCT, + ENUM_GET_STRING_SERIAL, ENUM_GET_9BYTE_CONFIG_DESC, ENUM_GET_FULL_CONFIG_DESC, ENUM_SET_CONFIG, @@ -1359,25 +1366,25 @@ static void enum_full_complete(void); // process device enumeration static void process_enumeration(tuh_xfer_t* xfer) { - // Retry a few times with transfers in enumeration since device can be unstable when starting up - enum { - ATTEMPT_COUNT_MAX = 3, - ATTEMPT_DELAY_MS = 100 - }; + // Retry a few times while enumerating since device can be unstable when starting up static uint8_t failed_count = 0; + if (XFER_RESULT_FAILED == xfer->result) { + enum { + ATTEMPT_COUNT_MAX = 3, + ATTEMPT_DELAY_MS = 100 + }; - if (XFER_RESULT_SUCCESS != xfer->result) { // retry if not reaching max attempt + failed_count++; bool retry = _dev0.enumerating && (failed_count < ATTEMPT_COUNT_MAX); - if ( retry ) { - failed_count++; + if (retry) { tusb_time_delay_ms_api(ATTEMPT_DELAY_MS); // delay a bit - TU_LOG1("Enumeration attempt %u\r\n", failed_count); + TU_LOG1("Enumeration attempt %u/%u\r\n", failed_count+1, ATTEMPT_COUNT_MAX); retry = tuh_control_xfer(xfer); } if (!retry) { - enum_full_complete(); + enum_full_complete(); // complete as failed } return; @@ -1386,6 +1393,8 @@ static void process_enumeration(tuh_xfer_t* xfer) { uint8_t const daddr = xfer->daddr; uintptr_t const state = xfer->user_data; + usbh_device_t* dev = get_device(daddr); + uint16_t langid = 0x0409; // default is English switch (state) { #if CFG_TUH_HUB @@ -1476,7 +1485,6 @@ static void process_enumeration(tuh_xfer_t* xfer) { tusb_time_delay_ms_api(2); const uint8_t new_addr = (uint8_t) tu_le16toh(xfer->setup->wValue); - usbh_device_t* new_dev = get_device(new_addr); TU_ASSERT(new_dev,); new_dev->addressed = 1; @@ -1490,21 +1498,69 @@ static void process_enumeration(tuh_xfer_t* xfer) { // Get full device descriptor TU_LOG_USBH("Get Device Descriptor\r\n"); TU_ASSERT(tuh_descriptor_get_device(new_addr, _usbh_epbuf.ctrl, sizeof(tusb_desc_device_t), - process_enumeration, ENUM_GET_9BYTE_CONFIG_DESC),); + process_enumeration, ENUM_GET_STRING_LANGUAGE_ID),); break; } - case ENUM_GET_9BYTE_CONFIG_DESC: { - tusb_desc_device_t const* desc_device = (tusb_desc_device_t const*) _usbh_epbuf.ctrl; - usbh_device_t* dev = get_device(daddr); + case ENUM_GET_STRING_LANGUAGE_ID: { + // save the received device descriptor TU_ASSERT(dev,); - + tusb_desc_device_t const* desc_device = (tusb_desc_device_t const*) _usbh_epbuf.ctrl; dev->vid = desc_device->idVendor; dev->pid = desc_device->idProduct; dev->i_manufacturer = desc_device->iManufacturer; dev->i_product = desc_device->iProduct; dev->i_serial = desc_device->iSerialNumber; + tuh_descriptor_get_string_langid(daddr, _usbh_epbuf.ctrl, CFG_TUH_ENUMERATION_BUFSIZE, + process_enumeration, ENUM_GET_STRING_MANUFACTURER); + break; + } + + case ENUM_GET_STRING_MANUFACTURER: { + TU_ASSERT(dev,); + const tusb_desc_string_t* desc_langid = (tusb_desc_string_t const*) _usbh_epbuf.ctrl; + if (desc_langid->bLength >= 4) { + langid = tu_le16toh(desc_langid->utf16le[0]); + } + if (dev->i_manufacturer != 0) { + tuh_descriptor_get_string(daddr, dev->i_manufacturer, langid, _usbh_epbuf.ctrl, CFG_TUH_ENUMERATION_BUFSIZE, + process_enumeration, ENUM_GET_STRING_PRODUCT); + break; + } else { + TU_ATTR_FALLTHROUGH; + } + } + + case ENUM_GET_STRING_PRODUCT: { + TU_ASSERT(dev,); + if (state == ENUM_GET_STRING_PRODUCT) { + langid = tu_le16toh(xfer->setup->wIndex); // if not fall through, get langid from previous setup packet + } + if (dev->i_product != 0) { + tuh_descriptor_get_string(daddr, dev->i_product, 0x0409, _usbh_epbuf.ctrl, CFG_TUH_ENUMERATION_BUFSIZE, + process_enumeration, ENUM_GET_STRING_SERIAL); + break; + } else { + TU_ATTR_FALLTHROUGH; + } + } + + case ENUM_GET_STRING_SERIAL: { + TU_ASSERT(dev,); + if (state == ENUM_GET_STRING_SERIAL) { + langid = tu_le16toh(xfer->setup->wIndex); // if not fall through, get langid from previous setup packet + } + if (dev->i_serial != 0) { + tuh_descriptor_get_string(daddr, dev->i_serial, langid, _usbh_epbuf.ctrl, CFG_TUH_ENUMERATION_BUFSIZE, + process_enumeration, ENUM_GET_9BYTE_CONFIG_DESC); + break; + } else { + TU_ATTR_FALLTHROUGH; + } + } + + case ENUM_GET_9BYTE_CONFIG_DESC: { // Get 9-byte for total length uint8_t const config_idx = CONFIG_NUM - 1; TU_LOG_USBH("Get Configuration[0] Descriptor (9 bytes)\r\n"); @@ -1537,7 +1593,6 @@ static void process_enumeration(tuh_xfer_t* xfer) { case ENUM_CONFIG_DRIVER: { TU_LOG_USBH("Device configured\r\n"); - usbh_device_t* dev = get_device(daddr); TU_ASSERT(dev,); dev->configured = 1; diff --git a/src/host/usbh.h b/src/host/usbh.h index c8b137173..0fbe39743 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -265,6 +265,13 @@ bool tuh_descriptor_get_hid_report(uint8_t daddr, uint8_t itf_num, uint8_t desc_ bool tuh_descriptor_get_string(uint8_t daddr, uint8_t index, uint16_t language_id, void* buffer, uint16_t len, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +// Get language id string descriptor (control transfer) +TU_ATTR_ALWAYS_INLINE static inline +bool tuh_descriptor_get_string_langid(uint8_t daddr, void* buffer, uint16_t len, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return tuh_descriptor_get_string(daddr, 0, 0, buffer, len, complete_cb, user_data); +} + // Get manufacturer string descriptor (control transfer) // true on success, false if there is on-going control transfer or incorrect parameters bool tuh_descriptor_get_manufacturer_string(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len, @@ -304,6 +311,12 @@ uint8_t tuh_descriptor_get_hid_report_sync(uint8_t daddr, uint8_t itf_num, uint8 // return transfer result uint8_t tuh_descriptor_get_string_sync(uint8_t daddr, uint8_t index, uint16_t language_id, void* buffer, uint16_t len); +// Sync (blocking) version of tuh_descriptor_get_string_langid() +TU_ATTR_ALWAYS_INLINE static inline +uint8_t tuh_descriptor_get_string_langid_sync(uint8_t daddr, void* buffer, uint16_t len) { + return tuh_descriptor_get_string_sync(daddr, 0, 0, buffer, len); +} + // Sync (blocking) version of tuh_descriptor_get_manufacturer_string() // return transfer result uint8_t tuh_descriptor_get_manufacturer_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len); -- cgit v1.3.1 From ee234a84caf59d23395ed70f5e1c9d772e3f958b Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 6 Mar 2025 11:03:47 +0700 Subject: hack: force/overwrite endpoint mps to 64 for device that incorrectly report 512 bytes for bulk in fullspeed mode. --- src/class/midi/midi_host.c | 4 ++-- src/common/tusb_private.h | 2 +- src/device/usbd.c | 4 ++-- src/host/usbh.c | 2 +- src/tusb.c | 15 ++++++++++++--- 5 files changed, 18 insertions(+), 9 deletions(-) (limited to 'src/host') diff --git a/src/class/midi/midi_host.c b/src/class/midi/midi_host.c index 7f7d536d8..03144eb45 100644 --- a/src/class/midi/midi_host.c +++ b/src/class/midi/midi_host.c @@ -267,10 +267,10 @@ bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *d break; case TUSB_DESC_ENDPOINT: { - tusb_desc_endpoint_t const *p_ep = (tusb_desc_endpoint_t const *) p_desc; + const tusb_desc_endpoint_t *p_ep = (const tusb_desc_endpoint_t *) p_desc; p_desc = tu_desc_next(p_desc); // next to CS endpoint TU_VERIFY(p_desc < p_end && tu_desc_next(p_desc) <= p_end); - midi_desc_cs_endpoint_t const *p_csep = (midi_desc_cs_endpoint_t const *) p_desc; + const midi_desc_cs_endpoint_t *p_csep = (const midi_desc_cs_endpoint_t *) p_desc; TU_LOG_DRV(" Endpoint and CS_Endpoint descriptor %02x\r\n", p_ep->bEndpointAddress); if (tu_edpt_dir(p_ep->bEndpointAddress) == TUSB_DIR_OUT) { diff --git a/src/common/tusb_private.h b/src/common/tusb_private.h index 445882243..31aca8a31 100644 --- a/src/common/tusb_private.h +++ b/src/common/tusb_private.h @@ -67,7 +67,7 @@ typedef struct { //--------------------------------------------------------------------+ // Check if endpoint descriptor is valid per USB specs -bool tu_edpt_validate(tusb_desc_endpoint_t const * desc_ep, tusb_speed_t speed); +bool tu_edpt_validate(tusb_desc_endpoint_t const * desc_ep, tusb_speed_t speed, bool is_host); // Bind all endpoint of a interface descriptor to class driver void tu_edpt_bind_driver(uint8_t ep2drv[][2], tusb_desc_interface_t const* p_desc, uint16_t desc_len, uint8_t driver_id); diff --git a/src/device/usbd.c b/src/device/usbd.c index faf926855..fb5cec49d 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -1296,7 +1296,7 @@ bool usbd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_ep) { rhport = _usbd_rhport; TU_ASSERT(tu_edpt_number(desc_ep->bEndpointAddress) < CFG_TUD_ENDPPOINT_MAX); - TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t) _usbd_dev.speed)); + TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t) _usbd_dev.speed, false)); return dcd_edpt_open(rhport, desc_ep); } @@ -1497,7 +1497,7 @@ bool usbd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const* desc_ep) uint8_t const dir = tu_edpt_dir(desc_ep->bEndpointAddress); TU_ASSERT(epnum < CFG_TUD_ENDPPOINT_MAX); - TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t) _usbd_dev.speed)); + TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t) _usbd_dev.speed, false)); _usbd_dev.ep_status[epnum][dir].stalled = 0; _usbd_dev.ep_status[epnum][dir].busy = 0; diff --git a/src/host/usbh.c b/src/host/usbh.c index 609fe5000..c87f058cd 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -986,7 +986,7 @@ static bool usbh_edpt_control_open(uint8_t dev_addr, uint8_t max_packet_size) { } bool tuh_edpt_open(uint8_t dev_addr, tusb_desc_endpoint_t const* desc_ep) { - TU_ASSERT(tu_edpt_validate(desc_ep, tuh_speed_get(dev_addr))); + TU_ASSERT(tu_edpt_validate(desc_ep, tuh_speed_get(dev_addr), true)); return hcd_edpt_open(usbh_get_rhport(dev_addr), dev_addr, desc_ep); } diff --git a/src/tusb.c b/src/tusb.c index 9303e9bc4..13b89997c 100644 --- a/src/tusb.c +++ b/src/tusb.c @@ -205,7 +205,7 @@ bool tu_edpt_release(tu_edpt_state_t* ep_state, osal_mutex_t mutex) { return ret; } -bool tu_edpt_validate(tusb_desc_endpoint_t const* desc_ep, tusb_speed_t speed) { +bool tu_edpt_validate(tusb_desc_endpoint_t const* desc_ep, tusb_speed_t speed, bool is_host) { uint16_t const max_packet_size = tu_edpt_packet_size(desc_ep); TU_LOG2(" Open EP %02X with Size = %u\r\n", desc_ep->bEndpointAddress, max_packet_size); @@ -221,8 +221,17 @@ bool tu_edpt_validate(tusb_desc_endpoint_t const* desc_ep, tusb_speed_t speed) { // Bulk highspeed must be EXACTLY 512 TU_ASSERT(max_packet_size == 512); } else { - // TODO Bulk fullspeed can only be 8, 16, 32, 64 - TU_ASSERT(max_packet_size <= 64); + // Bulk fullspeed can only be 8, 16, 32, 64 + if (is_host && max_packet_size == 512) { + // HACK: while in host mode, some device incorrectly always report 512 regardless of link speed + // overwrite descriptor to force 64 + TU_LOG1(" WARN: EP max packet size is 512 in fullspeed, force to 64\r\n"); + tusb_desc_endpoint_t* hacked_ep = (tusb_desc_endpoint_t*) (uintptr_t) desc_ep; + hacked_ep->wMaxPacketSize = tu_htole16(64); + } else { + TU_ASSERT(max_packet_size == 8 || max_packet_size == 16 || + max_packet_size == 32 || max_packet_size == 64); + } } break; -- cgit v1.3.1 From e54753814befa26742fa8a9805f5b7beac32a963 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 21 Mar 2025 00:11:18 +0700 Subject: enable hil dual for metro m4 with max3421 --- examples/host/device_info/src/main.c | 2 +- src/host/usbh.h | 9 +++------ test/hil/tinyusb.json | 2 +- 3 files changed, 5 insertions(+), 8 deletions(-) (limited to 'src/host') diff --git a/examples/host/device_info/src/main.c b/examples/host/device_info/src/main.c index 775968c16..ac4c46a11 100644 --- a/examples/host/device_info/src/main.c +++ b/examples/host/device_info/src/main.c @@ -81,7 +81,7 @@ void init_freertos_task(void); //-------------------------------------------------------------------- // Main //-------------------------------------------------------------------- -void init_tinyusb(void) { +static void init_tinyusb(void) { // init host stack on configured roothub port tusb_rhport_init_t host_init = { .role = TUSB_ROLE_HOST, diff --git a/src/host/usbh.h b/src/host/usbh.h index 52b4f478c..36bb7c9b2 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -155,8 +155,7 @@ bool tuh_inited(void); void tuh_task_ext(uint32_t timeout_ms, bool in_isr); // Task function should be called in main/rtos loop -TU_ATTR_ALWAYS_INLINE static inline -void tuh_task(void) { +TU_ATTR_ALWAYS_INLINE static inline void tuh_task(void) { tuh_task_ext(UINT32_MAX, false); } @@ -197,16 +196,14 @@ bool tuh_mounted(uint8_t daddr); bool tuh_connected(uint8_t daddr); // Check if device is suspended -TU_ATTR_ALWAYS_INLINE static inline -bool tuh_suspended(uint8_t daddr) { +TU_ATTR_ALWAYS_INLINE static inline bool tuh_suspended(uint8_t daddr) { // TODO implement suspend & resume on host (void) daddr; return false; } // Check if device is ready to communicate with -TU_ATTR_ALWAYS_INLINE static inline -bool tuh_ready(uint8_t daddr) { +TU_ATTR_ALWAYS_INLINE static inline bool tuh_ready(uint8_t daddr) { return tuh_mounted(daddr) && !tuh_suspended(daddr); } diff --git a/test/hil/tinyusb.json b/test/hil/tinyusb.json index 7393226eb..c2bbdf5a3 100644 --- a/test/hil/tinyusb.json +++ b/test/hil/tinyusb.json @@ -60,7 +60,7 @@ "name": "metro_m4_express", "uid": "9995AD485337433231202020FF100A34", "tests": { - "device": true, "host": false, "dual": false, + "device": true, "host": false, "dual": true, "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2002130"}] }, "flasher": { -- cgit v1.3.1 From 9f541a3d961e1a75a9c6441cb3564c726292731b Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 24 Mar 2025 22:55:04 +0700 Subject: host: add tuh_enum_descriptor_device_cb() and tuh_enum_descriptor_configuration_cb() callback host: support device with multiple configurations --- src/host/usbh.c | 75 +++++++++++++++++++++++++++++++++------------------------ src/host/usbh.h | 7 ++++-- 2 files changed, 48 insertions(+), 34 deletions(-) (limited to 'src/host') diff --git a/src/host/usbh.c b/src/host/usbh.c index c87f058cd..308916c9b 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -52,21 +52,25 @@ enum { // Weak stubs: invoked if no strong implementation is available //--------------------------------------------------------------------+ TU_ATTR_WEAK bool hcd_deinit(uint8_t rhport) { - (void) rhport; - return false; + (void) rhport; return false; } TU_ATTR_WEAK bool hcd_configure(uint8_t rhport, uint32_t cfg_id, const void* cfg_param) { - (void) rhport; - (void) cfg_id; - (void) cfg_param; + (void) rhport; (void) cfg_id; (void) cfg_param; return false; } +TU_ATTR_WEAK void tuh_enum_descriptor_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device) { + (void) daddr; (void) desc_device; +} + +TU_ATTR_WEAK bool tuh_enum_descriptor_configuration_cb(uint8_t daddr, uint8_t cfg_index, const tusb_desc_configuration_t *desc_config) { + (void) daddr; (void) cfg_index; (void) desc_config; + return true; +} + TU_ATTR_WEAK void tuh_event_hook_cb(uint8_t rhport, uint32_t eventid, bool in_isr) { - (void) rhport; - (void) eventid; - (void) in_isr; + (void) rhport; (void) eventid; (void) in_isr; } TU_ATTR_WEAK bool hcd_dcache_clean(const void* addr, uint32_t data_size) { @@ -126,6 +130,7 @@ typedef struct { uint8_t i_manufacturer; uint8_t i_product; uint8_t i_serial; + uint8_t bNumConfigurations; // Configuration Descriptor // uint8_t interface_count; // bNumInterfaces alias @@ -230,7 +235,6 @@ static usbh_class_driver_t const usbh_class_drivers[] = { }; enum { BUILTIN_DRIVER_COUNT = TU_ARRAY_SIZE(usbh_class_drivers) }; -enum { CONFIG_NUM = 1 }; // default to use configuration 1 // Additional class drivers implemented by application tu_static usbh_class_driver_t const * _app_driver = NULL; @@ -1372,8 +1376,8 @@ enum { ENUM_CONFIG_DRIVER }; -static bool enum_request_set_addr(void); -static bool _parse_configuration_descriptor (uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg); +static bool enum_request_set_addr(tusb_desc_device_t const* desc_device); +static bool enum_parse_configuration_desc (uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg); static void enum_full_complete(void); // process device enumeration @@ -1489,7 +1493,7 @@ static void process_enumeration(tuh_xfer_t* xfer) { #endif case ENUM_SET_ADDR: - enum_request_set_addr(); + enum_request_set_addr((tusb_desc_device_t*) _usbh_epbuf.ctrl); break; case ENUM_GET_DEVICE_DESC: { @@ -1523,6 +1527,9 @@ static void process_enumeration(tuh_xfer_t* xfer) { dev->i_manufacturer = desc_device->iManufacturer; dev->i_product = desc_device->iProduct; dev->i_serial = desc_device->iSerialNumber; + dev->bNumConfigurations = desc_device->bNumConfigurations; + + tuh_enum_descriptor_device_cb(daddr, desc_device); // callback tuh_descriptor_get_string_langid(daddr, _usbh_epbuf.ctrl, CFG_TUH_ENUMERATION_BUFSIZE, process_enumeration, ENUM_GET_STRING_MANUFACTURER); @@ -1574,8 +1581,8 @@ static void process_enumeration(tuh_xfer_t* xfer) { case ENUM_GET_9BYTE_CONFIG_DESC: { // Get 9-byte for total length - uint8_t const config_idx = CONFIG_NUM - 1; - TU_LOG_USBH("Get Configuration[0] Descriptor (9 bytes)\r\n"); + uint8_t const config_idx = 0; + TU_LOG_USBH("Get Configuration[%u] Descriptor (9 bytes)\r\n", config_idx); TU_ASSERT(tuh_descriptor_get_configuration(daddr, config_idx, _usbh_epbuf.ctrl, 9, process_enumeration, ENUM_GET_FULL_CONFIG_DESC),); break; @@ -1585,25 +1592,32 @@ static void process_enumeration(tuh_xfer_t* xfer) { uint8_t const* desc_config = _usbh_epbuf.ctrl; // Use offsetof to avoid pointer to the odd/misaligned address - uint16_t const total_len = tu_le16toh( - tu_unaligned_read16(desc_config + offsetof(tusb_desc_configuration_t, wTotalLength))); + uint16_t const total_len = tu_le16toh(tu_unaligned_read16(desc_config + offsetof(tusb_desc_configuration_t, wTotalLength))); // TODO not enough buffer to hold configuration descriptor TU_ASSERT(total_len <= CFG_TUH_ENUMERATION_BUFSIZE,); // Get full configuration descriptor - uint8_t const config_idx = CONFIG_NUM - 1; - TU_LOG_USBH("Get Configuration[0] Descriptor\r\n"); + uint8_t const config_idx = (uint8_t) tu_le16toh(xfer->setup->wIndex); + TU_LOG_USBH("Get Configuration[%u] Descriptor\r\n", config_idx); TU_ASSERT(tuh_descriptor_get_configuration(daddr, config_idx, _usbh_epbuf.ctrl, total_len, process_enumeration, ENUM_SET_CONFIG),); break; } - case ENUM_SET_CONFIG: - // tuh_desc_configuration_cb(daddr, CONFIG_NUM-1, (const tusb_desc_configuration_t*) _usbh_epbuf.ctrl); - - TU_ASSERT(tuh_configuration_set(daddr, CONFIG_NUM, process_enumeration, ENUM_CONFIG_DRIVER),); + case ENUM_SET_CONFIG: { + uint8_t config_idx = (uint8_t) tu_le16toh(xfer->setup->wIndex); + if (tuh_enum_descriptor_configuration_cb(daddr, config_idx, (const tusb_desc_configuration_t*) _usbh_epbuf.ctrl)) { + TU_ASSERT(tuh_configuration_set(daddr, config_idx+1, process_enumeration, ENUM_CONFIG_DRIVER),); + } else { + config_idx++; + TU_ASSERT(config_idx < dev->bNumConfigurations,); + TU_LOG_USBH("Get Configuration[%u] Descriptor (9 bytes)\r\n", config_idx); + TU_ASSERT(tuh_descriptor_get_configuration(daddr, config_idx, _usbh_epbuf.ctrl, 9, + process_enumeration, ENUM_GET_FULL_CONFIG_DESC),); + } break; + } case ENUM_CONFIG_DRIVER: { TU_LOG_USBH("Device configured\r\n"); @@ -1613,7 +1627,7 @@ static void process_enumeration(tuh_xfer_t* xfer) { // Parse configuration & set up drivers // driver_open() must not make any usb transfer - TU_ASSERT(_parse_configuration_descriptor(daddr, (tusb_desc_configuration_t*) _usbh_epbuf.ctrl),); + TU_ASSERT(enum_parse_configuration_desc(daddr, (tusb_desc_configuration_t*) _usbh_epbuf.ctrl),); // Start the Set Configuration process for interfaces (itf = TUSB_INDEX_INVALID_8) // Since driver can perform control transfer within its set_config, this is done asynchronously. @@ -1624,14 +1638,11 @@ static void process_enumeration(tuh_xfer_t* xfer) { } default: - // stop enumeration if unknown state - enum_full_complete(); + enum_full_complete(); // stop enumeration if unknown state break; } } - - static bool enum_new_device(hcd_event_t* event) { _dev0.rhport = event->rhport; _dev0.hub_addr = event->connection.hub_addr; @@ -1701,9 +1712,7 @@ static uint8_t get_new_address(bool is_hub) { return 0; // invalid address } -static bool enum_request_set_addr(void) { - tusb_desc_device_t const* desc_device = (tusb_desc_device_t const*) _usbh_epbuf.ctrl; - +static bool enum_request_set_addr(tusb_desc_device_t const* desc_device) { // Get new address uint8_t const new_addr = get_new_address(desc_device->bDeviceClass == TUSB_CLASS_HUB); TU_ASSERT(new_addr != 0); @@ -1741,7 +1750,7 @@ static bool enum_request_set_addr(void) { return true; } -static bool _parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg) { +static bool enum_parse_configuration_desc(uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg) { usbh_device_t* dev = get_device(dev_addr); uint16_t const total_len = tu_le16toh(desc_cfg->wTotalLength); uint8_t const* desc_end = ((uint8_t const*) desc_cfg) + total_len; @@ -1858,7 +1867,9 @@ void usbh_driver_set_config_complete(uint8_t dev_addr, uint8_t itf_num) { TU_LOG_USBH("HUB address = %u is mounted\r\n", dev_addr); }else { // Invoke callback if available - if (tuh_mount_cb) tuh_mount_cb(dev_addr); + if (tuh_mount_cb) { + tuh_mount_cb(dev_addr); + } } } } diff --git a/src/host/usbh.h b/src/host/usbh.h index 36bb7c9b2..d95bb9b57 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -100,10 +100,13 @@ typedef union { //--------------------------------------------------------------------+ // Invoked when enumeration get device descriptor -// TU_ATTR_WEAK void tuh_descriptor_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device); +// Device is not ready to communicate yet, application can copy the descriptor if needed +void tuh_enum_descriptor_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device); // Invoked when enumeration get configuration descriptor -// TU_ATTR_WEAK void tuh_desc_configuration_cb(uint8_t daddr, uint8_t cfg_index, const tusb_desc_configuration_t *desc_config); +// For multi-configuration device return false to skip, true to proceed with this configuration (may not be implemented yet) +// Device is not ready to communicate yet, application can copy the descriptor if needed +bool tuh_enum_descriptor_configuration_cb(uint8_t daddr, uint8_t cfg_index, const tusb_desc_configuration_t *desc_config); // Invoked when a device is mounted (configured) TU_ATTR_WEAK void tuh_mount_cb (uint8_t daddr); -- cgit v1.3.1 From 65e01fff2e7ab5302baa45bdd81a1d774e269452 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Mar 2025 16:15:58 +0700 Subject: add tuh_edpt_close() API, it will abort any pending transfer implement hcd_edpt_close() for pio-usb and max3421e, also move max3421e api into its own header. --- examples/host/bare_api/src/main.c | 254 +++++++++++-------------- src/host/hcd.h | 3 + src/host/usbh.c | 6 + src/host/usbh.h | 7 + src/portable/analog/max3421/hcd_max3421.c | 40 ++-- src/portable/analog/max3421/hcd_max3421.h | 63 ++++++ src/portable/raspberrypi/pio_usb/hcd_pio_usb.c | 5 + tools/get_deps.py | 4 +- 8 files changed, 218 insertions(+), 164 deletions(-) create mode 100644 src/portable/analog/max3421/hcd_max3421.h (limited to 'src/host') diff --git a/examples/host/bare_api/src/main.c b/examples/host/bare_api/src/main.c index f582f4f5a..0c76ff0c9 100644 --- a/examples/host/bare_api/src/main.c +++ b/examples/host/bare_api/src/main.c @@ -55,16 +55,15 @@ uint8_t* get_hid_buf(uint8_t daddr); void free_hid_buf(uint8_t daddr); /*------------- MAIN -------------*/ -int main(void) -{ +int main(void) { board_init(); printf("TinyUSB Bare API Example\r\n"); // init host stack on configured roothub port tusb_rhport_init_t host_init = { - .role = TUSB_ROLE_HOST, - .speed = TUSB_SPEED_AUTO + .role = TUSB_ROLE_HOST, + .speed = TUSB_SPEED_AUTO }; tusb_init(BOARD_TUH_RHPORT, &host_init); @@ -72,8 +71,7 @@ int main(void) board_init_after_tusb(); } - while (1) - { + while (1) { // tinyusb host task tuh_task(); led_blinking_task(); @@ -85,8 +83,7 @@ int main(void) /*------------- TinyUSB Callbacks -------------*/ // Invoked when device is mounted (configured) -void tuh_mount_cb (uint8_t daddr) -{ +void tuh_mount_cb(uint8_t daddr) { printf("Device attached, address = %d\r\n", daddr); // Get Device Descriptor @@ -95,8 +92,7 @@ void tuh_mount_cb (uint8_t daddr) } /// Invoked when device is unmounted (bus reset/unplugged) -void tuh_umount_cb(uint8_t daddr) -{ +void tuh_umount_cb(uint8_t daddr) { printf("Device removed, address = %d\r\n", daddr); free_hid_buf(daddr); } @@ -104,11 +100,8 @@ void tuh_umount_cb(uint8_t daddr) //--------------------------------------------------------------------+ // Device Descriptor //--------------------------------------------------------------------+ - -void print_device_descriptor(tuh_xfer_t* xfer) -{ - if ( XFER_RESULT_SUCCESS != xfer->result ) - { +void print_device_descriptor(tuh_xfer_t *xfer) { + if (XFER_RESULT_SUCCESS != xfer->result) { printf("Failed to get device descriptor\r\n"); return; } @@ -131,33 +124,29 @@ void print_device_descriptor(tuh_xfer_t* xfer) // Get String descriptor using Sync API uint16_t temp_buf[128]; - printf(" iManufacturer %u " , desc_device.iManufacturer); - if (XFER_RESULT_SUCCESS == tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf)) ) - { + printf(" iManufacturer %u ", desc_device.iManufacturer); + if (XFER_RESULT_SUCCESS == tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) { print_utf16(temp_buf, TU_ARRAY_SIZE(temp_buf)); } printf("\r\n"); - printf(" iProduct %u " , desc_device.iProduct); - if (XFER_RESULT_SUCCESS == tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) - { + printf(" iProduct %u ", desc_device.iProduct); + if (XFER_RESULT_SUCCESS == tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) { print_utf16(temp_buf, TU_ARRAY_SIZE(temp_buf)); } printf("\r\n"); - printf(" iSerialNumber %u " , desc_device.iSerialNumber); - if (XFER_RESULT_SUCCESS == tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) - { + printf(" iSerialNumber %u ", desc_device.iSerialNumber); + if (XFER_RESULT_SUCCESS == tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) { print_utf16(temp_buf, TU_ARRAY_SIZE(temp_buf)); } printf("\r\n"); - printf(" bNumConfigurations %u\r\n" , desc_device.bNumConfigurations); + printf(" bNumConfigurations %u\r\n", desc_device.bNumConfigurations); // Get configuration descriptor with sync API - if (XFER_RESULT_SUCCESS == tuh_descriptor_get_configuration_sync(daddr, 0, temp_buf, sizeof(temp_buf))) - { - parse_config_descriptor(daddr, (tusb_desc_configuration_t*) temp_buf); + if (XFER_RESULT_SUCCESS == tuh_descriptor_get_configuration_sync(daddr, 0, temp_buf, sizeof(temp_buf))) { + parse_config_descriptor(daddr, (tusb_desc_configuration_t *) temp_buf); } } @@ -171,37 +160,33 @@ uint16_t count_interface_total_len(tusb_desc_interface_t const* desc_itf, uint8_ void open_hid_interface(uint8_t daddr, tusb_desc_interface_t const *desc_itf, uint16_t max_len); // simple configuration parser to open and listen to HID Endpoint IN -void parse_config_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg) -{ - uint8_t const* desc_end = ((uint8_t const*) desc_cfg) + tu_le16toh(desc_cfg->wTotalLength); - uint8_t const* p_desc = tu_desc_next(desc_cfg); +void parse_config_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const *desc_cfg) { + uint8_t const *desc_end = ((uint8_t const *) desc_cfg) + tu_le16toh(desc_cfg->wTotalLength); + uint8_t const *p_desc = tu_desc_next(desc_cfg); // parse each interfaces - while( p_desc < desc_end ) - { + while (p_desc < desc_end) { uint8_t assoc_itf_count = 1; // Class will always starts with Interface Association (if any) and then Interface descriptor - if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) ) - { - tusb_desc_interface_assoc_t const * desc_iad = (tusb_desc_interface_assoc_t const *) p_desc; + if (TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc)) { + tusb_desc_interface_assoc_t const *desc_iad = (tusb_desc_interface_assoc_t const *) p_desc; assoc_itf_count = desc_iad->bInterfaceCount; - p_desc = tu_desc_next(p_desc); // next to Interface + p_desc = tu_desc_next(p_desc);// next to Interface } // must be interface from now - if( TUSB_DESC_INTERFACE != tu_desc_type(p_desc) ) return; - tusb_desc_interface_t const* desc_itf = (tusb_desc_interface_t const*) p_desc; + if (TUSB_DESC_INTERFACE != tu_desc_type(p_desc)) { return; } + tusb_desc_interface_t const *desc_itf = (tusb_desc_interface_t const *) p_desc; - uint16_t const drv_len = count_interface_total_len(desc_itf, assoc_itf_count, (uint16_t) (desc_end-p_desc)); + uint16_t const drv_len = count_interface_total_len(desc_itf, assoc_itf_count, (uint16_t) (desc_end - p_desc)); // probably corrupted descriptor - if(drv_len < sizeof(tusb_desc_interface_t)) return; + if (drv_len < sizeof(tusb_desc_interface_t)) { return; } // only open and listen to HID endpoint IN - if (desc_itf->bInterfaceClass == TUSB_CLASS_HID) - { + if (desc_itf->bInterfaceClass == TUSB_CLASS_HID) { open_hid_interface(dev_addr, desc_itf, drv_len); } @@ -210,25 +195,21 @@ void parse_config_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const* } } -uint16_t count_interface_total_len(tusb_desc_interface_t const* desc_itf, uint8_t itf_count, uint16_t max_len) -{ - uint8_t const* p_desc = (uint8_t const*) desc_itf; +uint16_t count_interface_total_len(tusb_desc_interface_t const *desc_itf, uint8_t itf_count, uint16_t max_len) { + uint8_t const *p_desc = (uint8_t const *) desc_itf; uint16_t len = 0; - while (itf_count--) - { + while (itf_count--) { // Next on interface desc len += tu_desc_len(desc_itf); p_desc = tu_desc_next(p_desc); - while (len < max_len) - { + while (len < max_len) { // return on IAD regardless of itf count - if ( tu_desc_type(p_desc) == TUSB_DESC_INTERFACE_ASSOCIATION ) return len; + if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE_ASSOCIATION) { return len; } - if ( (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE) && - ((tusb_desc_interface_t const*) p_desc)->bAlternateSetting == 0 ) - { + if ((tu_desc_type(p_desc) == TUSB_DESC_INTERFACE) && + ((tusb_desc_interface_t const *) p_desc)->bAlternateSetting == 0) { break; } @@ -246,46 +227,45 @@ uint16_t count_interface_total_len(tusb_desc_interface_t const* desc_itf, uint8_ void hid_report_received(tuh_xfer_t* xfer); -void open_hid_interface(uint8_t daddr, tusb_desc_interface_t const *desc_itf, uint16_t max_len) -{ +void open_hid_interface(uint8_t daddr, tusb_desc_interface_t const *desc_itf, uint16_t max_len) { // len = interface + hid + n*endpoints uint16_t const drv_len = (uint16_t) (sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + desc_itf->bNumEndpoints * sizeof(tusb_desc_endpoint_t)); // corrupted descriptor - if (max_len < drv_len) return; + if (max_len < drv_len) { return; } uint8_t const *p_desc = (uint8_t const *) desc_itf; // HID descriptor p_desc = tu_desc_next(p_desc); tusb_hid_descriptor_hid_t const *desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; - if(HID_DESC_TYPE_HID != desc_hid->bDescriptorType) return; + if (HID_DESC_TYPE_HID != desc_hid->bDescriptorType) { return; } // Endpoint descriptor p_desc = tu_desc_next(p_desc); - tusb_desc_endpoint_t const * desc_ep = (tusb_desc_endpoint_t const *) p_desc; - - for(int i = 0; i < desc_itf->bNumEndpoints; i++) - { - if (TUSB_DESC_ENDPOINT != desc_ep->bDescriptorType) return; - - if(tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) - { - // skip if failed to open endpoint - if ( ! tuh_edpt_open(daddr, desc_ep) ) return; - - uint8_t* buf = get_hid_buf(daddr); - if (!buf) return; // out of memory - - tuh_xfer_t xfer = - { - .daddr = daddr, - .ep_addr = desc_ep->bEndpointAddress, - .buflen = 64, - .buffer = buf, - .complete_cb = hid_report_received, - .user_data = (uintptr_t) buf, // since buffer is not available in callback, use user data to store the buffer + tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) p_desc; + + for (int i = 0; i < desc_itf->bNumEndpoints; i++) { + if (TUSB_DESC_ENDPOINT != desc_ep->bDescriptorType) { return; } + + if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) { + if (!tuh_edpt_open(daddr, desc_ep)) { + return; // skip if failed to open endpoint + } + + uint8_t *buf = get_hid_buf(daddr); + if (!buf) { + return;// out of memory + } + + tuh_xfer_t xfer = { + .daddr = daddr, + .ep_addr = desc_ep->bEndpointAddress, + .buflen = 64, + .buffer = buf, + .complete_cb = hid_report_received, + .user_data = (uintptr_t) buf,// since buffer is not available in callback, use user data to store the buffer }; // submit transfer for this EP @@ -299,18 +279,17 @@ void open_hid_interface(uint8_t daddr, tusb_desc_interface_t const *desc_itf, ui } } -void hid_report_received(tuh_xfer_t* xfer) -{ +void hid_report_received(tuh_xfer_t *xfer) { // Note: not all field in xfer is available for use (i.e filled by tinyusb stack) in callback to save sram // For instance, xfer->buffer is NULL. We have used user_data to store buffer when submitted callback - uint8_t* buf = (uint8_t*) xfer->user_data; + uint8_t *buf = (uint8_t *) xfer->user_data; - if (xfer->result == XFER_RESULT_SUCCESS) - { + if (xfer->result == XFER_RESULT_SUCCESS) { printf("[dev %u: ep %02x] HID Report:", xfer->daddr, xfer->ep_addr); - for(uint32_t i=0; iactual_len; i++) - { - if (i%16 == 0) printf("\r\n "); + for (uint32_t i = 0; i < xfer->actual_len; i++) { + if (i % 16 == 0) { + printf("\r\n "); + } printf("%02X ", buf[i]); } printf("\r\n"); @@ -329,12 +308,9 @@ void hid_report_received(tuh_xfer_t* xfer) //--------------------------------------------------------------------+ // get an buffer from pool -uint8_t* get_hid_buf(uint8_t daddr) -{ - for(size_t i=0; i> 6 & 0x1F)); - *utf8++ = (uint8_t)(0x80 | (chr >> 0 & 0x3F)); - } else { - // TODO: Verify surrogate. - *utf8++ = (uint8_t)(0xE0 | (chr >> 12 & 0x0F)); - *utf8++ = (uint8_t)(0x80 | (chr >> 6 & 0x3F)); - *utf8++ = (uint8_t)(0x80 | (chr >> 0 & 0x3F)); - } - // TODO: Handle UTF-16 code points that take two entries. + // TODO: Check for runover. + (void) utf8_len; + // Get the UTF-16 length out of the data itself. + + for (size_t i = 0; i < utf16_len; i++) { + uint16_t chr = utf16[i]; + if (chr < 0x80) { + *utf8++ = chr & 0xffu; + } else if (chr < 0x800) { + *utf8++ = (uint8_t) (0xC0 | (chr >> 6 & 0x1F)); + *utf8++ = (uint8_t) (0x80 | (chr >> 0 & 0x3F)); + } else { + // TODO: Verify surrogate. + *utf8++ = (uint8_t) (0xE0 | (chr >> 12 & 0x0F)); + *utf8++ = (uint8_t) (0x80 | (chr >> 6 & 0x3F)); + *utf8++ = (uint8_t) (0x80 | (chr >> 0 & 0x3F)); } + // TODO: Handle UTF-16 code points that take two entries. + } } // Count how many bytes a utf-16-le encoded string will take in utf-8. static int _count_utf8_bytes(const uint16_t *buf, size_t len) { - size_t total_bytes = 0; - for (size_t i = 0; i < len; i++) { - uint16_t chr = buf[i]; - if (chr < 0x80) { - total_bytes += 1; - } else if (chr < 0x800) { - total_bytes += 2; - } else { - total_bytes += 3; - } - // TODO: Handle UTF-16 code points that take two entries. + size_t total_bytes = 0; + for (size_t i = 0; i < len; i++) { + uint16_t chr = buf[i]; + if (chr < 0x80) { + total_bytes += 1; + } else if (chr < 0x800) { + total_bytes += 2; + } else { + total_bytes += 3; } - return (int) total_bytes; + // TODO: Handle UTF-16 code points that take two entries. + } + return (int) total_bytes; } static void print_utf16(uint16_t *temp_buf, size_t buf_len) { - if ((temp_buf[0] & 0xff) == 0) return; // empty - size_t utf16_len = ((temp_buf[0] & 0xff) - 2) / sizeof(uint16_t); - size_t utf8_len = (size_t) _count_utf8_bytes(temp_buf + 1, utf16_len); - _convert_utf16le_to_utf8(temp_buf + 1, utf16_len, (uint8_t *) temp_buf, sizeof(uint16_t) * buf_len); - ((uint8_t*) temp_buf)[utf8_len] = '\0'; + if ((temp_buf[0] & 0xff) == 0) return;// empty + size_t utf16_len = ((temp_buf[0] & 0xff) - 2) / sizeof(uint16_t); + size_t utf8_len = (size_t) _count_utf8_bytes(temp_buf + 1, utf16_len); + _convert_utf16le_to_utf8(temp_buf + 1, utf16_len, (uint8_t *) temp_buf, sizeof(uint16_t) * buf_len); + ((uint8_t *) temp_buf)[utf8_len] = '\0'; - printf("%s", (char*)temp_buf); + printf("%s", (char *) temp_buf); } diff --git a/src/host/hcd.h b/src/host/hcd.h index 56b6fdb5d..aa9e9cf3b 100644 --- a/src/host/hcd.h +++ b/src/host/hcd.h @@ -165,6 +165,9 @@ void hcd_device_close(uint8_t rhport, uint8_t dev_addr); // Open an endpoint bool hcd_edpt_open(uint8_t rhport, uint8_t daddr, tusb_desc_endpoint_t const * ep_desc); +// Close an endpoint +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr); + // Submit a transfer, when complete hcd_event_xfer_complete() must be invoked bool hcd_edpt_xfer(uint8_t rhport, uint8_t daddr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen); diff --git a/src/host/usbh.c b/src/host/usbh.c index 308916c9b..5925a7be0 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -994,6 +994,12 @@ bool tuh_edpt_open(uint8_t dev_addr, tusb_desc_endpoint_t const* desc_ep) { return hcd_edpt_open(usbh_get_rhport(dev_addr), dev_addr, desc_ep); } +bool tuh_edpt_close(uint8_t daddr, uint8_t ep_addr) { + TU_VERIFY(0 != tu_edpt_number(ep_addr)); // cannot close EP0 + tuh_edpt_abort_xfer(daddr, ep_addr); // abort any pending transfer + return hcd_edpt_close(usbh_get_rhport(daddr), daddr, ep_addr); +} + bool usbh_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) { usbh_device_t* dev = get_device(dev_addr); TU_VERIFY(dev); diff --git a/src/host/usbh.h b/src/host/usbh.h index d95bb9b57..4829a8183 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -33,6 +33,10 @@ #include "common/tusb_common.h" +#if CFG_TUH_MAX3421 +#include "portable/analog/max3421/hcd_max3421.h" +#endif + //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ @@ -227,6 +231,9 @@ bool tuh_edpt_xfer(tuh_xfer_t* xfer); // Open a non-control endpoint bool tuh_edpt_open(uint8_t daddr, tusb_desc_endpoint_t const * desc_ep); +// Close a non-control endpoint, it will abort any pending transfer +bool tuh_edpt_close(uint8_t daddr, uint8_t ep_addr); + // Abort a queued transfer. Note: it can only abort transfer that has not been started // Return true if a queued transfer is aborted, false if there is no transfer to abort bool tuh_edpt_abort_xfer(uint8_t daddr, uint8_t ep_addr); diff --git a/src/portable/analog/max3421/hcd_max3421.c b/src/portable/analog/max3421/hcd_max3421.c index c5e924266..3fbf950a4 100644 --- a/src/portable/analog/max3421/hcd_max3421.c +++ b/src/portable/analog/max3421/hcd_max3421.c @@ -252,28 +252,6 @@ static tuh_configure_max3421_t _tuh_cfg = { .pinctl = 0, // default: negative edge interrupt }; -//--------------------------------------------------------------------+ -// API: SPI transfer with MAX3421E -// - spi_cs_api(), spi_xfer_api(), int_api(): must be implemented by application -// - reg_read(), reg_write(): is implemented by this driver, can be used by application -//--------------------------------------------------------------------+ - -// API to control MAX3421 SPI CS -extern void tuh_max3421_spi_cs_api(uint8_t rhport, bool active); - -// API to transfer data with MAX3421 SPI -// Either tx_buf or rx_buf can be NULL, which means transfer is write or read only -extern bool tuh_max3421_spi_xfer_api(uint8_t rhport, uint8_t const* tx_buf, uint8_t* rx_buf, size_t xfer_bytes); - -// API to enable/disable MAX3421 INTR pin interrupt -extern void tuh_max3421_int_api(uint8_t rhport, bool enabled); - -// API to read MAX3421's register. Implemented by TinyUSB -uint8_t tuh_max3421_reg_read(uint8_t rhport, uint8_t reg, bool in_isr); - -// API to write MAX3421's register. Implemented by TinyUSB -bool tuh_max3421_reg_write(uint8_t rhport, uint8_t reg, uint8_t data, bool in_isr); - //--------------------------------------------------------------------+ // SPI Commands and Helper //--------------------------------------------------------------------+ @@ -632,6 +610,9 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t daddr, tusb_desc_endpoint_t const * e if (daddr == 0 && ep_num == 0) { ep = &_hcd_data.ep[0]; }else { + if (NULL != find_ep_not_addr0(daddr, ep_num, ep_dir)) { + return false; // endpoint already opened + } ep = allocate_ep(); TU_ASSERT(ep); ep->daddr = daddr; @@ -645,6 +626,21 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t daddr, tusb_desc_endpoint_t const * e return true; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; + uint8_t const ep_num = tu_edpt_number(ep_addr); + tusb_dir_t const ep_dir = tu_edpt_dir(ep_addr); + max3421_ep_t * ep = find_ep_not_addr0(daddr, ep_num, ep_dir); + + if (!ep) { + return false; // not opened + } + + tu_memclr(ep, sizeof(max3421_ep_t)); + + return true; +} + /* The microcontroller repeatedly writes the SNDFIFO register R2 to load the FIFO with up to 64 data bytes. * Then the microcontroller writes the SNDBC register, which this does three things: * 1. Tells the MAX3421E SIE (Serial Interface Engine) how many bytes in the FIFO to send. diff --git a/src/portable/analog/max3421/hcd_max3421.h b/src/portable/analog/max3421/hcd_max3421.h new file mode 100644 index 000000000..4631fa21a --- /dev/null +++ b/src/portable/analog/max3421/hcd_max3421.h @@ -0,0 +1,63 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * 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. + * + * 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. + * + * This file is part of the TinyUSB stack. + */ +#ifndef TUSB_HCD_MAX3421_H +#define TUSB_HCD_MAX3421_H + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// SPI transfer API with MAX3421E are implemented by application +// - spi_cs_api(), spi_xfer_api(), int_api() +//--------------------------------------------------------------------+ + +// API to control MAX3421 SPI CS +extern void tuh_max3421_spi_cs_api(uint8_t rhport, bool active); + +// API to transfer data with MAX3421 SPI +// Either tx_buf or rx_buf can be NULL, which means transfer is write or read only +extern bool tuh_max3421_spi_xfer_api(uint8_t rhport, uint8_t const* tx_buf, uint8_t* rx_buf, size_t xfer_bytes); + +// API to enable/disable MAX3421 INTR pin interrupt +extern void tuh_max3421_int_api(uint8_t rhport, bool enabled); + +//--------------------------------------------------------------------+ +// API for read/write MAX3421 registers +// are implemented by this driver, can be used by application +//--------------------------------------------------------------------+ + +// API to read MAX3421's register. Implemented by TinyUSB +uint8_t tuh_max3421_reg_read(uint8_t rhport, uint8_t reg, bool in_isr); + +// API to write MAX3421's register. Implemented by TinyUSB +bool tuh_max3421_reg_write(uint8_t rhport, uint8_t reg, uint8_t data, bool in_isr); + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c b/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c index 6422afff1..225a44dcf 100644 --- a/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c +++ b/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c @@ -122,6 +122,11 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const return pio_usb_host_endpoint_open(pio_rhport, dev_addr, (uint8_t const *) desc_ep, need_pre); } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + uint8_t const pio_rhport = RHPORT_PIO(rhport); + return pio_usb_host_endpoint_close(pio_rhport, daddr, ep_addr); +} + bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *buffer, uint16_t buflen) { uint8_t const pio_rhport = RHPORT_PIO(rhport); return pio_usb_host_endpoint_transfer(pio_rhport, dev_addr, ep_addr, buffer, buflen); diff --git a/tools/get_deps.py b/tools/get_deps.py index 3f529bd7e..ba9dc23ce 100755 --- a/tools/get_deps.py +++ b/tools/get_deps.py @@ -58,8 +58,8 @@ deps_optional = { 'hw/mcu/nxp/mcux-sdk': ['https://github.com/hathach/mcux-sdk.git', '144f1eb7ea8c06512e12f12b27383601c0272410', 'kinetis_k kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx imxrt'], - 'hw/mcu/raspberry_pi/Pico-PIO-USB': ['https://github.com/sekigon-gonnoc/Pico-PIO-USB.git', - '0ca3657d55ea20e7fa4483bbd21ce951bc1d6fa5', + 'hw/mcu/raspberry_pi/Pico-PIO-USB': ['https://github.com/hathach/Pico-PIO-USB.git', + '810653f66adadba3e0e4b4b56d5167ac4f7fdbf7', 'rp2040'], 'hw/mcu/renesas/fsp': ['https://github.com/renesas/fsp.git', 'edcc97d684b6f716728a60d7a6fea049d9870bd6', -- cgit v1.3.1 From 901ce2ad93b39c08e8e6b7e5b3f4dbd0b9df879e Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 26 Mar 2025 21:13:01 +0700 Subject: hcd/ehci: hcd_edpt_open() return false if ep is already opened. implement hcd_edpt_close() --- hw/bsp/imxrt/family.c | 4 +- src/device/usbd.c | 9 +- src/host/usbh.c | 2 +- src/portable/ehci/ehci.c | 259 ++++++++++++++++++++------------------ src/portable/ehci/ehci.h | 314 +++++++++++++++++++++++------------------------ test/hil/hil_test.py | 3 +- 6 files changed, 301 insertions(+), 290 deletions(-) (limited to 'src/host') diff --git a/hw/bsp/imxrt/family.c b/hw/bsp/imxrt/family.c index 7b89cc76d..7e4734a66 100644 --- a/hw/bsp/imxrt/family.c +++ b/hw/bsp/imxrt/family.c @@ -61,7 +61,7 @@ - Define CFG_TUSB_MEM_SECTION=__attribute__((section("NonCacheable"))) */ -static void BOARD_ConfigMPU(void); +// static void BOARD_ConfigMPU(void); // needed by fsl_flexspi_nor_boot TU_ATTR_USED const uint8_t dcd_data[] = {0x00}; @@ -456,7 +456,7 @@ static void BOARD_ConfigMPU(void) { #elif __CORTEX_M == 4 -void BOARD_ConfigMPU(void) { +static void BOARD_ConfigMPU(void) { #if defined(__CC_ARM) || defined(__ARMCC_VERSION) extern uint32_t Image$$RW_m_ncache$$Base[]; /* RW_m_ncache_unused is a auxiliary region which is used to get the whole size of noncache section */ diff --git a/src/device/usbd.c b/src/device/usbd.c index fb5cec49d..9c381d5e0 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -561,8 +561,7 @@ static void usbd_reset(uint8_t rhport) { } bool tud_task_event_ready(void) { - // Skip if stack is not initialized - if (!tud_inited()) return false; + TU_VERIFY(tud_inited()); // Skip if stack is not initialized return !osal_queue_empty(_usbd_q); } @@ -684,7 +683,9 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) { case USBD_EVENT_FUNC_CALL: TU_LOG_USBD("\r\n"); - if (event.func_call.func) event.func_call.func(event.func_call.param); + if (event.func_call.func) { + event.func_call.func(event.func_call.param); + } break; case DCD_EVENT_SOF: @@ -701,7 +702,7 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) { #if CFG_TUSB_OS != OPT_OS_NONE && CFG_TUSB_OS != OPT_OS_PICO // return if there is no more events, for application to run other background - if (osal_queue_empty(_usbd_q)) return; + if (osal_queue_empty(_usbd_q)) { return; } #endif } } diff --git a/src/host/usbh.c b/src/host/usbh.c index 5925a7be0..e60db53da 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -520,7 +520,7 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { // Loop until there is no more events in the queue while (1) { hcd_event_t event; - if (!osal_queue_receive(_usbh_q, &event, timeout_ms)) return; + if (!osal_queue_receive(_usbh_q, &event, timeout_ms)) { return; } switch (event.event_id) { case HCD_EVENT_DEVICE_ATTACH: diff --git a/src/portable/ehci/ehci.c b/src/portable/ehci/ehci.c index 01bbf62bf..292a352fb 100644 --- a/src/portable/ehci/ehci.c +++ b/src/portable/ehci/ehci.c @@ -62,8 +62,7 @@ #define QHD_MAX (CFG_TUH_DEVICE_MAX*CFG_TUH_ENDPOINT_MAX + CFG_TUH_HUB) #define QTD_MAX QHD_MAX -typedef struct -{ +typedef struct { ehci_link_t period_framelist[FRAMELIST_SIZE]; // TODO only implement 1 ms & 2 ms & 4 ms, 8 ms (framelist) @@ -139,6 +138,12 @@ static ehci_qhd_t* qhd_get_from_addr (uint8_t dev_addr, uint8_t ep_addr); static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc); static void qhd_attach_qtd(ehci_qhd_t *qhd, ehci_qtd_t *qtd); static void qhd_remove_qtd(ehci_qhd_t *qhd); +TU_ATTR_ALWAYS_INLINE static inline bool qhd_is_periodic(ehci_qhd_t const *qhd) { + return qhd->int_smask != 0; +} +TU_ATTR_ALWAYS_INLINE static inline uint8_t qhd_ep_addr(ehci_qhd_t const *qhd) { + return tu_edpt_addr(qhd->ep_number, qhd->pid); +} TU_ATTR_ALWAYS_INLINE static inline ehci_qtd_t* qtd_control(uint8_t dev_addr); TU_ATTR_ALWAYS_INLINE static inline ehci_qtd_t* qtd_find_free (void); @@ -146,9 +151,10 @@ static void qtd_init (ehci_qtd_t* qtd, void const* buffer, uint16_t total_bytes) TU_ATTR_ALWAYS_INLINE static inline ehci_link_t* list_get_period_head(uint8_t rhport, uint32_t interval_ms); TU_ATTR_ALWAYS_INLINE static inline ehci_qhd_t* list_get_async_head(uint8_t rhport); -TU_ATTR_ALWAYS_INLINE static inline void list_insert (ehci_link_t *current, ehci_link_t *new, uint8_t new_type); TU_ATTR_ALWAYS_INLINE static inline ehci_link_t* list_next (ehci_link_t const *p_link); -static void list_remove_qhd_by_daddr(ehci_link_t* list_head, uint8_t dev_addr); +TU_ATTR_ALWAYS_INLINE static inline void list_insert (ehci_link_t *current, ehci_link_t *entry, uint8_t type); +TU_ATTR_ALWAYS_INLINE static inline void list_remove(ehci_link_t* head, ehci_link_t* prev, ehci_qhd_t* qhd); +static void list_remove_qhd_by_addr(ehci_link_t *list_head, uint8_t dev_addr, uint8_t ep_addr); static void ehci_disable_schedule(ehci_registers_t* regs, bool is_period) { // maybe have a timeout for status @@ -175,15 +181,12 @@ static void ehci_enable_schedule(ehci_registers_t* regs, bool is_period) { //--------------------------------------------------------------------+ // HCD API //--------------------------------------------------------------------+ - -uint32_t hcd_frame_number(uint8_t rhport) -{ +uint32_t hcd_frame_number(uint8_t rhport) { (void) rhport; return (ehci_data.uframe_number + ehci_data.regs->frame_index) >> 3; } -void hcd_port_reset(uint8_t rhport) -{ +void hcd_port_reset(uint8_t rhport) { (void) rhport; ehci_registers_t* regs = ehci_data.regs; @@ -204,8 +207,7 @@ void hcd_port_reset(uint8_t rhport) regs->portsc = portsc; } -void hcd_port_reset_end(uint8_t rhport) -{ +void hcd_port_reset_end(uint8_t rhport) { (void) rhport; ehci_registers_t* regs = ehci_data.regs; @@ -221,32 +223,29 @@ void hcd_port_reset_end(uint8_t rhport) regs->portsc = portsc; } -bool hcd_port_connect_status(uint8_t rhport) -{ +bool hcd_port_connect_status(uint8_t rhport) { (void) rhport; return ehci_data.regs->portsc_bm.current_connect_status; } -tusb_speed_t hcd_port_speed_get(uint8_t rhport) -{ +tusb_speed_t hcd_port_speed_get(uint8_t rhport) { (void) rhport; return (tusb_speed_t) ehci_data.regs->portsc_bm.nxp_port_speed; // NXP specific port speed } // Close all opened endpoint belong to this device -void hcd_device_close(uint8_t rhport, uint8_t daddr) -{ +void hcd_device_close(uint8_t rhport, uint8_t daddr) { // skip dev0 if (daddr == 0) { return; } - // Remove from async list - list_remove_qhd_by_daddr((ehci_link_t *) list_get_async_head(rhport), daddr); + // Remove from async list all endpoints of this device + list_remove_qhd_by_addr((ehci_link_t *) list_get_async_head(rhport), daddr, TUSB_INDEX_INVALID_8); - // Remove from all interval period list - for(uint8_t i = 0; i < TU_ARRAY_SIZE(ehci_data.period_head_arr); i++) { - list_remove_qhd_by_daddr((ehci_link_t *) &ehci_data.period_head_arr[i], daddr); + // Remove from all interval period list of this device + for (uint8_t i = 0; i < TU_ARRAY_SIZE(ehci_data.period_head_arr); i++) { + list_remove_qhd_by_addr((ehci_link_t *) &ehci_data.period_head_arr[i], daddr, TUSB_INDEX_INVALID_8); } // Async doorbell (EHCI 4.8.2 for operational details) @@ -358,12 +357,10 @@ bool ehci_init(uint8_t rhport, uint32_t capability_reg, uint32_t operatial_reg) } #if 0 -static void ehci_stop(uint8_t rhport) -{ +static void ehci_stop(uint8_t rhport) { (void) rhport; ehci_registers_t* regs = ehci_data.regs; - regs->command_bm.run_stop = 0; // USB Spec: controller has to stop within 16 uframe = 2 frames @@ -375,41 +372,44 @@ static void ehci_stop(uint8_t rhport) // Endpoint API //--------------------------------------------------------------------+ -bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) -{ - (void) rhport; - +bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) { // TODO not support ISO yet TU_ASSERT (ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); //------------- Prepare Queue Head -------------// - ehci_qhd_t *p_qhd = (ep_desc->bEndpointAddress == 0) ? qhd_control(dev_addr) : qhd_find_free(); + ehci_qhd_t *p_qhd; + if (ep_desc->bEndpointAddress == 0) { + p_qhd = qhd_control(dev_addr); + } else { + TU_VERIFY(NULL == qhd_get_from_addr(dev_addr, ep_desc->bEndpointAddress)); // ep not opened yet + p_qhd = qhd_find_free(); + } TU_ASSERT(p_qhd); - qhd_init(p_qhd, dev_addr, ep_desc); - // control of dev0 is always present as async head - if ( dev_addr == 0 ) return true; + // control of dev0 always exists as async head + if (dev_addr == 0) { + return true; + } // Insert to list ehci_link_t * list_head = NULL; - - switch (ep_desc->bmAttributes.xfer) - { + switch (ep_desc->bmAttributes.xfer) { case TUSB_XFER_CONTROL: case TUSB_XFER_BULK: - list_head = (ehci_link_t*) list_get_async_head(rhport); - break; + list_head = (ehci_link_t *) list_get_async_head(rhport); + break; case TUSB_XFER_INTERRUPT: list_head = list_get_period_head(rhport, p_qhd->interval_ms); - break; + break; case TUSB_XFER_ISOCHRONOUS: // TODO iso is not supported - break; + break; - default: break; + default: + break; } TU_ASSERT(list_head); @@ -421,8 +421,23 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const return true; } -bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) -{ +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + ehci_qhd_t* qhd = qhd_get_from_addr(daddr, ep_addr); + TU_VERIFY(qhd != NULL); + + ehci_link_t * list_head; + if (qhd_is_periodic(qhd)) { + // interrupt endpoint + list_head = list_get_period_head(rhport, qhd->interval_ms);; + } else { + list_head = (ehci_link_t *) list_get_async_head(rhport); + } + + list_remove_qhd_by_addr(list_head, daddr, ep_addr); + return true; +} + +bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) { (void) rhport; ehci_qhd_t* qhd = &ehci_data.control[dev_addr].qhd; @@ -444,14 +459,14 @@ bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet return true; } -bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) -{ +bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) { (void) rhport; uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); ehci_qhd_t* qhd = qhd_get_from_addr(dev_addr, ep_addr); + TU_VERIFY(qhd != NULL); ehci_qtd_t* qtd; if (epnum == 0) { @@ -540,8 +555,7 @@ bool hcd_edpt_clear_stall(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { // This isr mean it is safe to modify previously removed queue head from async list. // In tinyusb, queue head is only removed when device is unplugged. TU_ATTR_ALWAYS_INLINE static inline -void async_advance_isr(uint8_t rhport) -{ +void async_advance_isr(uint8_t rhport) { (void) rhport; ehci_qhd_t *qhd_pool = ehci_data.qhd_pool; @@ -612,8 +626,7 @@ void qhd_xfer_complete_isr(ehci_qhd_t * qhd) { } TU_ATTR_ALWAYS_INLINE static inline -void proccess_async_xfer_isr(ehci_qhd_t * const list_head) -{ +void proccess_async_xfer_isr(ehci_qhd_t * const list_head) { ehci_qhd_t *qhd = list_head; do { @@ -623,8 +636,7 @@ void proccess_async_xfer_isr(ehci_qhd_t * const list_head) } TU_ATTR_ALWAYS_INLINE static inline -void process_period_xfer_isr(uint8_t rhport, uint32_t interval_ms) -{ +void process_period_xfer_isr(uint8_t rhport, uint32_t interval_ms) { uint32_t const period_1ms_addr = (uint32_t) list_get_period_head(rhport, 1u); ehci_link_t next_link = *list_get_period_head(rhport, interval_ms); @@ -726,51 +738,55 @@ TU_ATTR_ALWAYS_INLINE static inline ehci_link_t* list_next(ehci_link_t const *p_ return (ehci_link_t*) tu_align32(p_link->address); } -TU_ATTR_ALWAYS_INLINE static inline void list_insert(ehci_link_t *current, ehci_link_t *new, uint8_t new_type) -{ - new->address = current->address; - current->address = ((uint32_t) new) | (new_type << 1); +TU_ATTR_ALWAYS_INLINE static inline void list_insert(ehci_link_t *current, ehci_link_t *entry, uint8_t type) { + entry->address = current->address; + current->address = ((uint32_t) entry) | (type << 1); +} + +// Remove a queue head from the list. +// Per EHCI 4.8.2 the removed qhd's next is linked to list head (which always reachable by Host Controller) +// TODO support iTD/siTD +TU_ATTR_ALWAYS_INLINE static inline void list_remove(ehci_link_t* head, ehci_link_t* prev, ehci_qhd_t* qhd) { + // TODO deactivate all TD, wait for QHD to inactive before removal + prev->address = qhd->next.address; + + // link the removed qhd's next to list head + qhd->next.address = ((uint32_t) head) | (EHCI_QTYPE_QHD << 1); + + if (qhd_is_periodic(qhd)) { + // period list queue element is guarantee to be free in the next frame (1 ms) + qhd->used = 0; + } else { + // async list use async advance handshake. Mark as removing, will completely re-usable when async advance isr occurs + qhd->removing = 1; + } + + hcd_dcache_clean(qhd, sizeof(ehci_qhd_t)); + hcd_dcache_clean(prev, sizeof(ehci_qhd_t)); } -// Remove all queue head belong to this device address -static void list_remove_qhd_by_daddr(ehci_link_t* list_head, uint8_t dev_addr) { - ehci_link_t* prev = list_head; +// Remove queue head belong to this device address +static void list_remove_qhd_by_addr(ehci_link_t *list_head, uint8_t dev_addr, uint8_t ep_addr) { + ehci_link_t *prev = list_head; while (prev && !prev->terminate) { - ehci_qhd_t* qhd = (ehci_qhd_t*) (uintptr_t) list_next(prev); + ehci_qhd_t *qhd = (ehci_qhd_t *) (uintptr_t) list_next(prev); // done if loop back to head - if ( (uintptr_t) qhd == (uintptr_t) list_head) { + if ((uintptr_t) qhd == (uintptr_t) list_head) { break; } - if ( qhd->dev_addr == dev_addr ) { - // TODO deactivate all TD, wait for QHD to inactive before removal - prev->address = qhd->next.address; - - // EHCI 4.8.2 link the removed qhd's next to async head (which always reachable by Host Controller) - qhd->next.address = ((uint32_t) list_head) | (EHCI_QTYPE_QHD << 1); - - if ( qhd->int_smask ) - { - // period list queue element is guarantee to be free in the next frame (1 ms) - qhd->used = 0; - }else - { - // async list use async advance handshake - // mark as removing, will completely re-usable when async advance isr occurs - qhd->removing = 1; - } - - hcd_dcache_clean(qhd, sizeof(ehci_qhd_t)); - hcd_dcache_clean(prev, sizeof(ehci_qhd_t)); - }else { + // ep_addr is 0xff means all endpoints of this device address + if (qhd->dev_addr == dev_addr && + (ep_addr == TUSB_INDEX_INVALID_8 || qhd_ep_addr(qhd) == ep_addr)) { + list_remove(list_head, prev, qhd); + } else { prev = list_next(prev); } } } - //--------------------------------------------------------------------+ // Queue Header helper //--------------------------------------------------------------------+ @@ -782,8 +798,10 @@ TU_ATTR_ALWAYS_INLINE static inline ehci_qhd_t* qhd_control(uint8_t dev_addr) { // Find a free queue head TU_ATTR_ALWAYS_INLINE static inline ehci_qhd_t *qhd_find_free(void) { - for ( uint32_t i = 0; i < QHD_MAX; i++ ) { - if ( !ehci_data.qhd_pool[i].used ) return &ehci_data.qhd_pool[i]; + for (uint32_t i = 0; i < QHD_MAX; i++) { + if (!ehci_data.qhd_pool[i].used) { + return &ehci_data.qhd_pool[i]; + } } return NULL; } @@ -800,10 +818,9 @@ static ehci_qhd_t *qhd_get_from_addr(uint8_t dev_addr, uint8_t ep_addr) { } ehci_qhd_t *qhd_pool = ehci_data.qhd_pool; - - for ( uint32_t i = 0; i < QHD_MAX; i++ ) { - if ( (qhd_pool[i].dev_addr == dev_addr) && - ep_addr == tu_edpt_addr(qhd_pool[i].ep_number, qhd_pool[i].pid) ) { + for (uint32_t i = 0; i < QHD_MAX; i++) { + if ((qhd_pool[i].dev_addr == dev_addr) && + ep_addr == qhd_ep_addr(&qhd_pool[i])) { return &qhd_pool[i]; } } @@ -812,8 +829,7 @@ static ehci_qhd_t *qhd_get_from_addr(uint8_t dev_addr, uint8_t ep_addr) { } // Init queue head with endpoint descriptor -static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) -{ +static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) { // address 0 is used as async head, which always on the list --> cannot be cleared (ehci halted otherwise) if (dev_addr != 0) { tu_memclr(p_qhd, sizeof(ehci_qhd_t)); @@ -830,39 +846,43 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t c p_qhd->ep_number = tu_edpt_number(ep_desc->bEndpointAddress); p_qhd->ep_speed = devtree_info.speed; p_qhd->data_toggle_control= (xfer_type == TUSB_XFER_CONTROL) ? 1 : 0; - p_qhd->head_list_flag = (dev_addr == 0) ? 1 : 0; // addr0's endpoint is the static asyn list head + p_qhd->head_list_flag = (dev_addr == 0) ? 1 : 0; // addr0's endpoint is the static async list head p_qhd->max_packet_size = tu_edpt_packet_size(ep_desc); p_qhd->fl_ctrl_ep_flag = ((xfer_type == TUSB_XFER_CONTROL) && (p_qhd->ep_speed != TUSB_SPEED_HIGH)) ? 1 : 0; p_qhd->nak_reload = 0; - // Bulk/Control -> smask = cmask = 0 - // TODO Isochronous - if (TUSB_XFER_INTERRUPT == xfer_type) - { - if (TUSB_SPEED_HIGH == p_qhd->ep_speed) - { - TU_ASSERT( interval <= 16, ); - if ( interval < 4) // sub millisecond interval - { - p_qhd->interval_ms = 0; - p_qhd->int_smask = (interval == 1) ? TU_BIN8(11111111) : - (interval == 2) ? TU_BIN8(10101010) : TU_BIN8(01000100); - }else - { - p_qhd->interval_ms = (uint8_t) tu_min16( 1 << (interval-4), 255 ); - p_qhd->int_smask = TU_BIT(interval % 8); + switch (xfer_type) { + case TUSB_XFER_CONTROL: + case TUSB_XFER_BULK: + p_qhd->int_smask = p_qhd->fl_int_cmask = 0; + break; + + case TUSB_XFER_INTERRUPT: + if (TUSB_SPEED_HIGH == p_qhd->ep_speed) { + TU_ASSERT(interval <= 16, ); + if (interval < 4) { + // sub millisecond interval + p_qhd->interval_ms = 0; + p_qhd->int_smask = (interval == 1) ? TU_BIN8(11111111) : + (interval == 2) ? TU_BIN8(10101010): TU_BIN8(01000100); + } else { + p_qhd->interval_ms = (uint8_t) tu_min16(1 << (interval - 4), 255); + p_qhd->int_smask = TU_BIT(interval % 8); + } + } else { + TU_ASSERT(0 != interval, ); + // Full/Low: 4.12.2.1 (EHCI) case 1 schedule start split at 1 us & complete split at 2,3,4 uframes + p_qhd->int_smask = 0x01; + p_qhd->fl_int_cmask = TU_BIN8(11100); + p_qhd->interval_ms = interval; } - }else - { - TU_ASSERT( 0 != interval, ); - // Full/Low: 4.12.2.1 (EHCI) case 1 schedule start split at 1 us & complete split at 2,3,4 uframes - p_qhd->int_smask = 0x01; - p_qhd->fl_int_cmask = TU_BIN8(11100); - p_qhd->interval_ms = interval; - } - }else - { - p_qhd->int_smask = p_qhd->fl_int_cmask = 0; + break; + + case TUSB_XFER_ISOCHRONOUS: + // TODO not support ISO yet + break; + + default: break; } p_qhd->fl_hub_addr = devtree_info.hub_addr; @@ -880,8 +900,7 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t c p_qhd->qtd_overlay.next.terminate = 1; p_qhd->qtd_overlay.alternate.terminate = 1; - if (TUSB_XFER_BULK == xfer_type && p_qhd->ep_speed == TUSB_SPEED_HIGH && p_qhd->pid == EHCI_PID_OUT) - { + if (TUSB_XFER_BULK == xfer_type && p_qhd->ep_speed == TUSB_SPEED_HIGH && p_qhd->pid == EHCI_PID_OUT) { p_qhd->qtd_overlay.ping_err = 1; // do PING for Highspeed Bulk OUT, EHCI section 4.11 } } diff --git a/src/portable/ehci/ehci.h b/src/portable/ehci/ehci.h index 457adc1d3..87659701b 100644 --- a/src/portable/ehci/ehci.h +++ b/src/portable/ehci/ehci.h @@ -49,15 +49,14 @@ // TODO merge OHCI with EHCI enum { - EHCI_MAX_ITD = 4, + EHCI_MAX_ITD = 4, EHCI_MAX_SITD = 16 }; //--------------------------------------------------------------------+ // EHCI Data Structure //--------------------------------------------------------------------+ -enum -{ +enum { EHCI_QTYPE_ITD = 0 , EHCI_QTYPE_QHD , EHCI_QTYPE_SITD , @@ -65,8 +64,7 @@ enum }; /// EHCI PID -enum -{ +enum { EHCI_PID_OUT = 0 , EHCI_PID_IN , EHCI_PID_SETUP @@ -74,187 +72,182 @@ enum /// Link pointer typedef union { - uint32_t address; - struct { - uint32_t terminate : 1; - uint32_t type : 2; - }; -}ehci_link_t; + uint32_t address; + struct { + uint32_t terminate : 1; + uint32_t type : 2; + }; +} ehci_link_t; TU_VERIFY_STATIC( sizeof(ehci_link_t) == 4, "size is not correct" ); /// Queue Element Transfer Descriptor /// Qtd is used to declare overlay in ehci_qhd_t -> cannot be declared with TU_ATTR_ALIGNED(32) -typedef struct -{ - // Word 0: Next QTD Pointer - ehci_link_t next; - - // Word 1: Alternate Next QTD Pointer (not used) - union{ - ehci_link_t alternate; - struct { - uint32_t : 5; - uint32_t used : 1; - uint32_t : 10; - uint32_t expected_bytes : 16; - }; - }; - - // Word 2: qTQ Token - volatile uint32_t ping_err : 1 ; ///< For Highspeed: 0 Out, 1 Ping. Full/Slow used as error indicator - volatile uint32_t non_hs_split_state : 1 ; ///< Used by HC to track the state of split transaction - volatile uint32_t non_hs_missed_uframe : 1 ; ///< HC misses a complete split transaction - volatile uint32_t xact_err : 1 ; ///< Error (Timeout, CRC, Bad PID ... ) - volatile uint32_t babble_err : 1 ; ///< Babble detected, also set Halted bit to 1 - volatile uint32_t buffer_err : 1 ; ///< Data overrun/underrun error - volatile uint32_t halted : 1 ; ///< Serious error or STALL received - volatile uint32_t active : 1 ; ///< Start transfer, clear by HC when complete - - uint32_t pid : 2 ; ///< 0: OUT, 1: IN, 2 Setup - volatile uint32_t err_count : 2 ; ///< Error Counter of consecutive errors - volatile uint32_t current_page : 3 ; ///< Index into the qTD buffer pointer list - uint32_t int_on_complete : 1 ; ///< Interrupt on complete - volatile uint32_t total_bytes : 15 ; ///< Transfer bytes, decreased during transaction - volatile uint32_t data_toggle : 1 ; ///< Data Toggle bit - - - /// Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page - uint32_t buffer[5]; +typedef struct { + // Word 0 Next QTD Pointer + ehci_link_t next; + + // Word 1 Alternate Next QTD Pointer (not used) + union { + ehci_link_t alternate; + struct { + uint32_t : 5; + uint32_t used : 1; + uint32_t : 10; + uint32_t expected_bytes : 16; + }; + }; + + // Word 2 qTQ Token + volatile uint32_t ping_err : 1; // For Highspeed: 0 Out, 1 Ping. Full/Slow used as error indicator + volatile uint32_t non_hs_split_state : 1; // Used by HC to track the state of split transaction + volatile uint32_t non_hs_missed_uframe : 1; // HC misses a complete split transaction + volatile uint32_t xact_err : 1; // Error (Timeout, CRC, Bad PID ... ) + volatile uint32_t babble_err : 1; // Babble detected, also set Halted bit to 1 + volatile uint32_t buffer_err : 1; // Data overrun/underrun error + volatile uint32_t halted : 1; // Serious error or STALL received + volatile uint32_t active : 1; // Start transfer, clear by HC when complete + + uint32_t pid : 2; // 0: OUT, 1: IN, 2 Setup + volatile uint32_t err_count : 2; // Error Counter of consecutive errors + volatile uint32_t current_page : 3; // Index into the qTD buffer pointer list + uint32_t int_on_complete : 1; // Interrupt on complete + volatile uint32_t total_bytes : 15; // Transfer bytes, decreased during transaction + volatile uint32_t data_toggle : 1; // Data Toggle bit + + // Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. + // The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page + uint32_t buffer[5]; } ehci_qtd_t; TU_VERIFY_STATIC( sizeof(ehci_qtd_t) == 32, "size is not correct" ); /// Queue Head -typedef struct TU_ATTR_ALIGNED(32) -{ - // Word 0: Next QHD - ehci_link_t next; - - // Word 1: Endpoint Characteristics - uint32_t dev_addr : 7 ; ///< device address - uint32_t fl_inactive_next_xact : 1 ; ///< Only valid for Periodic with Full/Slow speed - uint32_t ep_number : 4 ; ///< EP number - uint32_t ep_speed : 2 ; ///< 0: Full, 1: Low, 2: High - uint32_t data_toggle_control : 1 ; ///< 0: use DT in qHD, 1: use DT in qTD - uint32_t head_list_flag : 1 ; ///< Head of the queue - uint32_t max_packet_size : 11 ; ///< Max packet size - uint32_t fl_ctrl_ep_flag : 1 ; ///< 1 if is Full/Low speed control endpoint - uint32_t nak_reload : 4 ; ///< Used by HC - - // Word 2: Endpoint Capabilities - uint32_t int_smask : 8 ; ///< Interrupt Schedule Mask - uint32_t fl_int_cmask : 8 ; ///< Split Completion Mask for Full/Slow speed - uint32_t fl_hub_addr : 7 ; ///< Hub Address for Full/Slow speed - uint32_t fl_hub_port : 7 ; ///< Hub Port for Full/Slow speed - uint32_t mult : 2 ; ///< Transaction per micro frame - - // Word 3: Current qTD Pointer - volatile uint32_t qtd_addr; - - // Word 4-11: Transfer Overlay - volatile ehci_qtd_t qtd_overlay; - - //--------------------------------------------------------------------+ +typedef struct TU_ATTR_ALIGNED(32) { + // Word 0 Next QHD + ehci_link_t next; + + // Word 1 Endpoint Characteristics + uint32_t dev_addr : 7; // device address + uint32_t fl_inactive_next_xact : 1; // Only valid for Periodic with Full/Slow speed + uint32_t ep_number : 4; // EP number + uint32_t ep_speed : 2; // Full (0), Low (1), High (2) + uint32_t data_toggle_control : 1; // 0 use DT in qHD, 1 use DT in qTD + uint32_t head_list_flag : 1; // Head of the queue + uint32_t max_packet_size : 11; // Max packet size + uint32_t fl_ctrl_ep_flag : 1; // 1 if is Full/Low speed control endpoint + uint32_t nak_reload : 4; // Used by HC + + // Word 2 Endpoint Capabilities + uint32_t int_smask : 8; // Interrupt Schedule Mask + uint32_t fl_int_cmask : 8; // Split Completion Mask for Full/Slow speed + uint32_t fl_hub_addr : 7; // Hub Address for Full/Slow speed + uint32_t fl_hub_port : 7; // Hub Port for Full/Slow speed + uint32_t mult : 2; // Transaction per micro frame + + // Word 3 Current qTD Pointer + volatile uint32_t qtd_addr; + + // Word 4-11 Transfer Overlay + volatile ehci_qtd_t qtd_overlay; + + //--------------------------------------------------------------------+ /// Due to the fact QHD is 32 bytes aligned but occupies only 48 bytes - /// thus there are 16 bytes padding free that we can make use of. + /// thus there are 16 bytes padding free that we can make use of. //--------------------------------------------------------------------+ - uint8_t used; - uint8_t removing; // removed from asyn list, waiting for async advance - uint8_t pid; - uint8_t interval_ms; // polling interval in frames (or millisecond) + uint8_t used; + uint8_t removing;// removed from asyn list, waiting for async advance + uint8_t pid; + uint8_t interval_ms;// polling interval in frames (or millisecond) - uint8_t TU_RESERVED[4]; + uint8_t TU_RESERVED[4]; // Attached TD management, note usbh will only queue 1 TD per QHD. // buffer for dcache invalidate since td's buffer is modified by HC and finding initial buffer address is not trivial uint32_t attached_buffer; - ehci_qtd_t * volatile attached_qtd; + ehci_qtd_t *volatile attached_qtd; } ehci_qhd_t; - TU_VERIFY_STATIC( sizeof(ehci_qhd_t) == 64, "size is not correct" ); /// Highspeed Isochronous Transfer Descriptor (section 3.3) typedef struct TU_ATTR_ALIGNED(32) { - // Word 0: Next Link Pointer - ehci_link_t next; - - // Word 1-8: iTD Transaction Status and Control List - struct { - // iTD Control - volatile uint32_t offset : 12 ; ///< This field is a value that is an offset, expressed in bytes, from the beginning of a buffer. - volatile uint32_t page_select : 3 ; ///< These bits are set by software to indicate which of the buffer page pointers the offset field in this slot should be concatenated to produce the starting memory address for this transaction. The valid range of values for this field is 0 to 6 - uint32_t int_on_complete : 1 ; ///< If this bit is set to a one, it specifies that when this transaction completes, the Host Controller should issue an interrupt at the next interrupt threshold - volatile uint32_t length : 12 ; ///< For an OUT, this field is the number of data bytes the host controller will send during the transaction. The host controller is not required to update this field to reflect the actual number of bytes transferred during the transfer - ///< For an IN, the initial value of the field is the number of bytes the host expects the endpoint to deliver. During the status update, the host controller writes back the number of bytes successfully received. The value in this register is the actual byte count - // iTD Status - volatile uint32_t error : 1 ; ///< Set to a one by the Host Controller during status update in the case where the host did not receive a valid response from the device (Timeout, CRC, Bad PID, etc.). This bit may only be set for isochronous IN transactions. - volatile uint32_t babble_err : 1 ; ///< Set to a 1 by the Host Controller during status update when a babble is detected during the transaction - volatile uint32_t buffer_err : 1 ; ///< Set to a 1 by the Host Controller during status update to indicate that the Host Controller is unable to keep up with the reception of incoming data (overrun) or is unable to supply data fast enough during transmission (underrun). - volatile uint32_t active : 1 ; ///< Set to 1 by software to enable the execution of an isochronous transaction by the Host Controller - } xact[8]; - - // Word 9-15 Buffer Page Pointer List (Plus) - uint32_t BufferPointer[7]; - -// // FIXME: Store meta data into buffer pointer reserved for saving memory -// /*---------- HCD Area ----------*/ -// uint32_t used; -// uint32_t IhdIdx; -// uint32_t reserved[6]; + // Word 0: Next Link Pointer + ehci_link_t next; + + // Word 1-8: iTD Transaction Status and Control List + struct { + // iTD Control + volatile uint32_t offset : 12; // offset in bytes, from the beginning of a buffer. + volatile uint32_t page_select : 3; // buffer page pointers the offset field in this slot should be concatenated to produce the starting memory address for this transaction. The valid range of values for this field is 0 to 6 + uint32_t int_on_complete : 1; // If this bit is set to a one, it specifies that when this transaction completes, the Host Controller should issue an interrupt at the next interrupt threshold + volatile uint32_t length : 12; // For an OUT, this field is the number of data bytes the host controller will send during the transaction. The host controller is not required to update this field to reflect the actual number of bytes transferred during the transfer + // For an IN, the initial value of the field is the number of bytes the host expects the endpoint to deliver. During the status update, the host controller writes back the number of bytes successfully received. The value in this register is the actual byte count + // iTD Status + volatile uint32_t error : 1; // Set to a one by the Host Controller during status update in the case where the host did not receive a valid response from the device (Timeout, CRC, Bad PID, etc.). This bit may only be set for isochronous IN transactions. + volatile uint32_t babble_err : 1; // Set to a 1 by the Host Controller during status update when a babble is detected during the transaction + volatile uint32_t buffer_err : 1; // Set to a 1 by the Host Controller during status update to indicate that the Host Controller is unable to keep up with the reception of incoming data (overrun) or is unable to supply data fast enough during transmission (underrun). + volatile uint32_t active : 1; // Set to 1 by software to enable the execution of an isochronous transaction by the Host Controller + } xact[8]; + + // Word 9-15 Buffer Page Pointer List (Plus) + uint32_t BufferPointer[7]; + + // FIXME: Store meta data into buffer pointer reserved for saving memory + //---------- HCD Area ---------- + // uint32_t used; + // uint32_t IhdIdx; + // uint32_t reserved[6]; } ehci_itd_t; - TU_VERIFY_STATIC( sizeof(ehci_itd_t) == 64, "size is not correct" ); /// Split (Full-Speed) Isochronous Transfer Descriptor -typedef struct TU_ATTR_ALIGNED(32) -{ +typedef struct TU_ATTR_ALIGNED(32) { // Word 0: Next Link Pointer - ehci_link_t next; - - // Word 1: siTD Endpoint Characteristics - uint32_t dev_addr : 7; ///< This field selects the specific device serving as the data source or sink. - uint32_t : 1; ///< reserved - uint32_t ep_number : 4; ///< This 4-bit field selects the particular endpoint number on the device serving as the data source or sink. - uint32_t : 4; ///< This field is reserved and should be set to zero. - uint32_t hub_addr : 7; ///< This field holds the device address of the transaction translators’ hub. - uint32_t : 1; ///< reserved - uint32_t port_number : 7; ///< This field is the port number of the recipient transaction translator. - uint32_t direction : 1; ///< 0 = OUT; 1 = IN. This field encodes whether the full-speed transaction should be an IN or OUT. - - // Word 2: Micro-frame Schedule Control - uint8_t int_smask ; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute complete-split transactions - uint8_t fl_int_cmask; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute start-split transactions. - uint16_t reserved ; ///< reserved - - // Word 3: siTD Transfer Status and Control - // Status [7:0] TODO identical to qTD Token'status --> refactor later - volatile uint32_t : 1 ; // reserved - volatile uint32_t split_state : 1 ; - volatile uint32_t missed_uframe : 1 ; - volatile uint32_t xact_err : 1 ; - volatile uint32_t babble_err : 1 ; - volatile uint32_t buffer_err : 1 ; - volatile uint32_t error : 1 ; - volatile uint32_t active : 1 ; - // Micro-frame Schedule Control - volatile uint32_t cmask_progress : 8 ; ///< This field is used by the host controller to record which split-completes have been executed. See Section 4.12.3.3.2 for behavioral requirements. - volatile uint32_t total_bytes : 10 ; ///< This field is initialized by software to the total number of bytes expected in this transfer. Maximum value is 1023 - volatile uint32_t : 4 ; ///< reserved - volatile uint32_t page_select : 1 ; ///< Used to indicate which data page pointer should be concatenated with the CurrentOffsetfield to construct a data buffer pointer - uint32_t int_on_complete : 1 ; ///< Do not interrupt when transaction is complete. 1 = Do interrupt when transaction is complete - uint32_t : 0 ; // padding to the end of current storage unit - - /// Word 4-5: Buffer Pointer List - uint32_t buffer[2]; // buffer[1] TP: Transaction Position - T-Count: Transaction Count - - /*---------- Word 6 ----------*/ - ehci_link_t back; - - /// SITD is 32-byte aligned but occupies only 28 --> 4 bytes for storing extra data - uint8_t used; - uint8_t ihd_idx; - uint8_t reserved2[2]; + ehci_link_t next; + + // Word 1: siTD Endpoint Characteristics + uint32_t dev_addr : 7; ///< This field selects the specific device serving as the data source or sink. + uint32_t : 1; ///< reserved + uint32_t ep_number : 4; ///< This 4-bit field selects the particular endpoint number on the device serving as the data source or sink. + uint32_t : 4; ///< This field is reserved and should be set to zero. + uint32_t hub_addr : 7; ///< This field holds the device address of the transaction translators’ hub. + uint32_t : 1; ///< reserved + uint32_t port_number : 7; ///< This field is the port number of the recipient transaction translator. + uint32_t direction : 1; ///< 0 = OUT; 1 = IN. This field encodes whether the full-speed transaction should be an IN or OUT. + + // Word 2: Micro-frame Schedule Control + uint8_t int_smask ; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute complete-split transactions + uint8_t fl_int_cmask; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute start-split transactions. + uint16_t reserved ; ///< reserved + + // Word 3: siTD Transfer Status and Control + // Status [7:0] TODO identical to qTD Token'status --> refactor later + volatile uint32_t : 1 ; // reserved + volatile uint32_t split_state : 1 ; + volatile uint32_t missed_uframe : 1 ; + volatile uint32_t xact_err : 1 ; + volatile uint32_t babble_err : 1 ; + volatile uint32_t buffer_err : 1 ; + volatile uint32_t error : 1 ; + volatile uint32_t active : 1 ; + // Micro-frame Schedule Control + volatile uint32_t cmask_progress : 8 ; ///< This field is used by the host controller to record which split-completes have been executed. See Section 4.12.3.3.2 for behavioral requirements. + volatile uint32_t total_bytes : 10 ; ///< This field is initialized by software to the total number of bytes expected in this transfer. Maximum value is 1023 + volatile uint32_t : 4 ; ///< reserved + volatile uint32_t page_select : 1 ; ///< Used to indicate which data page pointer should be concatenated with the CurrentOffsetfield to construct a data buffer pointer + uint32_t int_on_complete : 1 ; ///< Do not interrupt when transaction is complete. 1 = Do interrupt when transaction is complete + uint32_t : 0 ; // padding to the end of current storage unit + + /// Word 4-5: Buffer Pointer List + uint32_t buffer[2]; // buffer[1] TP: Transaction Position - T-Count: Transaction Count + + /*---------- Word 6 ----------*/ + ehci_link_t back; + + /// SITD is 32-byte aligned but occupies only 28 --> 4 bytes for storing extra data + uint8_t used; + uint8_t ihd_idx; + uint8_t reserved2[2]; } ehci_sitd_t; TU_VERIFY_STATIC( sizeof(ehci_sitd_t) == 32, "size is not correct" ); @@ -315,8 +308,7 @@ enum { EHCI_PORTSC_MASK_OVER_CURRENT_CHANGE }; -typedef volatile struct -{ +typedef volatile struct { union { uint32_t command; // 0x00 diff --git a/test/hil/hil_test.py b/test/hil/hil_test.py index 662bb3a1f..8b89de66c 100755 --- a/test/hil/hil_test.py +++ b/test/hil/hil_test.py @@ -340,8 +340,8 @@ def test_host_device_info(board): ser.close() if len(data) == 0: assert False, 'No data from device' - lines = data.decode('utf-8', errors='ignore').splitlines() + enum_dev_sn = [] for l in lines: vid_pid_sn = re.search(r'ID ([0-9a-fA-F]+):([0-9a-fA-F]+) SN (\w+)', l) @@ -353,7 +353,6 @@ def test_host_device_info(board): failed_msg = f'Expected {declared_devs}, Enumerated {enum_dev_sn}' print('\n'.join(lines)) assert False, failed_msg - return 0 -- cgit v1.3.1 From 4787cd5f546eabad630fc5c22f37f67a076ac37e Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 3 Apr 2025 18:11:33 +0700 Subject: fix(hcd) hcd_edpt_open() return true if endpoint is already opened. --- examples/host/device_info/src/main.c | 31 ++++++++++++++++++++----------- src/host/hcd.h | 1 + src/portable/analog/max3421/hcd_max3421.c | 2 +- src/portable/ehci/ehci.c | 4 +++- 4 files changed, 25 insertions(+), 13 deletions(-) (limited to 'src/host') diff --git a/examples/host/device_info/src/main.c b/examples/host/device_info/src/main.c index ac4c46a11..e924a137b 100644 --- a/examples/host/device_info/src/main.c +++ b/examples/host/device_info/src/main.c @@ -124,13 +124,18 @@ void tuh_mount_cb(uint8_t daddr) { } printf("Device %u: ID %04x:%04x SN ", daddr, desc.device.idVendor, desc.device.idProduct); - xfer_result = tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, desc.serial, sizeof(desc.serial)); + + xfer_result = XFER_RESULT_FAILED; + if (desc.device.iSerialNumber != 0) { + xfer_result = tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, desc.serial, sizeof(desc.serial)); + } if (XFER_RESULT_SUCCESS != xfer_result) { uint16_t* serial = (uint16_t*)(uintptr_t) desc.serial; - serial[0] = 'n'; - serial[1] = '/'; - serial[2] = 'a'; - serial[3] = 0; + serial[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * 3 + 2)); + serial[1] = 'n'; + serial[2] = '/'; + serial[3] = 'a'; + serial[4] = 0; } print_utf16((uint16_t*)(uintptr_t) desc.serial, sizeof(desc.serial)/2); printf("\r\n"); @@ -150,16 +155,20 @@ void tuh_mount_cb(uint8_t daddr) { // Get String descriptor using Sync API printf(" iManufacturer %u ", desc.device.iManufacturer); - xfer_result = tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf)); - if (XFER_RESULT_SUCCESS == xfer_result) { - print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2); + if (desc.device.iManufacturer != 0) { + xfer_result = tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf)); + if (XFER_RESULT_SUCCESS == xfer_result) { + print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2); + } } printf("\r\n"); printf(" iProduct %u ", desc.device.iProduct); - xfer_result = tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf)); - if (XFER_RESULT_SUCCESS == xfer_result) { - print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2); + if (desc.device.iProduct != 0) { + xfer_result = tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf)); + if (XFER_RESULT_SUCCESS == xfer_result) { + print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2); + } } printf("\r\n"); diff --git a/src/host/hcd.h b/src/host/hcd.h index aa9e9cf3b..b20d96d54 100644 --- a/src/host/hcd.h +++ b/src/host/hcd.h @@ -163,6 +163,7 @@ void hcd_device_close(uint8_t rhport, uint8_t dev_addr); //--------------------------------------------------------------------+ // Open an endpoint +// return true if successfully opened or endpoint is currently opened bool hcd_edpt_open(uint8_t rhport, uint8_t daddr, tusb_desc_endpoint_t const * ep_desc); // Close an endpoint diff --git a/src/portable/analog/max3421/hcd_max3421.c b/src/portable/analog/max3421/hcd_max3421.c index 3fbf950a4..bb33200f2 100644 --- a/src/portable/analog/max3421/hcd_max3421.c +++ b/src/portable/analog/max3421/hcd_max3421.c @@ -611,7 +611,7 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t daddr, tusb_desc_endpoint_t const * e ep = &_hcd_data.ep[0]; }else { if (NULL != find_ep_not_addr0(daddr, ep_num, ep_dir)) { - return false; // endpoint already opened + return true; // already opened } ep = allocate_ep(); TU_ASSERT(ep); diff --git a/src/portable/ehci/ehci.c b/src/portable/ehci/ehci.c index 292a352fb..7451f69a3 100644 --- a/src/portable/ehci/ehci.c +++ b/src/portable/ehci/ehci.c @@ -381,7 +381,9 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const if (ep_desc->bEndpointAddress == 0) { p_qhd = qhd_control(dev_addr); } else { - TU_VERIFY(NULL == qhd_get_from_addr(dev_addr, ep_desc->bEndpointAddress)); // ep not opened yet + if (NULL != qhd_get_from_addr(dev_addr, ep_desc->bEndpointAddress)) { + return true; // already opened + } p_qhd = qhd_find_free(); } TU_ASSERT(p_qhd); -- cgit v1.3.1