diff --git a/examples/CDC/no_serial/no_serial.ino b/examples/CDC/no_serial/no_serial.ino index 1f04357c..c7538d5b 100644 --- a/examples/CDC/no_serial/no_serial.ino +++ b/examples/CDC/no_serial/no_serial.ino @@ -23,7 +23,9 @@ int led = LED_BUILTIN; void setup() { - Serial.end(); + // clear configuration will remove all USB interfaces including CDC (Serial) + TinyUSBDevice.clearConfiguration(); + pinMode(led, OUTPUT); } diff --git a/examples/Composite/mouse_external_flash/mouse_external_flash.ino b/examples/Composite/mouse_external_flash/mouse_external_flash.ino index e6a7a499..8cdbbb1d 100644 --- a/examples/Composite/mouse_external_flash/mouse_external_flash.ino +++ b/examples/Composite/mouse_external_flash/mouse_external_flash.ino @@ -72,14 +72,12 @@ Adafruit_USBD_MSC usb_msc; // HID report descriptor using TinyUSB's template // Single Report (no ID) descriptor -uint8_t const desc_hid_report[] = -{ - TUD_HID_REPORT_DESC_MOUSE() +uint8_t const desc_hid_report[] = { + TUD_HID_REPORT_DESC_MOUSE() }; -// USB HID object. For ESP32 these values cannot be changed after this declaration -// desc report, desc len, protocol, interval, use out endpoint -Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROTOCOL_NONE, 2, false); +// USB HID object +Adafruit_USBD_HID usb_hid; #if defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(ARDUINO_NRF52840_CIRCUITPLAY) const int pin = 4; // Left Button @@ -93,6 +91,10 @@ Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROT const int pin = PIN_BUTTON1; bool activeState = false; +#elif defined(ARDUINO_ARCH_ESP32) + const int pin = 0; + bool activeState = false; + #else const int pin = 12; bool activeState = false; @@ -102,6 +104,11 @@ Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROT // the setup function runs once when you press reset or power the board void setup() { +#if defined(ARDUINO_ARCH_MBED) && defined(ARDUINO_ARCH_RP2040) + // Manual begin() is required on core without built-in support for TinyUSB such as mbed rp2040 + TinyUSB_Device_Init(0); +#endif + flash.begin(); pinMode(LED_BUILTIN, OUTPUT); @@ -123,9 +130,10 @@ void setup() // Set up button pinMode(pin, activeState ? INPUT_PULLDOWN : INPUT_PULLUP); - // Notes: following commented-out functions has no affect on ESP32 - // usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); - + // Set up HID + usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); + usb_hid.setBootProtocol(HID_ITF_PROTOCOL_NONE); + usb_hid.setPollInterval(2); usb_hid.begin(); Serial.begin(115200); diff --git a/examples/Composite/mouse_ramdisk/mouse_ramdisk.ino b/examples/Composite/mouse_ramdisk/mouse_ramdisk.ino index 37a48118..09da8690 100644 --- a/examples/Composite/mouse_ramdisk/mouse_ramdisk.ino +++ b/examples/Composite/mouse_ramdisk/mouse_ramdisk.ino @@ -33,14 +33,12 @@ Adafruit_USBD_MSC usb_msc; // HID report descriptor using TinyUSB's template // Single Report (no ID) descriptor -uint8_t const desc_hid_report[] = -{ - TUD_HID_REPORT_DESC_MOUSE() +uint8_t const desc_hid_report[] = { + TUD_HID_REPORT_DESC_MOUSE() }; -// USB HID object. For ESP32 these values cannot be changed after this declaration -// desc report, desc len, protocol, interval, use out endpoint -Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROTOCOL_NONE, 2, false); +// USB HID object +Adafruit_USBD_HID usb_hid; #if defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(ARDUINO_NRF52840_CIRCUITPLAY) const int pin = 4; // Left Button @@ -54,6 +52,10 @@ Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROT const int pin = PIN_BUTTON1; bool activeState = false; +#elif defined(ARDUINO_ARCH_ESP32) + const int pin = 0; + bool activeState = false; + #else const int pin = 12; bool activeState = false; @@ -84,9 +86,10 @@ void setup() // Set up button pinMode(pin, activeState ? INPUT_PULLDOWN : INPUT_PULLUP); - // Notes: following commented-out functions has no affect on ESP32 - // usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); - + // Set up HID + usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); + usb_hid.setBootProtocol(HID_ITF_PROTOCOL_NONE); + usb_hid.setPollInterval(2); usb_hid.begin(); Serial.begin(115200); diff --git a/examples/HID/hid_boot_keyboard/hid_boot_keyboard.ino b/examples/HID/hid_boot_keyboard/hid_boot_keyboard.ino index 1c4054b9..c5bca727 100644 --- a/examples/HID/hid_boot_keyboard/hid_boot_keyboard.ino +++ b/examples/HID/hid_boot_keyboard/hid_boot_keyboard.ino @@ -20,14 +20,13 @@ // HID report descriptor using TinyUSB's template // Single Report (no ID) descriptor -uint8_t const desc_hid_report[] = -{ +uint8_t const desc_hid_report[] = { TUD_HID_REPORT_DESC_KEYBOARD() }; // USB HID object. For ESP32 these values cannot be changed after this declaration // desc report, desc len, protocol, interval, use out endpoint -Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROTOCOL_KEYBOARD, 2, false); +Adafruit_USBD_HID usb_hid; //------------- Input Pins -------------// // Array of pins and its keycode. @@ -73,11 +72,11 @@ void setup() TinyUSB_Device_Init(0); #endif - // Notes: following commented-out functions has no affect on ESP32 - // usb_hid.setBootProtocol(HID_ITF_PROTOCOL_KEYBOARD); - // usb_hid.setPollInterval(2); - // usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); - // usb_hid.setStringDescriptor("TinyUSB Keyboard"); + // Setup HID + usb_hid.setBootProtocol(HID_ITF_PROTOCOL_KEYBOARD); + usb_hid.setPollInterval(2); + usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); + usb_hid.setStringDescriptor("TinyUSB Keyboard"); // Set up output report (on control endpoint) for Capslock indicator usb_hid.setReportCallback(NULL, hid_report_callback); diff --git a/examples/HID/hid_boot_mouse/hid_boot_mouse.ino b/examples/HID/hid_boot_mouse/hid_boot_mouse.ino index 08f5e833..1715d768 100644 --- a/examples/HID/hid_boot_mouse/hid_boot_mouse.ino +++ b/examples/HID/hid_boot_mouse/hid_boot_mouse.ino @@ -30,6 +30,10 @@ const int pin = PIN_BUTTON1; bool activeState = false; +#elif defined(ARDUINO_ARCH_ESP32) + const int pin = 0; + bool activeState = false; + #else const int pin = 12; bool activeState = false; @@ -38,14 +42,12 @@ // HID report descriptor using TinyUSB's template // Single Report (no ID) descriptor -uint8_t const desc_hid_report[] = -{ +uint8_t const desc_hid_report[] = { TUD_HID_REPORT_DESC_MOUSE() }; -// USB HID object. For ESP32 these values cannot be changed after this declaration -// desc report, desc len, protocol, interval, use out endpoint -Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROTOCOL_MOUSE, 2, false); +// USB HID object +Adafruit_USBD_HID usb_hid; // the setup function runs once when you press reset or power the board void setup() @@ -58,11 +60,11 @@ void setup() // Set up button, pullup opposite to active state pinMode(pin, activeState ? INPUT_PULLDOWN : INPUT_PULLUP); - // Notes: following commented-out functions has no affect on ESP32 - // usb_hid.setBootProtocol(HID_ITF_PROTOCOL_MOUSE); - // usb_hid.setPollInterval(2); - // usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); - // usb_hid.setStringDescriptor("TinyUSB Mouse"); + // Set up HID + usb_hid.setBootProtocol(HID_ITF_PROTOCOL_MOUSE); + usb_hid.setPollInterval(2); + usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); + usb_hid.setStringDescriptor("TinyUSB Mouse"); usb_hid.begin(); diff --git a/examples/HID/hid_composite/hid_composite.ino b/examples/HID/hid_composite/hid_composite.ino index f55abde6..3f179260 100644 --- a/examples/HID/hid_composite/hid_composite.ino +++ b/examples/HID/hid_composite/hid_composite.ino @@ -31,6 +31,10 @@ const int pin = PIN_BUTTON1; bool activeState = false; +#elif defined(ARDUINO_ARCH_ESP32) + const int pin = 0; + bool activeState = false; + #else const int pin = 12; bool activeState = false; @@ -46,24 +50,22 @@ enum }; // HID report descriptor using TinyUSB's template -uint8_t const desc_hid_report[] = -{ +uint8_t const desc_hid_report[] = { TUD_HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(RID_KEYBOARD) ), TUD_HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(RID_MOUSE) ), TUD_HID_REPORT_DESC_CONSUMER( HID_REPORT_ID(RID_CONSUMER_CONTROL) ) }; -// USB HID object. For ESP32 these values cannot be changed after this declaration -// desc report, desc len, protocol, interval, use out endpoint -Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROTOCOL_NONE, 2, false); +// USB HID object. +Adafruit_USBD_HID usb_hid; // the setup function runs once when you press reset or power the board void setup() { - // Notes: following commented-out functions has no affect on ESP32 - // usb_hid.setPollInterval(2); - // usb_hid.setReportDescriptor(); - // usb_hid.setStringDescriptor("TinyUSB HID Composite"); + // Set up HID + usb_hid.setPollInterval(2); + usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); + usb_hid.setStringDescriptor("TinyUSB HID Composite"); usb_hid.begin(); diff --git a/examples/HID/hid_dual_interfaces/hid_dual_interfaces.ino b/examples/HID/hid_dual_interfaces/hid_dual_interfaces.ino index 1a7984c2..43f5445b 100644 --- a/examples/HID/hid_dual_interfaces/hid_dual_interfaces.ino +++ b/examples/HID/hid_dual_interfaces/hid_dual_interfaces.ino @@ -34,36 +34,43 @@ const int pin = PIN_BUTTON; bool activeState = false; +#elif defined(ARDUINO_ARCH_ESP32) + const int pin = 0; + bool activeState = false; + #else const int pin = 12; bool activeState = false; #endif // HID report descriptor using TinyUSB's template -uint8_t const desc_keyboard_report[] = -{ +uint8_t const desc_keyboard_report[] = { TUD_HID_REPORT_DESC_KEYBOARD() }; -uint8_t const desc_mouse_report[] = -{ +uint8_t const desc_mouse_report[] = { TUD_HID_REPORT_DESC_MOUSE() }; -// USB HID object. For ESP32 these values cannot be changed after this declaration -// desc report, desc len, protocol, interval, use out endpoint -Adafruit_USBD_HID usb_keyboard(desc_keyboard_report, sizeof(desc_keyboard_report), HID_ITF_PROTOCOL_KEYBOARD, 2, false); -Adafruit_USBD_HID usb_mouse(desc_mouse_report, sizeof(desc_mouse_report), HID_ITF_PROTOCOL_MOUSE, 2, false); +// USB HID objects +Adafruit_USBD_HID usb_keyboard; +Adafruit_USBD_HID usb_mouse; // the setup function runs once when you press reset or power the board void setup() { - // Notes: following commented-out functions has no affect on ESP32 - // usb_keyboard.setPollInterval(2); - // usb_keyboard.setReportDescriptor(); - // usb_keyboard.setStringDescriptor("TinyUSB HID Composite"); - + // HID Keyboard + usb_keyboard.setPollInterval(2); + usb_keyboard.setBootProtocol(HID_ITF_PROTOCOL_KEYBOARD); + usb_keyboard.setReportDescriptor(desc_keyboard_report, sizeof(desc_keyboard_report)); + usb_keyboard.setStringDescriptor("TinyUSB HID Keyboard"); usb_keyboard.begin(); + + // HID Mouse + usb_mouse.setPollInterval(2); + usb_mouse.setBootProtocol(HID_ITF_PROTOCOL_MOUSE); + usb_mouse.setReportDescriptor(desc_mouse_report, sizeof(desc_mouse_report)); + usb_mouse.setStringDescriptor("TinyUSB HID Keyboard"); usb_mouse.begin(); // Set up button, pullup opposite to active state diff --git a/examples/HID/hid_gamepad/hid_gamepad.ino b/examples/HID/hid_gamepad/hid_gamepad.ino index ee3f1436..84b3289c 100644 --- a/examples/HID/hid_gamepad/hid_gamepad.ino +++ b/examples/HID/hid_gamepad/hid_gamepad.ino @@ -22,14 +22,12 @@ // HID report descriptor using TinyUSB's template // Single Report (no ID) descriptor -uint8_t const desc_hid_report[] = -{ +uint8_t const desc_hid_report[] = { TUD_HID_REPORT_DESC_GAMEPAD() }; -// USB HID object. For ESP32 these values cannot be changed after this declaration -// desc report, desc len, protocol, interval, use out endpoint -Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROTOCOL_NONE, 2, false); +// USB HID object +Adafruit_USBD_HID usb_hid; // Report payload defined in src/class/hid/hid.h // - For Gamepad Button Bit Mask see hid_gamepad_button_bm_t @@ -45,9 +43,9 @@ void setup() Serial.begin(115200); - // Notes: following commented-out functions has no affect on ESP32 - // usb_hid.setPollInterval(2); - // usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); + // Setup HID + usb_hid.setPollInterval(2); + usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); usb_hid.begin(); diff --git a/examples/HID/hid_generic_inout/hid_generic_inout.ino b/examples/HID/hid_generic_inout/hid_generic_inout.ino index 242155e6..b543dd78 100644 --- a/examples/HID/hid_generic_inout/hid_generic_inout.ino +++ b/examples/HID/hid_generic_inout/hid_generic_inout.ino @@ -39,14 +39,12 @@ // HID report descriptor using TinyUSB's template // Generic In Out with 64 bytes report (max) -uint8_t const desc_hid_report[] = -{ +uint8_t const desc_hid_report[] = { TUD_HID_REPORT_DESC_GENERIC_INOUT(64) }; -// USB HID object. For ESP32 these values cannot be changed after this declaration -// desc report, desc len, protocol, interval, use out endpoint -Adafruit_USBD_HID usb_hid(desc_hid_report, sizeof(desc_hid_report), HID_ITF_PROTOCOL_NONE, 2, true); +// USB HID object +Adafruit_USBD_HID usb_hid; // the setup function runs once when you press reset or power the board void setup() @@ -57,10 +55,10 @@ void setup() #endif // Notes: following commented-out functions has no affect on ESP32 - // usb_hid.enableOutEndpoint(true); - // usb_hid.setPollInterval(2); - // usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); - // usb_hid.setStringDescriptor("TinyUSB HID Generic"); + usb_hid.enableOutEndpoint(true); + usb_hid.setPollInterval(2); + usb_hid.setReportDescriptor(desc_hid_report, sizeof(desc_hid_report)); + usb_hid.setStringDescriptor("TinyUSB HID Generic"); usb_hid.setReportCallback(get_report_callback, set_report_callback); usb_hid.begin(); diff --git a/examples/MIDI/midi_test/midi_test.ino b/examples/MIDI/midi_test/midi_test.ino index 4903b97c..ce41970b 100644 --- a/examples/MIDI/midi_test/midi_test.ino +++ b/examples/MIDI/midi_test/midi_test.ino @@ -45,7 +45,7 @@ void setup() pinMode(LED_BUILTIN, OUTPUT); - //usb_midi.setStringDescriptor("TinyUSB MIDI"); + usb_midi.setStringDescriptor("TinyUSB MIDI"); // Initialize MIDI, and listen to all MIDI channels // This will also call usb_midi's begin() diff --git a/examples/Video/video_capture/video_capture.ino b/examples/Video/video_capture/video_capture.ino index db5d5c96..353489b1 100644 --- a/examples/Video/video_capture/video_capture.ino +++ b/examples/Video/video_capture/video_capture.ino @@ -156,6 +156,11 @@ void loop() { tud_video_n_frame_xfer(0, 0, (void*) frame_buffer, FRAME_WIDTH * FRAME_HEIGHT * 16 / 8); } +//--------------------------------------------------------------------+ +// TinyUSB Video Callbacks +//--------------------------------------------------------------------+ +extern "C" { + void tud_video_frame_xfer_complete_cb(uint_fast8_t ctl_idx, uint_fast8_t stm_idx) { (void) ctl_idx; (void) stm_idx; @@ -173,6 +178,8 @@ int tud_video_commit_cb(uint_fast8_t ctl_idx, uint_fast8_t stm_idx, return VIDEO_ERROR_NONE; } +} // extern C + //------------- Helper -------------// static void fill_color_bar(uint8_t* buffer, unsigned start_position) { /* EBU color bars diff --git a/src/arduino/Adafruit_TinyUSB_API.cpp b/src/arduino/Adafruit_TinyUSB_API.cpp index a67a66b3..1195471b 100644 --- a/src/arduino/Adafruit_TinyUSB_API.cpp +++ b/src/arduino/Adafruit_TinyUSB_API.cpp @@ -24,8 +24,7 @@ #include "tusb_option.h" -// ESP32 will use the arduino-esp32 core initialization and Serial -#if CFG_TUD_ENABLED && !defined(ARDUINO_ARCH_ESP32) +#if CFG_TUD_ENABLED #include "Adafruit_TinyUSB.h" #include "Arduino.h" @@ -48,6 +47,7 @@ void TinyUSB_Device_Task(void) { } #endif +#ifndef ARDUINO_ARCH_ESP32 void TinyUSB_Device_FlushCDC(void) { uint8_t const cdc_instance = Adafruit_USBD_CDC::getInstanceCount(); for (uint8_t instance = 0; instance < cdc_instance; instance++) { @@ -88,8 +88,9 @@ __attribute__((used)) int CFG_TUSB_DEBUG_PRINTF(const char *__restrict format, va_end(ap); return len; } -#endif +#endif // CFG_TUSB_DEBUG -} // extern C +#endif // ARDUINO_ARCH_ESP32 +} // extern C #endif diff --git a/src/arduino/Adafruit_USBD_Device.cpp b/src/arduino/Adafruit_USBD_Device.cpp index 98adf91a..f65d59b3 100644 --- a/src/arduino/Adafruit_USBD_Device.cpp +++ b/src/arduino/Adafruit_USBD_Device.cpp @@ -34,10 +34,14 @@ // USB Information can be defined in variant file e.g pins_arduino.h #include "Arduino.h" -// - USB_VID, USB_PID, USB_MANUFACTURER, USB_PRODUCT are defined on most -// core that has built-in support for TinyUSB. Otherwise -// - BOARD_VENDORID, BOARD_PRODUCTID, BOARD_MANUFACTURER, BOARD_NAME are use -// if defined, mostly on mbed core +/* VID, PID, Manufacturer and Product name: + * - For most ports: USB_VID, USB_PID, USB_MANUFACTURER, USB_PRODUCT are + * defined. + * - For ESP32: Default USB_MANUFACTURER is Espressif (instead of Adafruit), + * ARDUINO_BOARD as USB_PRODUCT + * - For mbed core: BOARD_VENDORID, BOARD_PRODUCTID, BOARD_MANUFACTURER, + * BOARD_NAME are defined + */ #ifndef USB_VID #ifdef BOARD_VENDORID @@ -56,16 +60,19 @@ #endif #ifndef USB_MANUFACTURER - #ifdef BOARD_MANUFACTURER #define USB_MANUFACTURER BOARD_MANUFACTURER +#elif defined(ARDUINO_ARCH_ESP32) +#define USB_MANUFACTURER "Espressif Systems" #else #define USB_MANUFACTURER "Adafruit" #endif #endif #ifndef USB_PRODUCT -#ifdef BOARD_NAME +#if defined(ARDUINO_BOARD) +#define USB_PRODUCT ARDUINO_BOARD +#elif defined(BOARD_NAME) #define USB_PRODUCT BOARD_NAME #else #define USB_PRODUCT "Unknown" @@ -84,7 +91,12 @@ enum { STRID_LANGUAGE = 0, STRID_MANUFACTURER, STRID_PRODUCT, STRID_SERIAL }; Adafruit_USBD_Device TinyUSBDevice; -Adafruit_USBD_Device::Adafruit_USBD_Device(void) {} +Adafruit_USBD_Device::Adafruit_USBD_Device(void) { +#if defined(ARDUINO_ARCH_ESP32) && ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE + // auto begin for ESP32 USB OTG Mode with CDC on boot + begin(0); +#endif +} void Adafruit_USBD_Device::setConfigurationBuffer(uint8_t *buf, uint32_t buflen) { @@ -152,36 +164,6 @@ bool Adafruit_USBD_Device::detach(void) { return tud_disconnect(); } bool Adafruit_USBD_Device::attach(void) { return tud_connect(); } -// EPS32 use built-in core descriptor builder. -// Therefore most of descriptors are stubs only -#ifdef ARDUINO_ARCH_ESP32 - -void Adafruit_USBD_Device::clearConfiguration(void) {} - -bool Adafruit_USBD_Device::addInterface(Adafruit_USBD_Interface &itf) { - (void)itf; - return true; -} - -bool Adafruit_USBD_Device::begin(uint8_t rhport) { - (void)rhport; - return true; -} - -uint8_t Adafruit_USBD_Device::getSerialDescriptor(uint16_t *serial_utf16) { - (void)serial_utf16; - return 0; -} - -uint16_t const *Adafruit_USBD_Device::descriptor_string_cb(uint8_t index, - uint16_t langid) { - (void)index; - (void)langid; - return NULL; -} - -#else - void Adafruit_USBD_Device::clearConfiguration(void) { tusb_desc_device_t const desc_dev = {.bLength = sizeof(tusb_desc_device_t), .bDescriptorType = TUSB_DESC_DEVICE, @@ -240,90 +222,6 @@ bool Adafruit_USBD_Device::addInterface(Adafruit_USBD_Interface &itf) { return false; } -#if 0 - uint8_t *desc_end = desc + len; - const char *desc_str = itf.getStringDescriptor(); - - // Parse interface descriptor to update - // - IAD: interface number - // - Interface: number & string descriptor - // - Endpoint: address - while (desc < desc_end) { - switch (tu_desc_type(desc)) { - case TUSB_DESC_INTERFACE_ASSOCIATION: { - tusb_desc_interface_assoc_t *desc_iad = - (tusb_desc_interface_assoc_t *)desc; - desc_iad->bFirstInterface = _itf_count; - break; - } - - case TUSB_DESC_INTERFACE: { - tusb_desc_interface_t *desc_itf = (tusb_desc_interface_t *)desc; - desc_itf->bInterfaceNumber = _itf_count; - -#if CFG_TUD_VIDEO && CFG_TUD_VIDEO_STREAMING - if (TUSB_CLASS_VIDEO == desc_itf->bInterfaceClass) { - desc += tu_desc_len(desc); // next to CS Interface - - if (TUSB_DESC_CS_INTERFACE == tu_desc_type(desc)) { - uint8_t const subtype = desc[2]; - - if (VIDEO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass) { - // Adjust stream interface number in VC Header - if (subtype == VIDEO_CS_ITF_VC_HEADER) { - uint8_t const vs_count = desc[11]; - for (uint8_t i = 0; i < vs_count; i++) { - desc[12 + i] += _itf_count; - } - } - } else if (VIDEO_SUBCLASS_STREAMING == desc_itf->bInterfaceSubClass) { - // Adjust the endpoint address in CS VS Input/Output Header - if (subtype == VIDEO_CS_ITF_VS_INPUT_HEADER) { - desc[6] = 0x80 | _epin_count; - } else if (subtype == VIDEO_CS_ITF_VS_OUTPUT_HEADER) { - desc[6] = _epout_count; - } - } - } - } -#endif - - if (desc_itf->bAlternateSetting == 0) { - _itf_count++; - if (desc_str && (_desc_str_count < STRING_DESCRIPTOR_MAX)) { - _desc_str_arr[_desc_str_count] = desc_str; - desc_itf->iInterface = _desc_str_count; - _desc_str_count++; - - // only assign string index to first interface - desc_str = NULL; - } else { - desc_itf->iInterface = 0; - } - } - - break; - } - - case TUSB_DESC_ENDPOINT: { - tusb_desc_endpoint_t *desc_ep = (tusb_desc_endpoint_t *)desc; - desc_ep->bEndpointAddress |= - (desc_ep->bEndpointAddress & 0x80) ? _epin_count++ : _epout_count++; - break; - } - - default: - break; - } - - if (desc[0] == 0) { - return false; - } - - desc += tu_desc_len(desc); - } -#endif - _desc_cfg_len += len; // Update configuration descriptor @@ -345,10 +243,28 @@ bool Adafruit_USBD_Device::begin(uint8_t rhport) { _desc_device.bDeviceSubClass = MISC_SUBCLASS_COMMON; _desc_device.bDeviceProtocol = MISC_PROTOCOL_IAD; +#if defined(ARDUINO_ARCH_ESP32) +#if ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE + // follow USBCDC cdc descriptor + uint8_t itfnum = allocInterface(2); + uint8_t strid = addStringDescriptor("TinyUSB Serial"); + uint8_t const desc_cdc[TUD_CDC_DESC_LEN] = { + TUD_CDC_DESCRIPTOR(itfnum, strid, 0x85, 64, 0x03, 0x84, 64)}; + + memcpy(_desc_cfg + _desc_cfg_len, desc_cdc, sizeof(desc_cdc)); + _desc_cfg_len += sizeof(desc_cdc); + + // Update configuration descriptor + tusb_desc_configuration_t *config = (tusb_desc_configuration_t *)_desc_cfg; + config->wTotalLength = _desc_cfg_len; + config->bNumInterfaces = _itf_count; +#endif +#else SerialTinyUSB.begin(115200); // Init device hardware and call tusb_init() TinyUSB_Port_InitDevice(rhport); +#endif return true; } @@ -604,6 +520,4 @@ void tud_dfu_runtime_reboot_to_dfu_cb(void) { } #endif -#endif // ESP32 - #endif // CFG_TUD_ENABLED diff --git a/src/arduino/Adafruit_USBD_Device.h b/src/arduino/Adafruit_USBD_Device.h index 5a2c045b..bd7672bf 100644 --- a/src/arduino/Adafruit_USBD_Device.h +++ b/src/arduino/Adafruit_USBD_Device.h @@ -88,7 +88,18 @@ class Adafruit_USBD_Device { } uint8_t allocEndpoint(uint8_t in) { - return in ? (0x80 | _epin_count++) : _epout_count++; + uint8_t ret = in ? (0x80 | _epin_count++) : _epout_count++; +#if defined(ARDUINO_ARCH_ESP32) && ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE + // ESP32 reserves 0x03, 0x84, 0x85 for CDC Serial + if (ret == 0x03) { + ret = _epout_count++; + } else if (ret == 0x84 || ret == 0x85) { + // Note: ESP32 does not have this much of EP IN + _epin_count = 6; + ret = 0x86; + } +#endif + return ret; } //------------- String descriptor -------------// diff --git a/src/arduino/hid/Adafruit_USBD_HID.cpp b/src/arduino/hid/Adafruit_USBD_HID.cpp index 5f8e3165..e7633e84 100644 --- a/src/arduino/hid/Adafruit_USBD_HID.cpp +++ b/src/arduino/hid/Adafruit_USBD_HID.cpp @@ -33,36 +33,7 @@ static Adafruit_USBD_HID *_hid_instances[CFG_TUD_HID] = {0}; uint8_t Adafruit_USBD_HID::_instance_count = 0; -#ifdef ARDUINO_ARCH_ESP32 -static uint16_t hid_load_descriptor(uint8_t *dst, uint8_t *itf) { - // uint8_t str_index = tinyusb_add_string_descriptor("TinyUSB HID"); - - uint8_t const inst_count = Adafruit_USBD_HID::getInstanceCount(); - TU_VERIFY(inst_count > 0, 0); - - Adafruit_USBD_HID *p_hid = _hid_instances[inst_count - 1]; - TU_VERIFY(p_hid); - - uint8_t ep_in = tinyusb_get_free_in_endpoint(); - TU_VERIFY(ep_in != 0); - ep_in |= 0x80; - - uint8_t ep_out = 0; - if (p_hid->isOutEndpointEnabled()) { - ep_out = tinyusb_get_free_out_endpoint(); - TU_VERIFY(ep_out != 0); - } - - uint16_t const desc_len = - p_hid->makeItfDesc(*itf, dst, TUD_HID_INOUT_DESC_LEN, ep_in, ep_out); - - *itf += 1; - return desc_len; -} -#endif - //------------- IMPLEMENTATION -------------// - Adafruit_USBD_HID::Adafruit_USBD_HID(void) : Adafruit_USBD_HID(NULL, 0, HID_ITF_PROTOCOL_NONE, 4, false) {} @@ -81,19 +52,6 @@ Adafruit_USBD_HID::Adafruit_USBD_HID(uint8_t const *desc_report, uint16_t len, _get_report_cb = NULL; _set_report_cb = NULL; - -#ifdef ARDUINO_ARCH_ESP32 - // ESP32 requires setup configuration descriptor within constructor - if (_instance_count >= CFG_TUD_HID) { - return; - } - - _instance = _instance_count++; - _hid_instances[_instance] = this; - - uint16_t const desc_len = getInterfaceDescriptorLen(); - tinyusb_enable_interface(USB_INTERFACE_HID, desc_len, hid_load_descriptor); -#endif } void Adafruit_USBD_HID::setPollInterval(uint8_t interval_ms) { @@ -173,7 +131,7 @@ uint16_t Adafruit_USBD_HID::getInterfaceDescriptor(uint8_t itfnum_deprecated, ep_in = TinyUSBDevice.allocEndpoint(TUSB_DIR_IN); if (_out_endpoint) { - TinyUSBDevice.allocEndpoint(TUSB_DIR_OUT); + ep_out = TinyUSBDevice.allocEndpoint(TUSB_DIR_OUT); } } diff --git a/src/arduino/midi/Adafruit_USBD_MIDI.cpp b/src/arduino/midi/Adafruit_USBD_MIDI.cpp index 764a3b16..d2a5c635 100644 --- a/src/arduino/midi/Adafruit_USBD_MIDI.cpp +++ b/src/arduino/midi/Adafruit_USBD_MIDI.cpp @@ -36,33 +36,9 @@ // TODO multiple instances static Adafruit_USBD_MIDI *_midi_dev = NULL; -#ifdef ARDUINO_ARCH_ESP32 -static uint16_t midi_load_descriptor(uint8_t *dst, uint8_t *itf) { - // uint8_t str_index = tinyusb_add_string_descriptor("TinyUSB HID"); - - uint8_t ep_in = tinyusb_get_free_in_endpoint(); - uint8_t ep_out = tinyusb_get_free_out_endpoint(); - TU_VERIFY(ep_in && ep_out); - ep_in |= 0x80; - - uint16_t desc_len = _midi_dev->getInterfaceDescriptorLen(); - desc_len = _midi_dev->makeItfDesc(*itf, dst, desc_len, ep_in, ep_out); - - *itf += 2; - return desc_len; -} -#endif - Adafruit_USBD_MIDI::Adafruit_USBD_MIDI(uint8_t n_cables) { _n_cables = n_cables; memset(_cable_name_strid, 0, sizeof(_cable_name_strid)); - -#ifdef ARDUINO_ARCH_ESP32 - // ESP32 requires setup configuration descriptor within constructor - _midi_dev = this; - uint16_t const desc_len = getInterfaceDescriptorLen(); - tinyusb_enable_interface(USB_INTERFACE_MIDI, desc_len, midi_load_descriptor); -#endif } void Adafruit_USBD_MIDI::setCables(uint8_t n_cables) { _n_cables = n_cables; } @@ -87,14 +63,16 @@ bool Adafruit_USBD_MIDI::begin(void) { return true; } -uint16_t Adafruit_USBD_MIDI::makeItfDesc(uint8_t itfnum, uint8_t *buf, - uint16_t bufsize, uint8_t ep_in, - uint8_t ep_out) { +uint16_t Adafruit_USBD_MIDI::getInterfaceDescriptor(uint8_t itfnum_deprecated, + uint8_t *buf, + uint16_t bufsize) { + (void)itfnum_deprecated; + uint16_t const desc_len = TUD_MIDI_DESC_HEAD_LEN + TUD_MIDI_DESC_JACK_LEN * _n_cables + 2 * TUD_MIDI_DESC_EP_LEN(_n_cables); - // null buf is for length only + // null buffer is used to get the length of descriptor only if (!buf) { return desc_len; } @@ -103,6 +81,10 @@ uint16_t Adafruit_USBD_MIDI::makeItfDesc(uint8_t itfnum, uint8_t *buf, return 0; } + uint8_t itfnum = TinyUSBDevice.allocInterface(2); + uint8_t ep_in = TinyUSBDevice.allocEndpoint(TUSB_DIR_IN); + uint8_t ep_out = TinyUSBDevice.allocEndpoint(TUSB_DIR_OUT); + uint16_t len = 0; // Header @@ -153,25 +135,6 @@ uint16_t Adafruit_USBD_MIDI::makeItfDesc(uint8_t itfnum, uint8_t *buf, return desc_len; } -uint16_t Adafruit_USBD_MIDI::getInterfaceDescriptor(uint8_t itfnum_deprecated, - uint8_t *buf, - uint16_t bufsize) { - (void)itfnum_deprecated; - - uint8_t itfnum = 0; - uint8_t ep_in = 0; - uint8_t ep_out = 0; - - // null buffer is used to get the length of descriptor only - if (buf) { - itfnum = TinyUSBDevice.allocInterface(2); - ep_in = TinyUSBDevice.allocEndpoint(TUSB_DIR_IN); - ep_out = TinyUSBDevice.allocEndpoint(TUSB_DIR_OUT); - } - - return makeItfDesc(itfnum, buf, bufsize, ep_in, ep_out); -} - int Adafruit_USBD_MIDI::read(void) { uint8_t ch; return tud_midi_stream_read(&ch, 1) ? (int)ch : (-1); diff --git a/src/arduino/midi/Adafruit_USBD_MIDI.h b/src/arduino/midi/Adafruit_USBD_MIDI.h index c04fb27f..0cce3031 100644 --- a/src/arduino/midi/Adafruit_USBD_MIDI.h +++ b/src/arduino/midi/Adafruit_USBD_MIDI.h @@ -63,10 +63,6 @@ class Adafruit_USBD_MIDI : public Stream, public Adafruit_USBD_Interface { virtual uint16_t getInterfaceDescriptor(uint8_t itfnum_deprecated, uint8_t *buf, uint16_t bufsize); - // internal use only - uint16_t makeItfDesc(uint8_t itfnum, uint8_t *buf, uint16_t bufsize, - uint8_t ep_in, uint8_t ep_out); - private: uint8_t _n_cables; uint8_t _cable_name_strid[16]; diff --git a/src/arduino/msc/Adafruit_USBD_MSC.cpp b/src/arduino/msc/Adafruit_USBD_MSC.cpp index 0fc199bd..83dd8832 100644 --- a/src/arduino/msc/Adafruit_USBD_MSC.cpp +++ b/src/arduino/msc/Adafruit_USBD_MSC.cpp @@ -32,48 +32,9 @@ static Adafruit_USBD_MSC *_msc_dev = NULL; -#ifdef ARDUINO_ARCH_ESP32 -static uint16_t msc_load_descriptor(uint8_t *dst, uint8_t *itf) { - // uint8_t str_index = tinyusb_add_string_descriptor("TinyUSB MSC"); - // uint8_t str_index = 0; - - uint8_t ep_in = tinyusb_get_free_in_endpoint(); - uint8_t ep_out = tinyusb_get_free_out_endpoint(); - TU_VERIFY(ep_in && ep_out); - ep_in |= 0x80; - - uint16_t const desc_len = - _msc_dev->makeItfDesc(*itf, dst, TUD_MSC_DESC_LEN, ep_in, ep_out); - *itf += 1; - return desc_len; -} -#endif - Adafruit_USBD_MSC::Adafruit_USBD_MSC(void) { _maxlun = 1; memset(_lun_info, 0, sizeof(_lun_info)); - -#ifdef ARDUINO_ARCH_ESP32 - // ESP32 requires setup configuration descriptor on declaration - _msc_dev = this; - tinyusb_enable_interface(USB_INTERFACE_MSC, TUD_MSC_DESC_LEN, - msc_load_descriptor); -#endif -} - -uint16_t Adafruit_USBD_MSC::makeItfDesc(uint8_t itfnum, uint8_t *buf, - uint16_t bufsize, uint8_t ep_in, - uint8_t ep_out) { - uint8_t const desc[] = { - TUD_MSC_DESCRIPTOR(itfnum, _strid, ep_out, ep_in, EPSIZE)}; - uint16_t const len = sizeof(desc); - - if (bufsize < len) { - return 0; - } - memcpy(buf, desc, len); - - return len; } uint16_t Adafruit_USBD_MSC::getInterfaceDescriptor(uint8_t itfnum_deprecated, @@ -90,7 +51,16 @@ uint16_t Adafruit_USBD_MSC::getInterfaceDescriptor(uint8_t itfnum_deprecated, uint8_t const ep_in = TinyUSBDevice.allocEndpoint(TUSB_DIR_IN); uint8_t const ep_out = TinyUSBDevice.allocEndpoint(TUSB_DIR_OUT); - return makeItfDesc(itfnum, buf, bufsize, ep_in, ep_out); + uint8_t const desc[] = { + TUD_MSC_DESCRIPTOR(itfnum, _strid, ep_out, ep_in, EPSIZE)}; + uint16_t const len = sizeof(desc); + + if (bufsize < len) { + return 0; + } + memcpy(buf, desc, len); + + return len; } void Adafruit_USBD_MSC::setMaxLun(uint8_t maxlun) { _maxlun = maxlun; } diff --git a/src/arduino/msc/Adafruit_USBD_MSC.h b/src/arduino/msc/Adafruit_USBD_MSC.h index e928698b..f2c5fc3d 100644 --- a/src/arduino/msc/Adafruit_USBD_MSC.h +++ b/src/arduino/msc/Adafruit_USBD_MSC.h @@ -86,10 +86,6 @@ class Adafruit_USBD_MSC : public Adafruit_USBD_Interface { virtual uint16_t getInterfaceDescriptor(uint8_t itfnum_deprecated, uint8_t *buf, uint16_t bufsize); - // internal use only - uint16_t makeItfDesc(uint8_t itfnum, uint8_t *buf, uint16_t bufsize, - uint8_t ep_in, uint8_t ep_out); - private: enum { MAX_LUN = 2 }; // TODO make it configurable struct { diff --git a/src/arduino/ports/esp32/tusb_config_esp32.h b/src/arduino/ports/esp32/tusb_config_esp32.h index 1655bb4f..d35d051a 100644 --- a/src/arduino/ports/esp32/tusb_config_esp32.h +++ b/src/arduino/ports/esp32/tusb_config_esp32.h @@ -49,6 +49,13 @@ extern "C" { #error "ESP32 Arduino core version 2.0.8 or later is required" #endif +#ifndef CFG_TUSB_OS +#define CFG_TUSB_OS OPT_OS_FREERTOS +// clang-format off +#define CFG_TUSB_OS_INC_PATH freertos/ +// clang-format on +#endif + #ifndef CFG_TUD_LOG_LEVEL #define CFG_TUD_LOG_LEVEL 2 #endif diff --git a/src/arduino/video/Adafruit_USBD_Video.cpp b/src/arduino/video/Adafruit_USBD_Video.cpp index 34cc5c66..9eda87a7 100644 --- a/src/arduino/video/Adafruit_USBD_Video.cpp +++ b/src/arduino/video/Adafruit_USBD_Video.cpp @@ -30,17 +30,9 @@ #include "Adafruit_USBD_Video.h" -#ifdef ARDUINO_ARCH_ESP32 -// static uint16_t hid_load_descriptor(uint8_t *dst, uint8_t *itf) {} -#endif - Adafruit_USBD_Video::Adafruit_USBD_Video(void) { _vc_id = 0; memset(&_camera_terminal, 0, sizeof(_camera_terminal)); - -#ifdef ARDUINO_ARCH_ESP32 -// tinyusb_enable_interface(USB_INTERFACE_HID, desc_len, hid_load_descriptor); -#endif } bool Adafruit_USBD_Video::addTerminal( diff --git a/src/arduino/webusb/Adafruit_USBD_WebUSB.cpp b/src/arduino/webusb/Adafruit_USBD_WebUSB.cpp index 564ccbda..f0635040 100644 --- a/src/arduino/webusb/Adafruit_USBD_WebUSB.cpp +++ b/src/arduino/webusb/Adafruit_USBD_WebUSB.cpp @@ -122,40 +122,10 @@ TU_VERIFY_STATIC(sizeof(desc_ms_os_20) == MS_OS_20_DESC_LEN, "Incorrect size"); //--------------------------------------------------------------------+ // IMPLEMENTATION //--------------------------------------------------------------------+ - -#ifdef ARDUINO_ARCH_ESP32 -static uint16_t webusb_load_descriptor(uint8_t *dst, uint8_t *itf) { - // uint8_t str_index = tinyusb_add_string_descriptor("TinyUSB MSC"); - - uint8_t ep_in = tinyusb_get_free_in_endpoint(); - uint8_t ep_out = tinyusb_get_free_out_endpoint(); - TU_VERIFY(ep_in && ep_out); - ep_in |= 0x80; - - uint16_t desc_len = _webusb_dev->getInterfaceDescriptorLen(); - desc_len = _webusb_dev->makeItfDesc(*itf, dst, desc_len, ep_in, ep_out); - - *itf += 1; - return desc_len; -} -#endif - Adafruit_USBD_WebUSB::Adafruit_USBD_WebUSB(const void *url) { _connected = false; _url = (const uint8_t *)url; _linestate_cb = NULL; - -#ifdef ARDUINO_ARCH_ESP32 - // ESP32 requires setup configuration descriptor within constructor - - // WebUSB requires USB version at least 2.1 (or 3.x) - USB.usbVersion(0x0210); - - _webusb_dev = this; - uint16_t const desc_len = getInterfaceDescriptorLen(); - tinyusb_enable_interface(USB_INTERFACE_VENDOR, desc_len, - webusb_load_descriptor); -#endif } bool Adafruit_USBD_WebUSB::begin(void) { @@ -179,29 +149,6 @@ void Adafruit_USBD_WebUSB::setLineStateCallback(linestate_callback_t fp) { _linestate_cb = fp; } -uint16_t Adafruit_USBD_WebUSB::makeItfDesc(uint8_t itfnum, uint8_t *buf, - uint16_t bufsize, uint8_t ep_in, - uint8_t ep_out) { - uint8_t desc[] = { - TUD_VENDOR_DESCRIPTOR(itfnum, _strid, ep_out, ep_in, EPSIZE)}; - uint16_t const len = sizeof(desc); - - // null buffer for length only - if (buf) { - if (bufsize < len) { - return 0; - } - - memcpy(buf, desc, len); - - // update the bFirstInterface in MS OS 2.0 descriptor - // that is binded to WinUSB driver - desc_ms_os_20[0x0a + 0x08 + 4] = itfnum; - } - - return len; -} - uint16_t Adafruit_USBD_WebUSB::getInterfaceDescriptor(uint8_t itfnum_deprecated, uint8_t *buf, uint16_t bufsize) { @@ -212,11 +159,25 @@ uint16_t Adafruit_USBD_WebUSB::getInterfaceDescriptor(uint8_t itfnum_deprecated, } uint8_t const itfnum = TinyUSBDevice.allocInterface(1); - ; uint8_t const ep_in = TinyUSBDevice.allocEndpoint(TUSB_DIR_IN); uint8_t const ep_out = TinyUSBDevice.allocEndpoint(TUSB_DIR_OUT); - return makeItfDesc(itfnum, buf, bufsize, ep_in, ep_out); + uint8_t desc[] = { + TUD_VENDOR_DESCRIPTOR(itfnum, _strid, ep_out, ep_in, EPSIZE)}; + uint16_t const len = sizeof(desc); + + // null buffer for length only + if (bufsize < len) { + return 0; + } + + memcpy(buf, desc, len); + + // update the bFirstInterface in MS OS 2.0 descriptor + // that is bound to WinUSB driver + desc_ms_os_20[0x0a + 0x08 + 4] = itfnum; + + return len; } bool Adafruit_USBD_WebUSB::connected(void) { diff --git a/src/arduino/webusb/Adafruit_USBD_WebUSB.h b/src/arduino/webusb/Adafruit_USBD_WebUSB.h index d9ed73de..86d5b53e 100644 --- a/src/arduino/webusb/Adafruit_USBD_WebUSB.h +++ b/src/arduino/webusb/Adafruit_USBD_WebUSB.h @@ -68,10 +68,6 @@ class Adafruit_USBD_WebUSB : public Stream, public Adafruit_USBD_Interface { virtual uint16_t getInterfaceDescriptor(uint8_t itfnum_deprecated, uint8_t *buf, uint16_t bufsize); - // internal use only - uint16_t makeItfDesc(uint8_t itfnum, uint8_t *buf, uint16_t bufsize, - uint8_t ep_in, uint8_t ep_out); - private: bool _connected; const uint8_t *_url; diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c index 773ff5c8..39c0666e 100644 --- a/src/class/cdc/cdc_host.c +++ b/src/class/cdc/cdc_host.c @@ -1377,7 +1377,7 @@ static inline bool ch34x_control_in(cdch_interface_t* p_cdc, uint8_t request, ui complete_cb, user_data); } -static bool ch34x_write_reg(cdch_interface_t* p_cdc, uint16_t reg, uint16_t reg_value, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +static inline bool ch34x_write_reg(cdch_interface_t* p_cdc, uint16_t reg, uint16_t reg_value, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return ch34x_control_out(p_cdc, CH34X_REQ_WRITE_REG, reg, reg_value, complete_cb, user_data); } @@ -1390,7 +1390,7 @@ static bool ch34x_write_reg(cdch_interface_t* p_cdc, uint16_t reg, uint16_t reg_ static bool ch34x_write_reg_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { uint16_t const div_ps = ch34x_get_divisor_prescaler(baudrate); - TU_VERIFY(div_ps != 0); + TU_VERIFY(div_ps); TU_ASSERT(ch34x_write_reg(p_cdc, CH34X_REG16_DIVISOR_PRESCALER, div_ps, complete_cb, user_data)); return true; @@ -1411,7 +1411,7 @@ static bool ch34x_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, ui p_cdc->requested_line_coding.data_bits = data_bits; uint8_t const lcr = ch34x_get_lcr(stop_bits, parity, data_bits); - TU_VERIFY(lcr != 0); + TU_VERIFY(lcr); TU_ASSERT (ch34x_control_out(p_cdc, CH34X_REQ_WRITE_REG, CH32X_REG16_LCR2_LCR, lcr, complete_cb ? ch34x_control_complete : NULL, user_data)); return true; @@ -1427,6 +1427,7 @@ static bool ch34x_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, } static void ch34x_set_line_coding_stage1_complete(tuh_xfer_t* xfer) { + // CH34x only has 1 interface and use wIndex as payload and not for bInterfaceNumber uint8_t const itf_num = 0; uint8_t const idx = tuh_cdc_itf_get_index(xfer->daddr, itf_num); cdch_interface_t* p_cdc = get_itf(idx); @@ -1475,7 +1476,7 @@ static bool ch34x_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t con // update transfer result, user_data is expected to point to xfer_result_t if (user_data) { - user_data = result; + *((xfer_result_t*) user_data) = result; } } @@ -1545,8 +1546,7 @@ static void ch34x_process_config(tuh_xfer_t* xfer) { uintptr_t const state = xfer->user_data; uint8_t buffer[2]; // TODO remove TU_ASSERT (p_cdc,); - - // TODO check xfer->result + TU_ASSERT (xfer->result == XFER_RESULT_SUCCESS,); switch (state) { case CONFIG_CH34X_READ_VERSION: @@ -1563,9 +1563,9 @@ static void ch34x_process_config(tuh_xfer_t* xfer) { // init CH34x with line coding cdc_line_coding_t const line_coding = CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X; uint16_t const div_ps = ch34x_get_divisor_prescaler(line_coding.bit_rate); - TU_ASSERT(div_ps != 0, ); + TU_ASSERT(div_ps, ); uint8_t const lcr = ch34x_get_lcr(line_coding.stop_bits, line_coding.parity, line_coding.data_bits); - TU_ASSERT(lcr != 0, ); + TU_ASSERT(lcr, ); TU_ASSERT (ch34x_control_out(p_cdc, CH34X_REQ_SERIAL_INIT, tu_u16(lcr, 0x9c), div_ps, ch34x_process_config, CONFIG_CH34X_SPECIAL_REG_WRITE),); break; @@ -1605,7 +1605,7 @@ static uint16_t ch34x_get_divisor_prescaler(uint32_t baval) { uint8_t b; uint32_t c; - TU_VERIFY(baval != 0, 0); + TU_VERIFY(baval != 0 && baval <= 2000000, 0); switch (baval) { case 921600: a = 0xf3; @@ -1659,7 +1659,7 @@ static uint8_t ch34x_get_lcr(uint8_t stop_bits, uint8_t parity, uint8_t data_bit break; case CDC_LINE_CODING_PARITY_ODD: - lcr |= CH34X_LCR_ENABLE_PAR; + lcr |= CH34X_LCR_ENABLE_PAR; break; case CDC_LINE_CODING_PARITY_EVEN: diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c new file mode 100644 index 00000000..cddbb1e0 --- /dev/null +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -0,0 +1,1189 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 William D. Jones + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * Copyright (c) 2020 Jan Duempelmann + * Copyright (c) 2020 Reinhard Panhuber + * + * 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. + */ + +#include "tusb_option.h" + +#if CFG_TUD_ENABLED && defined(TUP_USBIP_DWC2) + +#include "device/dcd.h" +#include "dwc2_type.h" + +// Following symbols must be defined by port header +// - _dwc2_controller[]: array of controllers +// - DWC2_EP_MAX: largest EP counts of all controllers +// - dwc2_phy_init/dwc2_phy_update: phy init called before and after core reset +// - dwc2_dcd_int_enable/dwc2_dcd_int_disable +// - dwc2_remote_wakeup_delay + +#if defined(TUP_USBIP_DWC2_STM32) + #include "dwc2_stm32.h" +#elif TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3) + #include "dwc2_esp32.h" +#elif TU_CHECK_MCU(OPT_MCU_GD32VF103) + #include "dwc2_gd32.h" +#elif TU_CHECK_MCU(OPT_MCU_BCM2711, OPT_MCU_BCM2835, OPT_MCU_BCM2837) + #include "dwc2_bcm.h" +#elif TU_CHECK_MCU(OPT_MCU_EFM32GG) + #include "dwc2_efm32.h" +#elif TU_CHECK_MCU(OPT_MCU_XMC4000) + #include "dwc2_xmc.h" +#else + #error "Unsupported MCUs" +#endif + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM +//--------------------------------------------------------------------+ + +// DWC2 registers +#define DWC2_REG(_port) ((dwc2_regs_t*) _dwc2_controller[_port].reg_base) + +// Debug level for DWC2 +#define DWC2_DEBUG 2 + +#ifndef dcache_clean +#define dcache_clean(_addr, _size) +#endif + +#ifndef dcache_invalidate +#define dcache_invalidate(_addr, _size) +#endif + +#ifndef dcache_clean_invalidate +#define dcache_clean_invalidate(_addr, _size) +#endif + +static TU_ATTR_ALIGNED(4) uint32_t _setup_packet[2]; + +typedef struct { + uint8_t* buffer; + tu_fifo_t* ff; + uint16_t total_len; + uint16_t max_size; + uint8_t interval; +} xfer_ctl_t; + +static xfer_ctl_t xfer_status[DWC2_EP_MAX][2]; +#define XFER_CTL_BASE(_ep, _dir) (&xfer_status[_ep][_dir]) + +// EP0 transfers are limited to 1 packet - larger sizes has to be split +static uint16_t ep0_pending[2]; // Index determines direction as tusb_dir_t type + +// TX FIFO RAM allocation so far in words - RX FIFO size is readily available from dwc2->grxfsiz +static uint16_t _allocated_fifo_words_tx; // TX FIFO size in words (IN EPs) +static bool _out_ep_closed; // Flag to check if RX FIFO size needs an update (reduce its size) + +// SOF enabling flag - required for SOF to not get disabled in ISR when SOF was enabled by +static bool _sof_en; + +// Calculate the RX FIFO size according to recommendations from reference manual +static inline uint16_t calc_grxfsiz(uint16_t max_ep_size, uint8_t ep_count) { + return 15 + 2 * (max_ep_size / 4) + 2 * ep_count; +} + +static void update_grxfsiz(uint8_t rhport) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + uint8_t const ep_count = _dwc2_controller[rhport].ep_count; + + // Determine largest EP size for RX FIFO + uint16_t max_epsize = 0; + for (uint8_t epnum = 0; epnum < ep_count; epnum++) { + max_epsize = tu_max16(max_epsize, xfer_status[epnum][TUSB_DIR_OUT].max_size); + } + + // Update size of RX FIFO + dwc2->grxfsiz = calc_grxfsiz(max_epsize, ep_count); +} + +// Start of Bus Reset +static void bus_reset(uint8_t rhport) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + uint8_t const ep_count = _dwc2_controller[rhport].ep_count; + + tu_memclr(xfer_status, sizeof(xfer_status)); + _out_ep_closed = false; + + _sof_en = false; + + // clear device address + dwc2->dcfg &= ~DCFG_DAD_Msk; + + // 1. NAK for all OUT endpoints + for (uint8_t n = 0; n < ep_count; n++) { + dwc2->epout[n].doepctl |= DOEPCTL_SNAK; + } + + // 2. Set up interrupt mask + dwc2->daintmsk = TU_BIT(DAINTMSK_OEPM_Pos) | TU_BIT(DAINTMSK_IEPM_Pos); + dwc2->doepmsk = DOEPMSK_STUPM | DOEPMSK_XFRCM; + dwc2->diepmsk = DIEPMSK_TOM | DIEPMSK_XFRCM; + + // "USB Data FIFOs" section in reference manual + // Peripheral FIFO architecture + // + // The FIFO is split up in a lower part where the RX FIFO is located and an upper part where the TX FIFOs start. + // We do this to allow the RX FIFO to grow dynamically which is possible since the free space is located + // between the RX and TX FIFOs. This is required by ISO OUT EPs which need a bigger FIFO than the standard + // configuration done below. + // + // Dynamically FIFO sizes are of interest only for ISO EPs since all others are usually not opened and closed. + // All EPs other than ISO are opened as soon as the driver starts up i.e. when the host sends a + // configure interface command. Hence, all IN EPs other the ISO will be located at the top. IN ISO EPs are usually + // opened when the host sends an additional command: setInterface. At this point in time + // the ISO EP will be located next to the free space and can change its size. In case more IN EPs change its size + // an additional memory + // + // --------------- 320 or 1024 ( 1280 or 4096 bytes ) + // | IN FIFO 0 | + // --------------- (320 or 1024) - 16 + // | IN FIFO 1 | + // --------------- (320 or 1024) - 16 - x + // | . . . . | + // --------------- (320 or 1024) - 16 - x - y - ... - z + // | IN FIFO MAX | + // --------------- + // | FREE | + // --------------- GRXFSIZ + // | OUT FIFO | + // | ( Shared ) | + // --------------- 0 + // + // According to "FIFO RAM allocation" section in RM, FIFO RAM are allocated as follows (each word 32-bits): + // - Each EP IN needs at least max packet size, 16 words is sufficient for EP0 IN + // + // - All EP OUT shared a unique OUT FIFO which uses + // - 13 for setup packets + control words (up to 3 setup packets). + // - 1 for global NAK (not required/used here). + // - Largest-EPsize / 4 + 1. ( FS: 64 bytes, HS: 512 bytes). Recommended is "2 x (Largest-EPsize/4) + 1" + // - 2 for each used OUT endpoint + // + // Therefore GRXFSIZ = 13 + 1 + 1 + 2 x (Largest-EPsize/4) + 2 x EPOUTnum + // - FullSpeed (64 Bytes ): GRXFSIZ = 15 + 2 x 16 + 2 x ep_count = 47 + 2 x ep_count + // - Highspeed (512 bytes): GRXFSIZ = 15 + 2 x 128 + 2 x ep_count = 271 + 2 x ep_count + // + // NOTE: Largest-EPsize & EPOUTnum is actual used endpoints in configuration. Since DCD has no knowledge + // of the overall picture yet. We will use the worst scenario: largest possible + ep_count + // + // For Isochronous, largest EP size can be 1023/1024 for FS/HS respectively. In addition if multiple ISO + // are enabled at least "2 x (Largest-EPsize/4) + 1" are recommended. Maybe provide a macro for application to + // overwrite this. + + // EP0 out max is 64 + dwc2->grxfsiz = calc_grxfsiz(64, ep_count); + + // Setup the control endpoint 0 + _allocated_fifo_words_tx = 16; + + // Control IN uses FIFO 0 with 64 bytes ( 16 32-bit word ) + dwc2->dieptxf0 = (16 << DIEPTXF0_TX0FD_Pos) | (_dwc2_controller[rhport].ep_fifo_size / 4 - _allocated_fifo_words_tx); + + // Fixed control EP0 size to 64 bytes + dwc2->epin[0].diepctl &= ~(0x03 << DIEPCTL_MPSIZ_Pos); + xfer_status[0][TUSB_DIR_OUT].max_size = 64; + xfer_status[0][TUSB_DIR_IN].max_size = 64; + + dwc2->epout[0].doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); + + dwc2->gintmsk |= GINTMSK_OEPINT | GINTMSK_IEPINT; +} + +static void edpt_schedule_packets(uint8_t rhport, uint8_t const epnum, uint8_t const dir, uint16_t const num_packets, + uint16_t total_bytes) { + (void) rhport; + + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + + // EP0 is limited to one packet each xfer + // We use multiple transaction of xfer->max_size length to get a whole transfer done + if (epnum == 0) { + xfer_ctl_t* const xfer = XFER_CTL_BASE(epnum, dir); + total_bytes = tu_min16(ep0_pending[dir], xfer->max_size); + ep0_pending[dir] -= total_bytes; + } + + // IN and OUT endpoint xfers are interrupt-driven, we just schedule them here. + if (dir == TUSB_DIR_IN) { + dwc2_epin_t* epin = dwc2->epin; + + // A full IN transfer (multiple packets, possibly) triggers XFRC. + epin[epnum].dieptsiz = (num_packets << DIEPTSIZ_PKTCNT_Pos) | + ((total_bytes << DIEPTSIZ_XFRSIZ_Pos) & DIEPTSIZ_XFRSIZ_Msk); + + epin[epnum].diepctl |= DIEPCTL_EPENA | DIEPCTL_CNAK; + + // For ISO endpoint set correct odd/even bit for next frame. + if ((epin[epnum].diepctl & DIEPCTL_EPTYP) == DIEPCTL_EPTYP_0 && (XFER_CTL_BASE(epnum, dir))->interval == 1) { + // Take odd/even bit from frame counter. + uint32_t const odd_frame_now = (dwc2->dsts & (1u << DSTS_FNSOF_Pos)); + epin[epnum].diepctl |= (odd_frame_now ? DIEPCTL_SD0PID_SEVNFRM_Msk : DIEPCTL_SODDFRM_Msk); + } + // Enable fifo empty interrupt only if there are something to put in the fifo. + if (total_bytes != 0) { + dwc2->diepempmsk |= (1 << epnum); + } + } else { + dwc2_epout_t* epout = dwc2->epout; + + // A full OUT transfer (multiple packets, possibly) triggers XFRC. + epout[epnum].doeptsiz &= ~(DOEPTSIZ_PKTCNT_Msk | DOEPTSIZ_XFRSIZ); + epout[epnum].doeptsiz |= (num_packets << DOEPTSIZ_PKTCNT_Pos) | + ((total_bytes << DOEPTSIZ_XFRSIZ_Pos) & DOEPTSIZ_XFRSIZ_Msk); + + epout[epnum].doepctl |= DOEPCTL_EPENA | DOEPCTL_CNAK; + if ((epout[epnum].doepctl & DOEPCTL_EPTYP) == DOEPCTL_EPTYP_0 && + XFER_CTL_BASE(epnum, dir)->interval == 1) { + // Take odd/even bit from frame counter. + uint32_t const odd_frame_now = (dwc2->dsts & (1u << DSTS_FNSOF_Pos)); + epout[epnum].doepctl |= (odd_frame_now ? DOEPCTL_SD0PID_SEVNFRM_Msk : DOEPCTL_SODDFRM_Msk); + } + } +} + +/*------------------------------------------------------------------*/ +/* Controller API + *------------------------------------------------------------------*/ +#if CFG_TUSB_DEBUG >= DWC2_DEBUG + +void print_dwc2_info(dwc2_regs_t* dwc2) { + // print guid, gsnpsid, ghwcfg1, ghwcfg2, ghwcfg3, ghwcfg4 + // use dwc2_info.py/md for bit-field value and comparison with other ports + volatile uint32_t const* p = (volatile uint32_t const*) &dwc2->guid; + TU_LOG(DWC2_DEBUG, "guid, gsnpsid, ghwcfg1, ghwcfg2, ghwcfg3, ghwcfg4\r\n"); + for (size_t i = 0; i < 5; i++) { + TU_LOG(DWC2_DEBUG, "0x%08lX, ", p[i]); + } + TU_LOG(DWC2_DEBUG, "0x%08lX\r\n", p[5]); +} + +#endif + +static void reset_core(dwc2_regs_t* dwc2) { + // reset core + dwc2->grstctl |= GRSTCTL_CSRST; + + // wait for reset bit is cleared + // TODO version 4.20a should wait for RESET DONE mask + while (dwc2->grstctl & GRSTCTL_CSRST) {} + + // wait for AHB master IDLE + while (!(dwc2->grstctl & GRSTCTL_AHBIDL)) {} + + // wait for device mode ? +} + +static bool phy_hs_supported(dwc2_regs_t* dwc2) { + // note: esp32 incorrect report its hs_phy_type as utmi +#if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3) + return false; +#else + return TUD_OPT_HIGH_SPEED && dwc2->ghwcfg2_bm.hs_phy_type != HS_PHY_TYPE_NONE; +#endif +} + +static void phy_fs_init(dwc2_regs_t* dwc2) { + TU_LOG(DWC2_DEBUG, "Fullspeed PHY init\r\n"); + + // Select FS PHY + dwc2->gusbcfg |= GUSBCFG_PHYSEL; + + // MCU specific PHY init before reset + dwc2_phy_init(dwc2, HS_PHY_TYPE_NONE); + + // Reset core after selecting PHY + reset_core(dwc2); + + // USB turnaround time is critical for certification where long cables and 5-Hubs are used. + // So if you need the AHB to run at less than 30 MHz, and if USB turnaround time is not critical, + // these bits can be programmed to a larger value. Default is 5 + dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_TRDT_Msk) | (5u << GUSBCFG_TRDT_Pos); + + // MCU specific PHY update post reset + dwc2_phy_update(dwc2, HS_PHY_TYPE_NONE); + + // set max speed + dwc2->dcfg = (dwc2->dcfg & ~DCFG_DSPD_Msk) | (DCFG_DSPD_FS << DCFG_DSPD_Pos); +} + +static void phy_hs_init(dwc2_regs_t* dwc2) { + uint32_t gusbcfg = dwc2->gusbcfg; + + // De-select FS PHY + gusbcfg &= ~GUSBCFG_PHYSEL; + + if (dwc2->ghwcfg2_bm.hs_phy_type == HS_PHY_TYPE_ULPI) { + TU_LOG(DWC2_DEBUG, "Highspeed ULPI PHY init\r\n"); + + // Select ULPI + gusbcfg |= GUSBCFG_ULPI_UTMI_SEL; + + // ULPI 8-bit interface, single data rate + gusbcfg &= ~(GUSBCFG_PHYIF16 | GUSBCFG_DDRSEL); + + // default internal VBUS Indicator and Drive + gusbcfg &= ~(GUSBCFG_ULPIEVBUSD | GUSBCFG_ULPIEVBUSI); + + // Disable FS/LS ULPI + gusbcfg &= ~(GUSBCFG_ULPIFSLS | GUSBCFG_ULPICSM); + } else { + TU_LOG(DWC2_DEBUG, "Highspeed UTMI+ PHY init\r\n"); + + // Select UTMI+ with 8-bit interface + gusbcfg &= ~(GUSBCFG_ULPI_UTMI_SEL | GUSBCFG_PHYIF16); + + // Set 16-bit interface if supported + if (dwc2->ghwcfg4_bm.utmi_phy_data_width) gusbcfg |= GUSBCFG_PHYIF16; + } + + // Apply config + dwc2->gusbcfg = gusbcfg; + + // mcu specific phy init + dwc2_phy_init(dwc2, dwc2->ghwcfg2_bm.hs_phy_type); + + // Reset core after selecting PHY + reset_core(dwc2); + + // Set turn-around, must after core reset otherwise it will be clear + // - 9 if using 8-bit PHY interface + // - 5 if using 16-bit PHY interface + gusbcfg &= ~GUSBCFG_TRDT_Msk; + gusbcfg |= (dwc2->ghwcfg4_bm.utmi_phy_data_width ? 5u : 9u) << GUSBCFG_TRDT_Pos; + dwc2->gusbcfg = gusbcfg; + + // MCU specific PHY update post reset + dwc2_phy_update(dwc2, dwc2->ghwcfg2_bm.hs_phy_type); + + // Set max speed + uint32_t dcfg = dwc2->dcfg; + dcfg &= ~DCFG_DSPD_Msk; + dcfg |= DCFG_DSPD_HS << DCFG_DSPD_Pos; + + // XCVRDLY: transceiver delay between xcvr_sel and txvalid during device chirp is required + // when using with some PHYs such as USB334x (USB3341, USB3343, USB3346, USB3347) + if (dwc2->ghwcfg2_bm.hs_phy_type == HS_PHY_TYPE_ULPI) dcfg |= DCFG_XCVRDLY; + + dwc2->dcfg = dcfg; +} + +static bool check_dwc2(dwc2_regs_t* dwc2) { +#if CFG_TUSB_DEBUG >= DWC2_DEBUG + print_dwc2_info(dwc2); +#endif + + // For some reasons: GD32VF103 snpsid and all hwcfg register are always zero (skip it) + (void) dwc2; +#if !TU_CHECK_MCU(OPT_MCU_GD32VF103) + uint32_t const gsnpsid = dwc2->gsnpsid & GSNPSID_ID_MASK; + TU_ASSERT(gsnpsid == DWC2_OTG_ID || gsnpsid == DWC2_FS_IOT_ID || gsnpsid == DWC2_HS_IOT_ID); +#endif + + return true; +} + +void dcd_init(uint8_t rhport) { + // Programming model begins in the last section of the chapter on the USB + // peripheral in each Reference Manual. + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + + // Check Synopsys ID register, failed if controller clock/power is not enabled + if (!check_dwc2(dwc2)) return; + dcd_disconnect(rhport); + + // max number of endpoints & total_fifo_size are: + // hw_cfg2->num_dev_ep, hw_cfg2->total_fifo_size + + if (phy_hs_supported(dwc2)) { + phy_hs_init(dwc2); // Highspeed + } else { + phy_fs_init(dwc2); // core does not support highspeed or hs phy is not present + } + + // Restart PHY clock + dwc2->pcgctl &= ~(PCGCTL_STOPPCLK | PCGCTL_GATEHCLK | PCGCTL_PWRCLMP | PCGCTL_RSTPDWNMODULE); + + /* Set HS/FS Timeout Calibration to 7 (max available value). + * The number of PHY clocks that the application programs in + * this field is added to the high/full speed interpacket timeout + * duration in the core to account for any additional delays + * introduced by the PHY. This can be required, because the delay + * introduced by the PHY in generating the linestate condition + * can vary from one PHY to another. + */ + dwc2->gusbcfg |= (7ul << GUSBCFG_TOCAL_Pos); + + // Force device mode + dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_FHMOD) | GUSBCFG_FDMOD; + + // Clear A override, force B Valid + dwc2->gotgctl = (dwc2->gotgctl & ~GOTGCTL_AVALOEN) | GOTGCTL_BVALOEN | GOTGCTL_BVALOVAL; + + // If USB host misbehaves during status portion of control xfer + // (non zero-length packet), send STALL back and discard. + dwc2->dcfg |= DCFG_NZLSOHSK; + + // flush all TX fifo and wait for it cleared + dwc2->grstctl = GRSTCTL_TXFFLSH | (0x10u << GRSTCTL_TXFNUM_Pos); + while (dwc2->grstctl & GRSTCTL_TXFFLSH_Msk) {} + + // flush RX fifo and wait for it cleared + dwc2->grstctl = GRSTCTL_RXFFLSH; + while (dwc2->grstctl & GRSTCTL_RXFFLSH_Msk) {} + + // Clear all interrupts + uint32_t int_mask = dwc2->gintsts; + dwc2->gintsts |= int_mask; + int_mask = dwc2->gotgint; + dwc2->gotgint |= int_mask; + + // Required as part of core initialization. + // TODO: How should mode mismatch be handled? It will cause + // the core to stop working/require reset. + dwc2->gintmsk = GINTMSK_OTGINT | GINTMSK_MMISM | GINTMSK_RXFLVLM | + GINTMSK_USBSUSPM | GINTMSK_USBRST | GINTMSK_ENUMDNEM | GINTMSK_WUIM; + + // Enable global interrupt + dwc2->gahbcfg |= GAHBCFG_GINT; + + // make sure we are in device mode +// TU_ASSERT(!(dwc2->gintsts & GINTSTS_CMOD), ); + +// TU_LOG_HEX(DWC2_DEBUG, dwc2->gotgctl); +// TU_LOG_HEX(DWC2_DEBUG, dwc2->gusbcfg); +// TU_LOG_HEX(DWC2_DEBUG, dwc2->dcfg); +// TU_LOG_HEX(DWC2_DEBUG, dwc2->gahbcfg); + + dcd_connect(rhport); +} + +void dcd_int_enable(uint8_t rhport) { + dwc2_dcd_int_enable(rhport); +} + +void dcd_int_disable(uint8_t rhport) { + dwc2_dcd_int_disable(rhport); +} + +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + dwc2->dcfg = (dwc2->dcfg & ~DCFG_DAD_Msk) | (dev_addr << DCFG_DAD_Pos); + + // Response with status after changing device address + dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); +} + +void dcd_remote_wakeup(uint8_t rhport) { + (void) rhport; + + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + + // set remote wakeup + dwc2->dctl |= DCTL_RWUSIG; + + // enable SOF to detect bus resume + dwc2->gintsts = GINTSTS_SOF; + dwc2->gintmsk |= GINTMSK_SOFM; + + // Per specs: remote wakeup signal bit must be clear within 1-15ms + dwc2_remote_wakeup_delay(); + + dwc2->dctl &= ~DCTL_RWUSIG; +} + +void dcd_connect(uint8_t rhport) { + (void) rhport; + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + dwc2->dctl &= ~DCTL_SDIS; +} + +void dcd_disconnect(uint8_t rhport) { + (void) rhport; + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + dwc2->dctl |= DCTL_SDIS; +} + +// Be advised: audio, video and possibly other iso-ep classes use dcd_sof_enable() to enable/disable its corresponding ISR on purpose! +void dcd_sof_enable(uint8_t rhport, bool en) { + (void) rhport; + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + + _sof_en = en; + + if (en) { + dwc2->gintsts = GINTSTS_SOF; + dwc2->gintmsk |= GINTMSK_SOFM; + } else { + dwc2->gintmsk &= ~GINTMSK_SOFM; + } +} + +/*------------------------------------------------------------------*/ +/* DCD Endpoint port + *------------------------------------------------------------------*/ + +bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_edpt) { + (void) rhport; + + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + uint8_t const ep_count = _dwc2_controller[rhport].ep_count; + + uint8_t const epnum = tu_edpt_number(desc_edpt->bEndpointAddress); + uint8_t const dir = tu_edpt_dir(desc_edpt->bEndpointAddress); + + TU_ASSERT(epnum < ep_count); + + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, dir); + xfer->max_size = tu_edpt_packet_size(desc_edpt); + xfer->interval = desc_edpt->bInterval; + + uint16_t const fifo_size = tu_div_ceil(xfer->max_size, 4); + + if (dir == TUSB_DIR_OUT) { + // Calculate required size of RX FIFO + uint16_t const sz = calc_grxfsiz(4 * fifo_size, ep_count); + + // If size_rx needs to be extended check if possible and if so enlarge it + if (dwc2->grxfsiz < sz) { + TU_ASSERT(sz + _allocated_fifo_words_tx <= _dwc2_controller[rhport].ep_fifo_size / 4); + + // Enlarge RX FIFO + dwc2->grxfsiz = sz; + } + + dwc2->epout[epnum].doepctl |= (1 << DOEPCTL_USBAEP_Pos) | + (desc_edpt->bmAttributes.xfer << DOEPCTL_EPTYP_Pos) | + (desc_edpt->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS ? DOEPCTL_SD0PID_SEVNFRM : 0) | + (xfer->max_size << DOEPCTL_MPSIZ_Pos); + + dwc2->daintmsk |= TU_BIT(DAINTMSK_OEPM_Pos + epnum); + } else { + // "USB Data FIFOs" section in reference manual + // Peripheral FIFO architecture + // + // --------------- 320 or 1024 ( 1280 or 4096 bytes ) + // | IN FIFO 0 | + // --------------- (320 or 1024) - 16 + // | IN FIFO 1 | + // --------------- (320 or 1024) - 16 - x + // | . . . . | + // --------------- (320 or 1024) - 16 - x - y - ... - z + // | IN FIFO MAX | + // --------------- + // | FREE | + // --------------- GRXFSIZ + // | OUT FIFO | + // | ( Shared ) | + // --------------- 0 + // + // In FIFO is allocated by following rules: + // - IN EP 1 gets FIFO 1, IN EP "n" gets FIFO "n". + + // Check if free space is available + TU_ASSERT(_allocated_fifo_words_tx + fifo_size + dwc2->grxfsiz <= _dwc2_controller[rhport].ep_fifo_size / 4); + + _allocated_fifo_words_tx += fifo_size; + + TU_LOG(DWC2_DEBUG, " Allocated %u bytes at offset %lu", fifo_size * 4, + _dwc2_controller[rhport].ep_fifo_size - _allocated_fifo_words_tx * 4); + + // DIEPTXF starts at FIFO #1. + // Both TXFD and TXSA are in unit of 32-bit words. + dwc2->dieptxf[epnum - 1] = (fifo_size << DIEPTXF_INEPTXFD_Pos) | + (_dwc2_controller[rhport].ep_fifo_size / 4 - _allocated_fifo_words_tx); + + dwc2->epin[epnum].diepctl |= (1 << DIEPCTL_USBAEP_Pos) | + (epnum << DIEPCTL_TXFNUM_Pos) | + (desc_edpt->bmAttributes.xfer << DIEPCTL_EPTYP_Pos) | + (desc_edpt->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS ? DIEPCTL_SD0PID_SEVNFRM : 0) | + (xfer->max_size << DIEPCTL_MPSIZ_Pos); + + dwc2->daintmsk |= (1 << (DAINTMSK_IEPM_Pos + epnum)); + } + + return true; +} + +// Close all non-control endpoints, cancel all pending transfers if any. +void dcd_edpt_close_all(uint8_t rhport) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + uint8_t const ep_count = _dwc2_controller[rhport].ep_count; + + // Disable non-control interrupt + dwc2->daintmsk = (1 << DAINTMSK_OEPM_Pos) | (1 << DAINTMSK_IEPM_Pos); + + for (uint8_t n = 1; n < ep_count; n++) { + // disable OUT endpoint + dwc2->epout[n].doepctl = 0; + xfer_status[n][TUSB_DIR_OUT].max_size = 0; + + // disable IN endpoint + dwc2->epin[n].diepctl = 0; + xfer_status[n][TUSB_DIR_IN].max_size = 0; + } + + // reset allocated fifo IN + _allocated_fifo_words_tx = 16; +} + +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) { + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, dir); + xfer->buffer = buffer; + xfer->ff = NULL; + xfer->total_len = total_bytes; + + // EP0 can only handle one packet + if (epnum == 0) { + ep0_pending[dir] = total_bytes; + + // Schedule the first transaction for EP0 transfer + edpt_schedule_packets(rhport, epnum, dir, 1, ep0_pending[dir]); + } else { + uint16_t num_packets = (total_bytes / xfer->max_size); + uint16_t const short_packet_size = total_bytes % xfer->max_size; + + // Zero-size packet is special case. + if ((short_packet_size > 0) || (total_bytes == 0)) num_packets++; + + // Schedule packets to be sent within interrupt + edpt_schedule_packets(rhport, epnum, dir, num_packets, total_bytes); + } + + return true; +} + +// The number of bytes has to be given explicitly to allow more flexible control of how many +// bytes should be written and second to keep the return value free to give back a boolean +// success message. If total_bytes is too big, the FIFO will copy only what is available +// into the USB buffer! +bool dcd_edpt_xfer_fifo(uint8_t rhport, uint8_t ep_addr, tu_fifo_t* ff, uint16_t total_bytes) { + // USB buffers always work in bytes so to avoid unnecessary divisions we demand item_size = 1 + TU_ASSERT(ff->item_size == 1); + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, dir); + xfer->buffer = NULL; + xfer->ff = ff; + xfer->total_len = total_bytes; + + uint16_t num_packets = (total_bytes / xfer->max_size); + uint16_t const short_packet_size = total_bytes % xfer->max_size; + + // Zero-size packet is special case. + if (short_packet_size > 0 || (total_bytes == 0)) num_packets++; + + // Schedule packets to be sent within interrupt + edpt_schedule_packets(rhport, epnum, dir, num_packets, total_bytes); + + return true; +} + +static void dcd_edpt_disable(uint8_t rhport, uint8_t ep_addr, bool stall) { + (void) rhport; + + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + if (dir == TUSB_DIR_IN) { + dwc2_epin_t* epin = dwc2->epin; + + // Only disable currently enabled non-control endpoint + if ((epnum == 0) || !(epin[epnum].diepctl & DIEPCTL_EPENA)) { + epin[epnum].diepctl |= DIEPCTL_SNAK | (stall ? DIEPCTL_STALL : 0); + } else { + // Stop transmitting packets and NAK IN xfers. + epin[epnum].diepctl |= DIEPCTL_SNAK; + while ((epin[epnum].diepint & DIEPINT_INEPNE) == 0) {} + + // Disable the endpoint. + epin[epnum].diepctl |= DIEPCTL_EPDIS | (stall ? DIEPCTL_STALL : 0); + while ((epin[epnum].diepint & DIEPINT_EPDISD_Msk) == 0) {} + + epin[epnum].diepint = DIEPINT_EPDISD; + } + + // Flush the FIFO, and wait until we have confirmed it cleared. + dwc2->grstctl = ((epnum << GRSTCTL_TXFNUM_Pos) | GRSTCTL_TXFFLSH); + while ((dwc2->grstctl & GRSTCTL_TXFFLSH_Msk) != 0) {} + } else { + dwc2_epout_t* epout = dwc2->epout; + + // Only disable currently enabled non-control endpoint + if ((epnum == 0) || !(epout[epnum].doepctl & DOEPCTL_EPENA)) { + epout[epnum].doepctl |= stall ? DOEPCTL_STALL : 0; + } else { + // Asserting GONAK is required to STALL an OUT endpoint. + // Simpler to use polling here, we don't use the "B"OUTNAKEFF interrupt + // anyway, and it can't be cleared by user code. If this while loop never + // finishes, we have bigger problems than just the stack. + dwc2->dctl |= DCTL_SGONAK; + while ((dwc2->gintsts & GINTSTS_BOUTNAKEFF_Msk) == 0) {} + + // Ditto here- disable the endpoint. + epout[epnum].doepctl |= DOEPCTL_EPDIS | (stall ? DOEPCTL_STALL : 0); + while ((epout[epnum].doepint & DOEPINT_EPDISD_Msk) == 0) {} + + epout[epnum].doepint = DOEPINT_EPDISD; + + // Allow other OUT endpoints to keep receiving. + dwc2->dctl |= DCTL_CGONAK; + } + } +} + +/** + * Close an endpoint. + */ +void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + dcd_edpt_disable(rhport, ep_addr, false); + + // Update max_size + xfer_status[epnum][dir].max_size = 0; // max_size = 0 marks a disabled EP - required for changing FIFO allocation + + if (dir == TUSB_DIR_IN) { + uint16_t const fifo_size = (dwc2->dieptxf[epnum - 1] & DIEPTXF_INEPTXFD_Msk) >> DIEPTXF_INEPTXFD_Pos; + uint16_t const fifo_start = (dwc2->dieptxf[epnum - 1] & DIEPTXF_INEPTXSA_Msk) >> DIEPTXF_INEPTXSA_Pos; + + // For now only the last opened endpoint can be closed without fuss. + TU_ASSERT(fifo_start == _dwc2_controller[rhport].ep_fifo_size / 4 - _allocated_fifo_words_tx,); + _allocated_fifo_words_tx -= fifo_size; + } else { + _out_ep_closed = true; // Set flag such that RX FIFO gets reduced in size once RX FIFO is empty + } +} + +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { + dcd_edpt_disable(rhport, ep_addr, true); +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) { + (void) rhport; + + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + // Clear stall and reset data toggle + if (dir == TUSB_DIR_IN) { + dwc2->epin[epnum].diepctl &= ~DIEPCTL_STALL; + dwc2->epin[epnum].diepctl |= DIEPCTL_SD0PID_SEVNFRM; + } else { + dwc2->epout[epnum].doepctl &= ~DOEPCTL_STALL; + dwc2->epout[epnum].doepctl |= DOEPCTL_SD0PID_SEVNFRM; + } +} + +/*------------------------------------------------------------------*/ + +// Read a single data packet from receive FIFO +static void read_fifo_packet(uint8_t rhport, uint8_t* dst, uint16_t len) { + (void) rhport; + + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + volatile const uint32_t* rx_fifo = dwc2->fifo[0]; + + // Reading full available 32 bit words from fifo + uint16_t full_words = len >> 2; + while (full_words--) { + tu_unaligned_write32(dst, *rx_fifo); + dst += 4; + } + + // Read the remaining 1-3 bytes from fifo + uint8_t const bytes_rem = len & 0x03; + if (bytes_rem != 0) { + uint32_t const tmp = *rx_fifo; + dst[0] = tu_u32_byte0(tmp); + if (bytes_rem > 1) dst[1] = tu_u32_byte1(tmp); + if (bytes_rem > 2) dst[2] = tu_u32_byte2(tmp); + } +} + +// Write a single data packet to EPIN FIFO +static void write_fifo_packet(uint8_t rhport, uint8_t fifo_num, uint8_t const* src, uint16_t len) { + (void) rhport; + + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + volatile uint32_t* tx_fifo = dwc2->fifo[fifo_num]; + + // Pushing full available 32 bit words to fifo + uint16_t full_words = len >> 2; + while (full_words--) { + *tx_fifo = tu_unaligned_read32(src); + src += 4; + } + + // Write the remaining 1-3 bytes into fifo + uint8_t const bytes_rem = len & 0x03; + if (bytes_rem) { + uint32_t tmp_word = src[0]; + if (bytes_rem > 1) tmp_word |= (src[1] << 8); + if (bytes_rem > 2) tmp_word |= (src[2] << 16); + + *tx_fifo = tmp_word; + } +} + +static void handle_rxflvl_irq(uint8_t rhport) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + volatile uint32_t const* rx_fifo = dwc2->fifo[0]; + + // Pop control word off FIFO + uint32_t const ctl_word = dwc2->grxstsp; + uint8_t const pktsts = (ctl_word & GRXSTSP_PKTSTS_Msk) >> GRXSTSP_PKTSTS_Pos; + uint8_t const epnum = (ctl_word & GRXSTSP_EPNUM_Msk) >> GRXSTSP_EPNUM_Pos; + uint16_t const bcnt = (ctl_word & GRXSTSP_BCNT_Msk) >> GRXSTSP_BCNT_Pos; + + dwc2_epout_t* epout = &dwc2->epout[epnum]; + +//#if CFG_TUSB_DEBUG >= DWC2_DEBUG +// const char * pktsts_str[] = +// { +// "ASSERT", "Global NAK (ISR)", "Out Data Received", "Out Transfer Complete (ISR)", +// "Setup Complete (ISR)", "ASSERT", "Setup Data Received" +// }; +// TU_LOG_LOCATION(); +// TU_LOG(DWC2_DEBUG, " EP %02X, Byte Count %u, %s\r\n", epnum, bcnt, pktsts_str[pktsts]); +// TU_LOG(DWC2_DEBUG, " daint = %08lX, doepint = %04X\r\n", (unsigned long) dwc2->daint, (unsigned int) epout->doepint); +//#endif + + switch (pktsts) { + // Global OUT NAK: do nothing + case GRXSTS_PKTSTS_GLOBALOUTNAK: + break; + + case GRXSTS_PKTSTS_SETUPRX: + // Setup packet received + + // We can receive up to three setup packets in succession, but + // only the last one is valid. + _setup_packet[0] = (*rx_fifo); + _setup_packet[1] = (*rx_fifo); + break; + + case GRXSTS_PKTSTS_SETUPDONE: + // Setup packet done (Interrupt) + epout->doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); + break; + + case GRXSTS_PKTSTS_OUTRX: { + // Out packet received + xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); + + // Read packet off RxFIFO + if (xfer->ff) { + // Ring buffer + tu_fifo_write_n_const_addr_full_words(xfer->ff, (const void*) (uintptr_t) rx_fifo, bcnt); + } else { + // Linear buffer + read_fifo_packet(rhport, xfer->buffer, bcnt); + + // Increment pointer to xfer data + xfer->buffer += bcnt; + } + + // Truncate transfer length in case of short packet + if (bcnt < xfer->max_size) { + xfer->total_len -= (epout->doeptsiz & DOEPTSIZ_XFRSIZ_Msk) >> DOEPTSIZ_XFRSIZ_Pos; + if (epnum == 0) { + xfer->total_len -= ep0_pending[TUSB_DIR_OUT]; + ep0_pending[TUSB_DIR_OUT] = 0; + } + } + } + break; + + // Out packet done (Interrupt) + case GRXSTS_PKTSTS_OUTDONE: + // Occurred on STM32L47 with dwc2 version 3.10a but not found on other version like 2.80a or 3.30a + // May (or not) be 3.10a specific feature/bug or depending on MCU configuration + // XFRC complete is additionally generated when + // - setup packet is received + // - complete the data stage of control write is complete + if ((epnum == 0) && (bcnt == 0) && (dwc2->gsnpsid >= DWC2_CORE_REV_3_00a)) { + uint32_t doepint = epout->doepint; + + if (doepint & (DOEPINT_STPKTRX | DOEPINT_OTEPSPR)) { + // skip this "no-data" transfer complete event + // Note: STPKTRX will be clear later by setup received handler + uint32_t clear_flags = DOEPINT_XFRC; + + if (doepint & DOEPINT_OTEPSPR) clear_flags |= DOEPINT_OTEPSPR; + + epout->doepint = clear_flags; + + // TU_LOG(DWC2_DEBUG, " FIX extra transfer complete on setup/data compete\r\n"); + } + } + break; + + default: // Invalid + TU_BREAKPOINT(); + break; + } +} + +static void handle_epout_irq(uint8_t rhport) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + uint8_t const ep_count = _dwc2_controller[rhport].ep_count; + + // DAINT for a given EP clears when DOEPINTx is cleared. + // OEPINT will be cleared when DAINT's out bits are cleared. + for (uint8_t n = 0; n < ep_count; n++) { + if (dwc2->daint & TU_BIT(DAINT_OEPINT_Pos + n)) { + dwc2_epout_t* epout = &dwc2->epout[n]; + + uint32_t const doepint = epout->doepint; + + // SETUP packet Setup Phase done. + if (doepint & DOEPINT_STUP) { + uint32_t clear_flag = DOEPINT_STUP; + + // STPKTRX is only available for version from 3_00a + if ((doepint & DOEPINT_STPKTRX) && (dwc2->gsnpsid >= DWC2_CORE_REV_3_00a)) { + clear_flag |= DOEPINT_STPKTRX; + } + + epout->doepint = clear_flag; + dcd_event_setup_received(rhport, (uint8_t*) _setup_packet, true); + } + + // OUT XFER complete + if (epout->doepint & DOEPINT_XFRC) { + epout->doepint = DOEPINT_XFRC; + + xfer_ctl_t* xfer = XFER_CTL_BASE(n, TUSB_DIR_OUT); + + // EP0 can only handle one packet + if ((n == 0) && ep0_pending[TUSB_DIR_OUT]) { + // Schedule another packet to be received. + edpt_schedule_packets(rhport, n, TUSB_DIR_OUT, 1, ep0_pending[TUSB_DIR_OUT]); + } else { + dcd_event_xfer_complete(rhport, n, xfer->total_len, XFER_RESULT_SUCCESS, true); + } + } + } + } +} + +static void handle_epin_irq(uint8_t rhport) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + uint8_t const ep_count = _dwc2_controller[rhport].ep_count; + dwc2_epin_t* epin = dwc2->epin; + + // DAINT for a given EP clears when DIEPINTx is cleared. + // IEPINT will be cleared when DAINT's out bits are cleared. + for (uint8_t n = 0; n < ep_count; n++) { + if (dwc2->daint & TU_BIT(DAINT_IEPINT_Pos + n)) { + // IN XFER complete (entire xfer). + xfer_ctl_t* xfer = XFER_CTL_BASE(n, TUSB_DIR_IN); + + if (epin[n].diepint & DIEPINT_XFRC) { + epin[n].diepint = DIEPINT_XFRC; + + // EP0 can only handle one packet + if ((n == 0) && ep0_pending[TUSB_DIR_IN]) { + // Schedule another packet to be transmitted. + edpt_schedule_packets(rhport, n, TUSB_DIR_IN, 1, ep0_pending[TUSB_DIR_IN]); + } else { + dcd_event_xfer_complete(rhport, n | TUSB_DIR_IN_MASK, xfer->total_len, XFER_RESULT_SUCCESS, true); + } + } + + // XFER FIFO empty + if ((epin[n].diepint & DIEPINT_TXFE) && (dwc2->diepempmsk & (1 << n))) { + // diepint's TXFE bit is read-only, software cannot clear it. + // It will only be cleared by hardware when written bytes is more than + // - 64 bytes or + // - Half of TX FIFO size (configured by DIEPTXF) + + uint16_t remaining_packets = (epin[n].dieptsiz & DIEPTSIZ_PKTCNT_Msk) >> DIEPTSIZ_PKTCNT_Pos; + + // Process every single packet (only whole packets can be written to fifo) + for (uint16_t i = 0; i < remaining_packets; i++) { + uint16_t const remaining_bytes = (epin[n].dieptsiz & DIEPTSIZ_XFRSIZ_Msk) >> DIEPTSIZ_XFRSIZ_Pos; + + // Packet can not be larger than ep max size + uint16_t const packet_size = tu_min16(remaining_bytes, xfer->max_size); + + // It's only possible to write full packets into FIFO. Therefore DTXFSTS register of current + // EP has to be checked if the buffer can take another WHOLE packet + if (packet_size > ((epin[n].dtxfsts & DTXFSTS_INEPTFSAV_Msk) << 2)) break; + + // Push packet to Tx-FIFO + if (xfer->ff) { + volatile uint32_t* tx_fifo = dwc2->fifo[n]; + tu_fifo_read_n_const_addr_full_words(xfer->ff, (void*) (uintptr_t) tx_fifo, packet_size); + } else { + write_fifo_packet(rhport, n, xfer->buffer, packet_size); + + // Increment pointer to xfer data + xfer->buffer += packet_size; + } + } + + // Turn off TXFE if all bytes are written. + if (((epin[n].dieptsiz & DIEPTSIZ_XFRSIZ_Msk) >> DIEPTSIZ_XFRSIZ_Pos) == 0) { + dwc2->diepempmsk &= ~(1 << n); + } + } + } + } +} + +void dcd_int_handler(uint8_t rhport) { + dwc2_regs_t* dwc2 = DWC2_REG(rhport); + + uint32_t const int_mask = dwc2->gintmsk; + uint32_t const int_status = dwc2->gintsts & int_mask; + + if (int_status & GINTSTS_USBRST) { + // USBRST is start of reset. + dwc2->gintsts = GINTSTS_USBRST; + bus_reset(rhport); + } + + if (int_status & GINTSTS_ENUMDNE) { + // ENUMDNE is the end of reset where speed of the link is detected + dwc2->gintsts = GINTSTS_ENUMDNE; + + tusb_speed_t speed; + switch ((dwc2->dsts & DSTS_ENUMSPD_Msk) >> DSTS_ENUMSPD_Pos) { + case DSTS_ENUMSPD_HS: + speed = TUSB_SPEED_HIGH; + break; + + case DSTS_ENUMSPD_LS: + speed = TUSB_SPEED_LOW; + break; + + case DSTS_ENUMSPD_FS_HSPHY: + case DSTS_ENUMSPD_FS: + default: + speed = TUSB_SPEED_FULL; + break; + } + + // TODO must update GUSBCFG_TRDT according to link speed + + dcd_event_bus_reset(rhport, speed, true); + } + + if (int_status & GINTSTS_USBSUSP) { + dwc2->gintsts = GINTSTS_USBSUSP; + dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true); + } + + if (int_status & GINTSTS_WKUINT) { + dwc2->gintsts = GINTSTS_WKUINT; + dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); + } + + // TODO check GINTSTS_DISCINT for disconnect detection + // if(int_status & GINTSTS_DISCINT) + + if (int_status & GINTSTS_OTGINT) { + // OTG INT bit is read-only + uint32_t const otg_int = dwc2->gotgint; + + if (otg_int & GOTGINT_SEDET) { + dcd_event_bus_signal(rhport, DCD_EVENT_UNPLUGGED, true); + } + + dwc2->gotgint = otg_int; + } + + if(int_status & GINTSTS_SOF) { + dwc2->gintsts = GINTSTS_SOF; + + if (_sof_en) { + uint32_t frame = (dwc2->dsts & (DSTS_FNSOF)) >> 8; + dcd_event_sof(rhport, frame, true); + } else { + // Disable SOF interrupt if SOF was not explicitly enabled. SOF was used for remote wakeup detection + dwc2->gintmsk &= ~GINTMSK_SOFM; + } + + dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); + } + + // RxFIFO non-empty interrupt handling. + if (int_status & GINTSTS_RXFLVL) { + // RXFLVL bit is read-only + + // Mask out RXFLVL while reading data from FIFO + dwc2->gintmsk &= ~GINTMSK_RXFLVLM; + + // Loop until all available packets were handled + do { + handle_rxflvl_irq(rhport); + } while (dwc2->gotgint & GINTSTS_RXFLVL); + + // Manage RX FIFO size + if (_out_ep_closed) { + update_grxfsiz(rhport); + + // Disable flag + _out_ep_closed = false; + } + + dwc2->gintmsk |= GINTMSK_RXFLVLM; + } + + // OUT endpoint interrupt handling. + if (int_status & GINTSTS_OEPINT) { + // OEPINT is read-only, clear using DOEPINTn + handle_epout_irq(rhport); + } + + // IN endpoint interrupt handling. + if (int_status & GINTSTS_IEPINT) { + // IEPINT bit read-only, clear using DIEPINTn + handle_epin_irq(rhport); + } + + // // Check for Incomplete isochronous IN transfer + // if(int_status & GINTSTS_IISOIXFR) { + // printf(" IISOIXFR!\r\n"); + //// TU_LOG(DWC2_DEBUG, " IISOIXFR!\r\n"); + // } +} + +#endif diff --git a/src/portable/synopsys/dwc2/dwc2_bcm.h b/src/portable/synopsys/dwc2/dwc2_bcm.h new file mode 100644 index 00000000..1017f351 --- /dev/null +++ b/src/portable/synopsys/dwc2/dwc2_bcm.h @@ -0,0 +1,89 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021, 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_DWC2_BCM_H_ +#define _TUSB_DWC2_BCM_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "broadcom/defines.h" +#include "broadcom/interrupts.h" +#include "broadcom/caches.h" + +#define DWC2_EP_MAX 8 + +static const dwc2_controller_t _dwc2_controller[] = +{ + { .reg_base = USB_OTG_GLOBAL_BASE, .irqnum = USB_IRQn, .ep_count = DWC2_EP_MAX, .ep_fifo_size = 4096 } +}; + +#define dcache_clean(_addr, _size) data_clean(_addr, _size) +#define dcache_invalidate(_addr, _size) data_invalidate(_addr, _size) +#define dcache_clean_invalidate(_addr, _size) data_clean_and_invalidate(_addr, _size) + +TU_ATTR_ALWAYS_INLINE +static inline void dwc2_dcd_int_enable(uint8_t rhport) +{ + BP_EnableIRQ(_dwc2_controller[rhport].irqnum); +} + +TU_ATTR_ALWAYS_INLINE +static inline void dwc2_dcd_int_disable (uint8_t rhport) +{ + BP_DisableIRQ(_dwc2_controller[rhport].irqnum); +} + +static inline void dwc2_remote_wakeup_delay(void) +{ + // try to delay for 1 ms + // TODO implement later +} + +// MCU specific PHY init, called BEFORE core reset +static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type) +{ + (void) dwc2; + (void) hs_phy_type; + + // nothing to do +} + +// MCU specific PHY update, it is called AFTER init() and core reset +static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type) +{ + (void) dwc2; + (void) hs_phy_type; + + // nothing to do +} + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/src/portable/synopsys/dwc2/dwc2_efm32.h b/src/portable/synopsys/dwc2/dwc2_efm32.h new file mode 100644 index 00000000..321ad13f --- /dev/null +++ b/src/portable/synopsys/dwc2/dwc2_efm32.h @@ -0,0 +1,89 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021 Rafael Silva (@perigoso) + * Copyright (c) 2021, 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 _DWC2_EFM32_H_ +#define _DWC2_EFM32_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "em_device.h" + +// EFM32 has custom control register before DWC registers +#define DWC2_REG_BASE (USB_BASE + offsetof(USB_TypeDef, GOTGCTL)) +#define DWC2_EP_MAX 7 + +static const dwc2_controller_t _dwc2_controller[] = +{ + { .reg_base = DWC2_REG_BASE, .irqnum = USB_IRQn, .ep_count = DWC2_EP_MAX, .ep_fifo_size = 2048 } +}; + +TU_ATTR_ALWAYS_INLINE +static inline void dwc2_dcd_int_enable(uint8_t rhport) +{ + NVIC_EnableIRQ(_dwc2_controller[rhport].irqnum); +} + +TU_ATTR_ALWAYS_INLINE +static inline void dwc2_dcd_int_disable (uint8_t rhport) +{ + NVIC_DisableIRQ(_dwc2_controller[rhport].irqnum); +} + +static inline void dwc2_remote_wakeup_delay(void) +{ + // try to delay for 1 ms +// uint32_t count = SystemCoreClock / 1000; +// while ( count-- ) __NOP(); +} + +// MCU specific PHY init, called BEFORE core reset +static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type) +{ + (void) dwc2; + (void) hs_phy_type; + + // Enable PHY + USB->ROUTE = USB_ROUTE_PHYPEN; +} + +// MCU specific PHY update, it is called AFTER init() and core reset +static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type) +{ + (void) dwc2; + (void) hs_phy_type; + + // EFM32 Manual: turn around must be 5 (reset & default value) + // dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_TRDT_Msk) | (5u << GUSBCFG_TRDT_Pos); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/portable/synopsys/dwc2/dwc2_esp32.h b/src/portable/synopsys/dwc2/dwc2_esp32.h new file mode 100644 index 00000000..2bddf023 --- /dev/null +++ b/src/portable/synopsys/dwc2/dwc2_esp32.h @@ -0,0 +1,96 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021, 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 _DWC2_ESP32_H_ +#define _DWC2_ESP32_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "esp_intr_alloc.h" +#include "soc/periph_defs.h" +//#include "soc/usb_periph.h" + +#define DWC2_REG_BASE 0x60080000UL +#define DWC2_EP_MAX 6 // USB_OUT_EP_NUM. TODO ESP32Sx only has 5 tx fifo (5 endpoint IN) + +static const dwc2_controller_t _dwc2_controller[] = +{ + { .reg_base = DWC2_REG_BASE, .irqnum = 0, .ep_count = DWC2_EP_MAX, .ep_fifo_size = 1024 } +}; + +static intr_handle_t usb_ih; + +static void dcd_int_handler_wrap(void* arg) +{ + (void) arg; + dcd_int_handler(0); +} + +TU_ATTR_ALWAYS_INLINE +static inline void dwc2_dcd_int_enable (uint8_t rhport) +{ + (void) rhport; + esp_intr_alloc(ETS_USB_INTR_SOURCE, ESP_INTR_FLAG_LOWMED, dcd_int_handler_wrap, NULL, &usb_ih); +} + +TU_ATTR_ALWAYS_INLINE +static inline void dwc2_dcd_int_disable (uint8_t rhport) +{ + (void) rhport; + esp_intr_free(usb_ih); +} + +static inline void dwc2_remote_wakeup_delay(void) +{ + vTaskDelay(pdMS_TO_TICKS(1)); +} + +// MCU specific PHY init, called BEFORE core reset +static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type) +{ + (void) dwc2; + (void) hs_phy_type; + + // nothing to do +} + +// MCU specific PHY update, it is called AFTER init() and core reset +static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type) +{ + (void) dwc2; + (void) hs_phy_type; + + // nothing to do +} + +#ifdef __cplusplus +} +#endif + +#endif /* _DWC2_ESP32_H_ */ diff --git a/src/portable/synopsys/dwc2/dwc2_gd32.h b/src/portable/synopsys/dwc2/dwc2_gd32.h new file mode 100644 index 00000000..17674087 --- /dev/null +++ b/src/portable/synopsys/dwc2/dwc2_gd32.h @@ -0,0 +1,101 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021, 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 DWC2_GD32_H_ +#define DWC2_GD32_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define DWC2_REG_BASE 0x50000000UL +#define DWC2_EP_MAX 4 + +static const dwc2_controller_t _dwc2_controller[] = +{ + { .reg_base = DWC2_REG_BASE, .irqnum = 86, .ep_count = DWC2_EP_MAX, .ep_fifo_size = 1280 } +}; + +extern uint32_t SystemCoreClock; + +// The GD32VF103 is a RISC-V MCU, which implements the ECLIC Core-Local +// Interrupt Controller by Nuclei. It is nearly API compatible to the +// NVIC used by ARM MCUs. +#define ECLIC_INTERRUPT_ENABLE_BASE 0xD2001001UL + +TU_ATTR_ALWAYS_INLINE +static inline void __eclic_enable_interrupt (uint32_t irq) { + *(volatile uint8_t*)(ECLIC_INTERRUPT_ENABLE_BASE + (irq * 4)) = 1; +} + +TU_ATTR_ALWAYS_INLINE +static inline void __eclic_disable_interrupt (uint32_t irq){ + *(volatile uint8_t*)(ECLIC_INTERRUPT_ENABLE_BASE + (irq * 4)) = 0; +} + +TU_ATTR_ALWAYS_INLINE +static inline void dwc2_dcd_int_enable(uint8_t rhport) +{ + __eclic_enable_interrupt(_dwc2_controller[rhport].irqnum); +} + +TU_ATTR_ALWAYS_INLINE +static inline void dwc2_dcd_int_disable (uint8_t rhport) +{ + __eclic_disable_interrupt(_dwc2_controller[rhport].irqnum); +} + +static inline void dwc2_remote_wakeup_delay(void) +{ + // try to delay for 1 ms + uint32_t count = SystemCoreClock / 1000; + while ( count-- ) __asm volatile ("nop"); +} + +// MCU specific PHY init, called BEFORE core reset +static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type) +{ + (void) dwc2; + (void) hs_phy_type; + + // nothing to do +} + +// MCU specific PHY update, it is called AFTER init() and core reset +static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type) +{ + (void) dwc2; + (void) hs_phy_type; + + // nothing to do +} + +#ifdef __cplusplus +} +#endif + +#endif /* DWC2_GD32_H_ */ diff --git a/src/portable/synopsys/dwc2/dwc2_stm32.h b/src/portable/synopsys/dwc2/dwc2_stm32.h new file mode 100644 index 00000000..fe631bb9 --- /dev/null +++ b/src/portable/synopsys/dwc2/dwc2_stm32.h @@ -0,0 +1,261 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021, 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 DWC2_STM32_H_ +#define DWC2_STM32_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +// EP_MAX : Max number of bi-directional endpoints including EP0 +// EP_FIFO_SIZE : Size of dedicated USB SRAM +#if CFG_TUSB_MCU == OPT_MCU_STM32F1 + #include "stm32f1xx.h" + #define EP_MAX_FS 4 + #define EP_FIFO_SIZE_FS 1280 + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F2 + #include "stm32f2xx.h" + #define EP_MAX_FS USB_OTG_FS_MAX_IN_ENDPOINTS + #define EP_FIFO_SIZE_FS USB_OTG_FS_TOTAL_FIFO_SIZE + + #define EP_MAX_HS USB_OTG_HS_MAX_IN_ENDPOINTS + #define EP_FIFO_SIZE_HS USB_OTG_HS_TOTAL_FIFO_SIZE + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F4 + #include "stm32f4xx.h" + #define EP_MAX_FS USB_OTG_FS_MAX_IN_ENDPOINTS + #define EP_FIFO_SIZE_FS USB_OTG_FS_TOTAL_FIFO_SIZE + + #define EP_MAX_HS USB_OTG_HS_MAX_IN_ENDPOINTS + #define EP_FIFO_SIZE_HS USB_OTG_HS_TOTAL_FIFO_SIZE + +#elif CFG_TUSB_MCU == OPT_MCU_STM32H7 + #include "stm32h7xx.h" + #define EP_MAX_FS 9 + #define EP_FIFO_SIZE_FS 4096 + + #define EP_MAX_HS 9 + #define EP_FIFO_SIZE_HS 4096 + + // NOTE: H7 with only 1 USB port: H72x / H73x / H7Ax / H7Bx + // USB_OTG_FS_PERIPH_BASE and OTG_FS_IRQn not defined + #if (! defined USB2_OTG_FS) + #define USB_OTG_FS_PERIPH_BASE USB1_OTG_HS_PERIPH_BASE + #define OTG_FS_IRQn OTG_HS_IRQn + #endif + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F7 + #include "stm32f7xx.h" + #define EP_MAX_FS 6 + #define EP_FIFO_SIZE_FS 1280 + + #define EP_MAX_HS 9 + #define EP_FIFO_SIZE_HS 4096 + +#elif CFG_TUSB_MCU == OPT_MCU_STM32L4 + #include "stm32l4xx.h" + #define EP_MAX_FS 6 + #define EP_FIFO_SIZE_FS 1280 + +#elif CFG_TUSB_MCU == OPT_MCU_STM32U5 + #include "stm32u5xx.h" + // U59x/5Ax/5Fx/5Gx are highspeed with built-in HS PHY + #ifdef USB_OTG_FS + #define USB_OTG_FS_PERIPH_BASE USB_OTG_FS_BASE + #define EP_MAX_FS 6 + #define EP_FIFO_SIZE_FS 1280 + #else + #define USB_OTG_HS_PERIPH_BASE USB_OTG_HS_BASE + #define EP_MAX_HS 9 + #define EP_FIFO_SIZE_HS 4096 + #endif +#else + #error "Unsupported MCUs" +#endif + +// OTG HS always has higher number of endpoints than FS +#ifdef USB_OTG_HS_PERIPH_BASE + #define DWC2_EP_MAX EP_MAX_HS +#else + #define DWC2_EP_MAX EP_MAX_FS +#endif + +// On STM32 for consistency we associate +// - Port0 to OTG_FS, and Port1 to OTG_HS +static const dwc2_controller_t _dwc2_controller[] = { + #ifdef USB_OTG_FS_PERIPH_BASE + { .reg_base = USB_OTG_FS_PERIPH_BASE, .irqnum = OTG_FS_IRQn, .ep_count = EP_MAX_FS, .ep_fifo_size = EP_FIFO_SIZE_FS }, + #endif + + #ifdef USB_OTG_HS_PERIPH_BASE + { .reg_base = USB_OTG_HS_PERIPH_BASE, .irqnum = OTG_HS_IRQn, .ep_count = EP_MAX_HS, .ep_fifo_size = EP_FIFO_SIZE_HS }, + #endif +}; + +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ + +// SystemCoreClock is already included by family header +// extern uint32_t SystemCoreClock; + +TU_ATTR_ALWAYS_INLINE static inline void dwc2_dcd_int_enable(uint8_t rhport) { + NVIC_EnableIRQ((IRQn_Type) _dwc2_controller[rhport].irqnum); +} + +TU_ATTR_ALWAYS_INLINE static inline void dwc2_dcd_int_disable(uint8_t rhport) { + NVIC_DisableIRQ((IRQn_Type) _dwc2_controller[rhport].irqnum); +} + +TU_ATTR_ALWAYS_INLINE static inline void dwc2_remote_wakeup_delay(void) { + // try to delay for 1 ms + uint32_t count = SystemCoreClock / 1000; + while (count--) __NOP(); +} + +// MCU specific PHY init, called BEFORE core reset +// - dwc2 3.30a (H5) use USB_HS_PHYC +// - dwc2 4.11a (U5) use femtoPHY +static inline void dwc2_phy_init(dwc2_regs_t* dwc2, uint8_t hs_phy_type) { + if (hs_phy_type == HS_PHY_TYPE_NONE) { + // Enable on-chip FS PHY + dwc2->stm32_gccfg |= STM32_GCCFG_PWRDWN; + + // https://community.st.com/t5/stm32cubemx-mcus/why-stm32h743-usb-fs-doesn-t-work-if-freertos-tickless-idle/m-p/349480#M18867 + // H7 running on full-speed phy need to disable ULPI clock in sleep mode. + // Otherwise, USB won't work when mcu executing WFI/WFE instruction i.e tick-less RTOS. + // Note: there may be other family that is affected by this, but only H7 and F7 is tested so far + #if defined(USB_OTG_FS_PERIPH_BASE) && defined(RCC_AHB1LPENR_USB2OTGFSULPILPEN) + if ( USB_OTG_FS_PERIPH_BASE == (uint32_t) dwc2 ) { + RCC->AHB1LPENR &= ~RCC_AHB1LPENR_USB2OTGFSULPILPEN; + } + #endif + + #if defined(USB_OTG_HS_PERIPH_BASE) && defined(RCC_AHB1LPENR_USB1OTGHSULPILPEN) + if ( USB_OTG_HS_PERIPH_BASE == (uint32_t) dwc2 ) { + RCC->AHB1LPENR &= ~RCC_AHB1LPENR_USB1OTGHSULPILPEN; + } + #endif + + #if defined(USB_OTG_HS_PERIPH_BASE) && defined(RCC_AHB1LPENR_OTGHSULPILPEN) + if ( USB_OTG_HS_PERIPH_BASE == (uint32_t) dwc2 ) { + RCC->AHB1LPENR &= ~RCC_AHB1LPENR_OTGHSULPILPEN; + } + #endif + + } else { +#if CFG_TUSB_MCU != OPT_MCU_STM32U5 + // Disable FS PHY, TODO on U5A5 (dwc2 4.11a) 16th bit is 'Host CDP behavior enable' + dwc2->stm32_gccfg &= ~STM32_GCCFG_PWRDWN; +#endif + + // Enable on-chip HS PHY + if (hs_phy_type == HS_PHY_TYPE_UTMI || hs_phy_type == HS_PHY_TYPE_UTMI_ULPI) { + #ifdef USB_HS_PHYC + // Enable UTMI HS PHY + dwc2->stm32_gccfg |= STM32_GCCFG_PHYHSEN; + + // Enable LDO + USB_HS_PHYC->USB_HS_PHYC_LDO |= USB_HS_PHYC_LDO_ENABLE; + + // Wait until LDO ready + while ( 0 == (USB_HS_PHYC->USB_HS_PHYC_LDO & USB_HS_PHYC_LDO_STATUS) ) {} + + uint32_t phyc_pll = 0; + + // TODO Try to get HSE_VALUE from registers instead of depending CFLAGS + switch ( HSE_VALUE ) + { + case 12000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_12MHZ ; break; + case 12500000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_12_5MHZ ; break; + case 16000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_16MHZ ; break; + case 24000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_24MHZ ; break; + case 25000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_25MHZ ; break; + case 32000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_Msk ; break; // Value not defined in header + default: + TU_ASSERT(false, ); + } + USB_HS_PHYC->USB_HS_PHYC_PLL = phyc_pll; + + // Control the tuning interface of the High Speed PHY + // Use magic value (USB_HS_PHYC_TUNE_VALUE) from ST driver for F7 + USB_HS_PHYC->USB_HS_PHYC_TUNE |= 0x00000F13U; + + // Enable PLL internal PHY + USB_HS_PHYC->USB_HS_PHYC_PLL |= USB_HS_PHYC_PLL_PLLEN; + #else + + #endif + } + } +} + +// MCU specific PHY update, it is called AFTER init() and core reset +static inline void dwc2_phy_update(dwc2_regs_t* dwc2, uint8_t hs_phy_type) { + // used to set turnaround time for fullspeed, nothing to do in highspeed mode + if (hs_phy_type == HS_PHY_TYPE_NONE) { + // Turnaround timeout depends on the AHB clock dictated by STM32 Reference Manual + uint32_t turnaround; + + if (SystemCoreClock >= 32000000u) { + turnaround = 0x6u; + } else if (SystemCoreClock >= 27500000u) { + turnaround = 0x7u; + } else if (SystemCoreClock >= 24000000u) { + turnaround = 0x8u; + } else if (SystemCoreClock >= 21800000u) { + turnaround = 0x9u; + } + else if (SystemCoreClock >= 20000000u) { + turnaround = 0xAu; + } + else if (SystemCoreClock >= 18500000u) { + turnaround = 0xBu; + } + else if (SystemCoreClock >= 17200000u) { + turnaround = 0xCu; + } + else if (SystemCoreClock >= 16000000u) { + turnaround = 0xDu; + } + else if (SystemCoreClock >= 15000000u) { + turnaround = 0xEu; + } + else { + turnaround = 0xFu; + } + + dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_TRDT_Msk) | (turnaround << GUSBCFG_TRDT_Pos); + } +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/portable/synopsys/dwc2/dwc2_type.h b/src/portable/synopsys/dwc2/dwc2_type.h new file mode 100644 index 00000000..0835426c --- /dev/null +++ b/src/portable/synopsys/dwc2/dwc2_type.h @@ -0,0 +1,1770 @@ +/** + * @author MCD Application Team + * Ha Thach (tinyusb.org) + * + * @attention + * + *