diff options
| author | Reinhard Panhuber <[email protected]> | 2021-02-12 18:05:20 +0100 |
|---|---|---|
| committer | Reinhard Panhuber <[email protected]> | 2021-02-12 18:05:20 +0100 |
| commit | cdf600048f717f187243b8118eac43b793c3feec (patch) | |
| tree | 00d88a8e39560c2e1a35f6c9feb97062733d9d8b /src | |
| parent | 185414721ff549058a199ade40966015e6260996 (diff) | |
| parent | 09868434cd9f53394350cce682333ada97f796c3 (diff) | |
Merge remote-tracking branch 'upstream/master' into edpt_ISO_xfer
Diffstat (limited to 'src')
| -rw-r--r-- | src/class/dfu/dfu_rt_device.c | 4 | ||||
| -rw-r--r-- | src/class/dfu/dfu_rt_device.h | 2 | ||||
| -rw-r--r-- | src/class/hid/hid.h | 91 | ||||
| -rw-r--r-- | src/class/hid/hid_device.c | 47 | ||||
| -rw-r--r-- | src/class/hid/hid_device.h | 53 | ||||
| -rw-r--r-- | src/class/hid/hid_host.c | 6 | ||||
| -rw-r--r-- | src/class/midi/midi_device.c | 49 | ||||
| -rw-r--r-- | src/common/tusb_types.h | 3 | ||||
| -rw-r--r-- | src/device/usbd.c | 114 | ||||
| -rw-r--r-- | src/device/usbd.h | 1 | ||||
| -rw-r--r-- | src/device/usbd_control.c | 18 | ||||
| -rw-r--r-- | src/host/usbh.c | 6 | ||||
| -rw-r--r-- | src/host/usbh.h | 1 | ||||
| -rw-r--r-- | src/osal/osal.h | 4 | ||||
| -rw-r--r-- | src/osal/osal_pico.h | 192 | ||||
| -rw-r--r-- | src/osal/osal_rtthread.h | 130 | ||||
| -rw-r--r-- | src/portable/raspberrypi/rp2040/dcd_rp2040.c | 481 | ||||
| -rw-r--r-- | src/portable/raspberrypi/rp2040/hcd_rp2040.c | 550 | ||||
| -rw-r--r-- | src/portable/raspberrypi/rp2040/rp2040_usb.c | 283 | ||||
| -rw-r--r-- | src/portable/raspberrypi/rp2040/rp2040_usb.h | 124 | ||||
| -rw-r--r-- | src/portable/sony/cxd56/dcd_cxd56.c | 90 | ||||
| -rw-r--r-- | src/tusb.h | 2 | ||||
| -rw-r--r-- | src/tusb_option.h | 14 |
23 files changed, 2136 insertions, 129 deletions
diff --git a/src/class/dfu/dfu_rt_device.c b/src/class/dfu/dfu_rt_device.c index 38644615a..5700615be 100644 --- a/src/class/dfu/dfu_rt_device.c +++ b/src/class/dfu/dfu_rt_device.c @@ -26,7 +26,7 @@ #include "tusb_option.h" -#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_DFU_RT) +#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_DFU_RUNTIME) #include "dfu_rt_device.h" #include "device/usbd_pvt.h" @@ -110,7 +110,7 @@ bool dfu_rtd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request { case DFU_REQUEST_DETACH: tud_control_status(rhport, request); - tud_dfu_rt_reboot_to_dfu(); + tud_dfu_runtime_reboot_to_dfu_cb(); break; case DFU_REQUEST_GETSTATUS: diff --git a/src/class/dfu/dfu_rt_device.h b/src/class/dfu/dfu_rt_device.h index 643e25d8f..cff43d035 100644 --- a/src/class/dfu/dfu_rt_device.h +++ b/src/class/dfu/dfu_rt_device.h @@ -58,7 +58,7 @@ typedef enum //--------------------------------------------------------------------+ // Invoked when received new data -TU_ATTR_WEAK void tud_dfu_rt_reboot_to_dfu(void); // TODO rename to _cb convention +TU_ATTR_WEAK void tud_dfu_runtime_reboot_to_dfu_cb(void); //--------------------------------------------------------------------+ // Internal Class Driver API diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index 8803e4b66..a7db087a7 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -144,6 +144,97 @@ typedef enum /** @} */ //--------------------------------------------------------------------+ +// GAMEPAD +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Gamepad Gamepad + * @{ */ + +/* From https://www.kernel.org/doc/html/latest/input/gamepad.html + ____________________________ __ + / [__ZL__] [__ZR__] \ | + / [__ TL __] [__ TR __] \ | Front Triggers + __/________________________________\__ __| + / _ \ | + / /\ __ (N) \ | + / || __ |MO| __ _ _ \ | Main Pad + | <===DP===> |SE| |ST| (W) -|- (E) | | + \ || ___ ___ _ / | + /\ \/ / \ / \ (S) /\ __| + / \________ | LS | ____ | RS | ________/ \ | +| / \ \___/ / \ \___/ / \ | | Control Sticks +| / \_____/ \_____/ \ | __| +| / \ | + \_____/ \_____/ + + |________|______| |______|___________| + D-Pad Left Right Action Pad + Stick Stick + + |_____________| + Menu Pad + + Most gamepads have the following features: + - Action-Pad 4 buttons in diamonds-shape (on the right side) NORTH, SOUTH, WEST and EAST. + - D-Pad (Direction-pad) 4 buttons (on the left side) that point up, down, left and right. + - Menu-Pad Different constellations, but most-times 2 buttons: SELECT - START. + - Analog-Sticks provide freely moveable sticks to control directions, Analog-sticks may also + provide a digital button if you press them. + - Triggers are located on the upper-side of the pad in vertical direction. The upper buttons + are normally named Left- and Right-Triggers, the lower buttons Z-Left and Z-Right. + - Rumble Many devices provide force-feedback features. But are mostly just simple rumble motors. + */ + +/// HID Gamepad Protocol Report. +typedef struct TU_ATTR_PACKED +{ + int8_t x; ///< Delta x movement of left analog-stick + int8_t y; ///< Delta y movement of left analog-stick + int8_t z; ///< Delta z movement of right analog-joystick + int8_t rz; ///< Delta Rz movement of right analog-joystick + int8_t rx; ///< Delta Rx movement of analog left trigger + int8_t ry; ///< Delta Ry movement of analog right trigger + uint8_t hat; ///< Buttons mask for currently pressed buttons in the DPad/hat + uint16_t buttons; ///< Buttons mask for currently pressed buttons +}hid_gamepad_report_t; + +/// Standard Gamepad Buttons Bitmap (from Linux input event codes) +typedef enum +{ + GAMEPAD_BUTTON_A = TU_BIT(0), ///< A/South button + GAMEPAD_BUTTON_B = TU_BIT(1), ///< B/East button + GAMEPAD_BUTTON_C = TU_BIT(2), ///< C button + GAMEPAD_BUTTON_X = TU_BIT(3), ///< X/North button + GAMEPAD_BUTTON_Y = TU_BIT(4), ///< Y/West button + GAMEPAD_BUTTON_Z = TU_BIT(5), ///< Z button + GAMEPAD_BUTTON_TL = TU_BIT(6), ///< L1 button + GAMEPAD_BUTTON_TR = TU_BIT(7), ///< R1 button + GAMEPAD_BUTTON_TL2 = TU_BIT(8), ///< L2 button + GAMEPAD_BUTTON_TR2 = TU_BIT(9), ///< R2 button + GAMEPAD_BUTTON_SELECT = TU_BIT(10), ///< Select button + GAMEPAD_BUTTON_START = TU_BIT(11), ///< Start button + GAMEPAD_BUTTON_MODE = TU_BIT(12), ///< Mode button + GAMEPAD_BUTTON_THUMBL = TU_BIT(13), ///< L3 button + GAMEPAD_BUTTON_THUMBR = TU_BIT(14), ///< R3 button +//GAMEPAD_BUTTON_ = TU_BIT(15), ///< Undefined button +}hid_gamepad_button_bm_t; + +/// Standard Gamepad HAT/DPAD Buttons (from Linux input event codes) +typedef enum +{ + GAMEPAD_HAT_CENTERED = 0, ///< DPAD_CENTERED + GAMEPAD_HAT_UP = 1, ///< DPAD_UP + GAMEPAD_HAT_UP_RIGHT = 2, ///< DPAD_UP_RIGHT + GAMEPAD_HAT_RIGHT = 3, ///< DPAD_RIGHT + GAMEPAD_HAT_DOWN_RIGHT = 4, ///< DPAD_DOWN_RIGHT + GAMEPAD_HAT_DOWN = 5, ///< DPAD_DOWN + GAMEPAD_HAT_DOWN_LEFT = 6, ///< DPAD_DOWN_LEFT + GAMEPAD_HAT_LEFT = 7, ///< DPAD_LEFT + GAMEPAD_HAT_UP_LEFT = 8, ///< DPAD_UP_LEFT +}hid_gamepad_hat_t; + +/// @} + +//--------------------------------------------------------------------+ // MOUSE //--------------------------------------------------------------------+ /** \addtogroup ClassDriver_HID_Mouse Mouse diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 1f03f8862..4cdcecc9e 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -107,9 +107,6 @@ bool tud_hid_n_boot_mode(uint8_t itf) return _hidd_itf[itf].boot_mode; } -//--------------------------------------------------------------------+ -// KEYBOARD API -//--------------------------------------------------------------------+ bool tud_hid_n_keyboard_report(uint8_t itf, uint8_t report_id, uint8_t modifier, uint8_t keycode[6]) { hid_keyboard_report_t report; @@ -127,10 +124,8 @@ bool tud_hid_n_keyboard_report(uint8_t itf, uint8_t report_id, uint8_t modifier, return tud_hid_n_report(itf, report_id, &report, sizeof(report)); } -//--------------------------------------------------------------------+ -// MOUSE APPLICATION API -//--------------------------------------------------------------------+ -bool tud_hid_n_mouse_report(uint8_t itf, uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t vertical, int8_t horizontal) +bool tud_hid_n_mouse_report(uint8_t itf, uint8_t report_id, + uint8_t buttons, int8_t x, int8_t y, int8_t vertical, int8_t horizontal) { hid_mouse_report_t report = { @@ -144,6 +139,24 @@ bool tud_hid_n_mouse_report(uint8_t itf, uint8_t report_id, uint8_t buttons, int return tud_hid_n_report(itf, report_id, &report, sizeof(report)); } +bool tud_hid_n_gamepad_report(uint8_t itf, uint8_t report_id, + int8_t x, int8_t y, int8_t z, int8_t rz, int8_t rx, int8_t ry, uint8_t hat, uint16_t buttons) +{ + hid_gamepad_report_t report = + { + .x = x, + .y = y, + .z = z, + .rz = rz, + .rx = rx, + .ry = ry, + .hat = hat, + .buttons = buttons, + }; + + return tud_hid_n_report(itf, report_id, &report, sizeof(report)); +} + //--------------------------------------------------------------------+ // USBD-CLASS API //--------------------------------------------------------------------+ @@ -368,14 +381,24 @@ bool hidd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_ uint8_t itf = 0; hidd_interface_t * p_hid = _hidd_itf; - for ( ; ; itf++, p_hid++) + // Identify which interface to use + for (itf = 0; itf < CFG_TUD_HID; itf++) { - if (itf >= TU_ARRAY_SIZE(_hidd_itf)) return false; - - if ( ep_addr == p_hid->ep_out ) break; + p_hid = &_hidd_itf[itf]; + if ( (ep_addr == p_hid->ep_out) || (ep_addr == p_hid->ep_in) ) break; } + TU_ASSERT(itf < CFG_TUD_HID); - if (ep_addr == p_hid->ep_out) + // Sent report successfully + if (ep_addr == p_hid->ep_in) + { + if (tud_hid_report_complete_cb) + { + tud_hid_report_complete_cb(itf, p_hid->epin_buf, (uint8_t) xferred_bytes); + } + } + // Received report + else if (ep_addr == p_hid->ep_out) { tud_hid_set_report_cb( #if CFG_TUD_HID > 1 diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 456b011ba..d5de53221 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -71,6 +71,10 @@ bool tud_hid_n_keyboard_report(uint8_t itf, uint8_t report_id, uint8_t modifier, // use template layout report as defined by hid_mouse_report_t bool tud_hid_n_mouse_report(uint8_t itf, uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t vertical, int8_t horizontal); +// Gamepad: convenient helper to send mouse report if application +// use template layout report TUD_HID_REPORT_DESC_GAMEPAD +bool tud_hid_n_gamepad_report(uint8_t itf, uint8_t report_id, int8_t x, int8_t y, int8_t z, int8_t rz, int8_t rx, int8_t ry, uint8_t hat, uint16_t buttons); + //--------------------------------------------------------------------+ // Application API (Single Port) //--------------------------------------------------------------------+ @@ -119,6 +123,11 @@ TU_ATTR_WEAK bool tud_hid_set_idle_cb(uint8_t idle_rate); #endif +// Invoked when sent REPORT successfully to host +// Application can use this to send the next report +// Note: For composite reports, report[0] is report ID +TU_ATTR_WEAK void tud_hid_report_complete_cb(uint8_t itf, uint8_t const* report, uint8_t len); + //--------------------------------------------------------------------+ // Inline Functions @@ -301,14 +310,37 @@ static inline bool tud_hid_mouse_report(uint8_t report_id, uint8_t buttons, int8 HID_COLLECTION_END \ // Gamepad Report Descriptor Template -// with 16 buttons and 2 joysticks with following layout -// | Button Map (2 bytes) | X | Y | Z | Rz +// with 16 buttons, 2 joysticks and 1 hat/dpad with following layout +// | X | Y | Z | Rz | Rx | Ry (1 byte each) | hat/DPAD (1 byte) | Button Map (2 bytes) | #define TUD_HID_REPORT_DESC_GAMEPAD(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ /* Report ID if any */\ __VA_ARGS__ \ + /* 8 bit X, Y, Z, Rz, Rx, Ry (min -127, max 127 ) */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Z ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_RZ ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_RX ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_RY ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT ( 6 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 8 bit DPad/Hat Button Map */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_HAT_SWITCH ) ,\ + HID_LOGICAL_MIN ( 1 ) ,\ + HID_LOGICAL_MAX ( 8 ) ,\ + HID_PHYSICAL_MIN ( 0 ) ,\ + HID_PHYSICAL_MAX_N ( 315, 2 ) ,\ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ /* 16 bit Button Map */ \ HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ HID_USAGE_MIN ( 1 ) ,\ @@ -318,17 +350,6 @@ static inline bool tud_hid_mouse_report(uint8_t report_id, uint8_t buttons, int8 HID_REPORT_COUNT ( 16 ) ,\ HID_REPORT_SIZE ( 1 ) ,\ HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* X, Y, Z, Rz (min -127, max 127 ) */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_LOGICAL_MIN ( 0x81 ) ,\ - HID_LOGICAL_MAX ( 0x7f ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_Z ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_RZ ) ,\ - HID_REPORT_COUNT ( 4 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ HID_COLLECTION_END \ // HID Generic Input & Output diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c index a96eb6276..64d1b8e5d 100644 --- a/src/class/hid/hid_host.c +++ b/src/class/hid/hid_host.c @@ -39,6 +39,7 @@ typedef struct { uint8_t itf_num; uint8_t ep_in; uint8_t ep_out; + bool valid; uint16_t report_size; }hidh_interface_t; @@ -53,6 +54,7 @@ static inline bool hidh_interface_open(uint8_t rhport, uint8_t dev_addr, uint8_t p_hid->ep_in = p_endpoint_desc->bEndpointAddress; p_hid->report_size = p_endpoint_desc->wMaxPacketSize.size; // TODO get size from report descriptor p_hid->itf_num = interface_number; + p_hid->valid = true; return true; } @@ -246,14 +248,14 @@ bool hidh_set_config(uint8_t dev_addr, uint8_t itf_num) usbh_driver_set_config_complete(dev_addr, itf_num); #if CFG_TUH_HID_KEYBOARD - if ( keyboardh_data[dev_addr-1].itf_num == itf_num) + if (( keyboardh_data[dev_addr-1].itf_num == itf_num) && keyboardh_data[dev_addr-1].valid) { tuh_hid_keyboard_mounted_cb(dev_addr); } #endif #if CFG_TUH_HID_MOUSE - if ( mouseh_data[dev_addr-1].ep_in == itf_num ) + if (( mouseh_data[dev_addr-1].ep_in == itf_num ) && mouseh_data[dev_addr-1].valid) { tuh_hid_mouse_mounted_cb(dev_addr); } diff --git a/src/class/midi/midi_device.c b/src/class/midi/midi_device.c index ce4c9cafe..b9d6b2efc 100644 --- a/src/class/midi/midi_device.c +++ b/src/class/midi/midi_device.c @@ -85,6 +85,32 @@ bool tud_midi_n_mounted (uint8_t itf) return midi->ep_in && midi->ep_out; } +static void _prep_out_transaction (midid_interface_t* p_midi) +{ + uint8_t const rhport = TUD_OPT_RHPORT; + uint16_t available = tu_fifo_remaining(&p_midi->rx_ff); + + // Prepare for incoming data but only allow what we can store in the ring buffer. + // TODO Actually we can still carry out the transfer, keeping count of received bytes + // and slowly move it to the FIFO when read(). + // This pre-check reduces endpoint claiming + TU_VERIFY(available >= sizeof(p_midi->epout_buf), ); + + // claim endpoint + TU_VERIFY(usbd_edpt_claim(rhport, p_midi->ep_out), ); + + // fifo can be changed before endpoint is claimed + available = tu_fifo_remaining(&p_midi->rx_ff); + + if ( available >= sizeof(p_midi->epout_buf) ) { + usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, sizeof(p_midi->epout_buf)); + }else + { + // Release endpoint since we don't make any transfer + usbd_edpt_release(rhport, p_midi->ep_out); + } +} + //--------------------------------------------------------------------+ // READ API //--------------------------------------------------------------------+ @@ -135,12 +161,17 @@ uint32_t tud_midi_n_read(uint8_t itf, uint8_t jack_id, void* buffer, uint32_t bu void tud_midi_n_read_flush (uint8_t itf, uint8_t jack_id) { (void) jack_id; - tu_fifo_clear(&_midid_itf[itf].rx_ff); + midid_interface_t* p_midi = &_midid_itf[itf]; + tu_fifo_clear(&p_midi->rx_ff); + _prep_out_transaction(p_midi); } bool tud_midi_n_receive (uint8_t itf, uint8_t packet[4]) { - return tu_fifo_read_n(&_midid_itf[itf].rx_ff, packet, 4); + midid_interface_t* p_midi = &_midid_itf[itf]; + uint32_t num_read = tu_fifo_read_n(&p_midi->rx_ff, packet, 4); + _prep_out_transaction(p_midi); + return (num_read == 4); } void midi_rx_done_cb(midid_interface_t* midi, uint8_t const* buffer, uint32_t bufsize) { @@ -192,6 +223,7 @@ uint32_t tud_midi_n_write(uint8_t itf, uint8_t jack_id, uint8_t const* buffer, u if (midi->write_buffer[0] == 0x4) { if (data == 0xf7) { midi->write_buffer[0] = 0x5; + midi->write_target_length = 2; } else { midi->write_target_length = 4; } @@ -274,8 +306,8 @@ void midid_init(void) midid_interface_t* midi = &_midid_itf[i]; // config fifo - tu_fifo_config(&midi->rx_ff, midi->rx_ff_buf, CFG_TUD_MIDI_RX_BUFSIZE, 1, true); - tu_fifo_config(&midi->tx_ff, midi->tx_ff_buf, CFG_TUD_MIDI_TX_BUFSIZE, 1, true); + tu_fifo_config(&midi->rx_ff, midi->rx_ff_buf, CFG_TUD_MIDI_RX_BUFSIZE, 1, false); // true, true + tu_fifo_config(&midi->tx_ff, midi->tx_ff_buf, CFG_TUD_MIDI_TX_BUFSIZE, 1, false); // OBVS. #if CFG_FIFO_MUTEX tu_fifo_config_mutex(&midi->rx_ff, osal_mutex_create(&midi->rx_ff_mutex)); @@ -366,11 +398,7 @@ uint16_t midid_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint } // Prepare for incoming data - if ( !usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EP_BUFSIZE) ) - { - TU_LOG1_FAILED(); - TU_BREAKPOINT(); - } + _prep_out_transaction(p_midi); return drv_len; } @@ -391,6 +419,7 @@ bool midid_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t bool midid_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { (void) result; + (void) rhport; uint8_t itf; midid_interface_t* p_midi; @@ -414,7 +443,7 @@ bool midid_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32 // prepare for next // TODO for now ep_out is not used by public API therefore there is no race condition, // and does not need to claim like ep_in - TU_ASSERT(usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EP_BUFSIZE), false); + _prep_out_transaction(p_midi); } else if ( ep_addr == p_midi->ep_in ) { diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 5ab15aa3c..2b4ceb69c 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -48,7 +48,8 @@ typedef enum { TUSB_SPEED_FULL = 0, TUSB_SPEED_LOW , - TUSB_SPEED_HIGH + TUSB_SPEED_HIGH, + TUSB_SPEED_INVALID = 0xff, }tusb_speed_t; /// defined base on USB Specs Endpoint's bmAttributes diff --git a/src/device/usbd.c b/src/device/usbd.c index 2e2f9cf65..c087e2b38 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -175,9 +175,9 @@ static usbd_class_driver_t const _usbd_driver[] = }, #endif - #if CFG_TUD_DFU_RT + #if CFG_TUD_DFU_RUNTIME { - DRIVER_NAME("DFU-RT") + DRIVER_NAME("DFU-RUNTIME") .init = dfu_rtd_init, .reset = dfu_rtd_reset, .open = dfu_rtd_open, @@ -485,6 +485,12 @@ void tud_task (void) // But it is easier to set it every time instead of wasting time to check then set _usbd_dev.connected = 1; + // mark both in & out control as free + _usbd_dev.ep_status[0][TUSB_DIR_OUT].busy = false; + _usbd_dev.ep_status[0][TUSB_DIR_OUT].claimed = 0; + _usbd_dev.ep_status[0][TUSB_DIR_IN ].busy = false; + _usbd_dev.ep_status[0][TUSB_DIR_IN ].claimed = 0; + // Process control request if ( !process_control_request(event.rhport, &event.setup_received) ) { @@ -605,6 +611,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const // forward to class driver: "non-STD request to Interface" return invoke_class_control(rhport, driver, p_request); } + if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type ) { // Non standard request is not supported @@ -712,14 +719,17 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const TU_ASSERT(ep_num < TU_ARRAY_SIZE(_usbd_dev.ep2drv) ); - bool ret = false; + usbd_class_driver_t const * driver = get_driver(_usbd_dev.ep2drv[ep_num][ep_dir]); - // Handle STD request to endpoint - if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) + if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type ) { - // force return true for standard request - ret = true; - + // Forward class request to its driver + TU_VERIFY(driver); + return invoke_class_control(rhport, driver, p_request); + } + else + { + // Handle STD request to endpoint switch ( p_request->bRequest ) { case TUSB_REQ_GET_STATUS: @@ -730,40 +740,39 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const break; case TUSB_REQ_CLEAR_FEATURE: - if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) usbd_edpt_clear_stall(rhport, ep_addr); - tud_control_status(rhport, p_request); - break; - case TUSB_REQ_SET_FEATURE: - if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) usbd_edpt_stall(rhport, ep_addr); - tud_control_status(rhport, p_request); + { + if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) + { + if ( TUSB_REQ_CLEAR_FEATURE == p_request->bRequest ) + { + usbd_edpt_clear_stall(rhport, ep_addr); + }else + { + usbd_edpt_stall(rhport, ep_addr); + } + } + + if (driver) + { + // Some classes such as USBTMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request + // We will also forward std request targeted endpoint to class drivers as well + + // STD request must always be ACKed regardless of driver returned value + // Also clear complete callback if driver set since it can also stall the request. + (void) invoke_class_control(rhport, driver, p_request); + usbd_control_set_complete_callback(NULL); + + // skip ZLP status if driver already did that + if ( !_usbd_dev.ep_status[0][TUSB_DIR_IN].busy ) tud_control_status(rhport, p_request); + } + } break; // Unknown/Unsupported request default: TU_BREAKPOINT(); return false; } } - - usbd_class_driver_t const * driver = get_driver(_usbd_dev.ep2drv[ep_num][ep_dir]); - - if (driver) - { - // Some classes such as USBTMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request - // We will forward all request targeted endpoint to class drivers after - // - For class-type requests: driver is fully responsible to reply to host - // - For std-type requests : driver init/re-init internal variable/buffer only, and - // must not call tud_control_status(), driver's return value will have no effect. - // EP state has already affected (stalled/cleared) - if ( invoke_class_control(rhport, driver, p_request) ) ret = true; - } - - if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) - { - // Set complete callback = NULL since it can also stall the request. - usbd_control_set_complete_callback(NULL); - } - - return ret; } break; @@ -1103,22 +1112,35 @@ bool usbd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * desc_ep) { TU_LOG2(" Open EP %02X with Size = %u\r\n", desc_ep->bEndpointAddress, desc_ep->wMaxPacketSize.size); - if (TUSB_XFER_ISOCHRONOUS == desc_ep->bmAttributes.xfer) - { - TU_ASSERT(desc_ep->wMaxPacketSize.size <= (_usbd_dev.speed == TUSB_SPEED_HIGH ? 1024 : 1023)); - } - else + switch (desc_ep->bmAttributes.xfer) { - uint16_t const max_epsize = (_usbd_dev.speed == TUSB_SPEED_HIGH ? 512 : 64); - - if (TUSB_XFER_BULK == desc_ep->bmAttributes.xfer) + case TUSB_XFER_ISOCHRONOUS: { - // Bulk must be EXACTLY 512/64 bytes - TU_ASSERT(desc_ep->wMaxPacketSize.size == max_epsize); - }else + uint16_t const max_epsize = (_usbd_dev.speed == TUSB_SPEED_HIGH ? 1024 : 1023); + TU_ASSERT(desc_ep->wMaxPacketSize.size <= max_epsize); + } + break; + + case TUSB_XFER_BULK: + if (_usbd_dev.speed == TUSB_SPEED_HIGH) + { + // Bulk highspeed must be EXACTLY 512 + TU_ASSERT(desc_ep->wMaxPacketSize.size == 512); + }else + { + // TODO Bulk fullspeed can only be 8, 16, 32, 64 + TU_ASSERT(desc_ep->wMaxPacketSize.size <= 64); + } + break; + + case TUSB_XFER_INTERRUPT: { + uint16_t const max_epsize = (_usbd_dev.speed == TUSB_SPEED_HIGH ? 1024 : 64); TU_ASSERT(desc_ep->wMaxPacketSize.size <= max_epsize); } + break; + + default: return false; } return dcd_edpt_open(rhport, desc_ep); diff --git a/src/device/usbd.h b/src/device/usbd.h index 360567743..b5f7dceba 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -57,6 +57,7 @@ extern void dcd_int_handler(uint8_t rhport); tusb_speed_t tud_speed_get(void); // Check if device is connected (may not mounted/configured yet) +// True if just got out of Bus Reset and received the very first data from host bool tud_connected(void); // Check if device is connected and configured diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index 8ed0ad1c0..d15380199 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -67,12 +67,7 @@ static inline bool _status_stage_xact(uint8_t rhport, tusb_control_request_t con { // Opposite to endpoint in Data Phase uint8_t const ep_addr = request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN; - - TU_LOG2(" Queue EP %02X with zlp Status\r\n", ep_addr); - - // status direction is reversed to one in the setup packet - // Note: Status must always be DATA1 - return dcd_edpt_xfer(rhport, ep_addr, NULL, 0); + return usbd_edpt_xfer(rhport, ep_addr, NULL, 0); } // Status phase @@ -101,9 +96,7 @@ static bool _data_stage_xact(uint8_t rhport) if ( xact_len ) memcpy(_usbd_ctrl_buf, _ctrl_xfer.buffer, xact_len); } - TU_LOG2(" Queue EP %02X with %u bytes\r\n", ep_addr, xact_len); - - return dcd_edpt_xfer(rhport, ep_addr, xact_len ? _usbd_ctrl_buf : NULL, xact_len); + return usbd_edpt_xfer(rhport, ep_addr, xact_len ? _usbd_ctrl_buf : NULL, xact_len); } // Transmit data to/from the control endpoint. @@ -140,9 +133,6 @@ bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, vo // USBD API //--------------------------------------------------------------------+ -//--------------------------------------------------------------------+ -// Prototypes -//--------------------------------------------------------------------+ void usbd_control_reset(void); void usbd_control_set_request(tusb_control_request_t const *request); void usbd_control_set_complete_callback( usbd_control_xfer_cb_t fp ); @@ -153,13 +143,13 @@ void usbd_control_reset(void) tu_varclr(&_ctrl_xfer); } -// TODO may find a better way +// Set complete callback void usbd_control_set_complete_callback( usbd_control_xfer_cb_t fp ) { _ctrl_xfer.complete_cb = fp; } -// useful for dcd_set_address where DCD is responsible for status response +// for dcd_set_address where DCD is responsible for status response void usbd_control_set_request(tusb_control_request_t const *request) { _ctrl_xfer.request = (*request); diff --git a/src/host/usbh.c b/src/host/usbh.c index e7347ff56..f278f4d94 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -151,6 +151,12 @@ tusb_device_state_t tuh_device_get_state (uint8_t const dev_addr) return (tusb_device_state_t) _usbh_devices[dev_addr].state; } +tusb_speed_t tuh_device_get_speed (uint8_t const dev_addr) +{ + TU_ASSERT( dev_addr <= CFG_TUSB_HOST_DEVICE_MAX, TUSB_SPEED_INVALID); + return (tusb_speed_t) _usbh_devices[dev_addr].speed; +} + void osal_task_delay(uint32_t msec) { (void) msec; diff --git a/src/host/usbh.h b/src/host/usbh.h index 12c9164dd..a05010b36 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -86,6 +86,7 @@ extern void hcd_int_handler(uint8_t rhport); #define tuh_int_handler hcd_int_handler tusb_device_state_t tuh_device_get_state (uint8_t dev_addr); +tusb_speed_t tuh_device_get_speed (uint8_t dev_addr); static inline bool tuh_device_is_configured(uint8_t dev_addr) { return tuh_device_get_state(dev_addr) == TUSB_DEVICE_STATE_CONFIGURED; diff --git a/src/osal/osal.h b/src/osal/osal.h index b5057ff4c..02e3e0a06 100644 --- a/src/osal/osal.h +++ b/src/osal/osal.h @@ -53,6 +53,10 @@ typedef void (*osal_task_func_t)( void * ); #include "osal_freertos.h" #elif CFG_TUSB_OS == OPT_OS_MYNEWT #include "osal_mynewt.h" +#elif CFG_TUSB_OS == OPT_OS_PICO + #include "osal_pico.h" +#elif CFG_TUSB_OS == OPT_OS_RTTHREAD + #include "osal_rtthread.h" #elif CFG_TUSB_OS == OPT_OS_CUSTOM #include "tusb_os_custom.h" // implemented by application #else diff --git a/src/osal/osal_pico.h b/src/osal/osal_pico.h new file mode 100644 index 000000000..1788e5c8d --- /dev/null +++ b/src/osal/osal_pico.h @@ -0,0 +1,192 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * 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_OSAL_PICO_H_ +#define _TUSB_OSAL_PICO_H_ + +#include "pico/time.h" +#include "pico/sem.h" +#include "pico/mutex.h" +#include "pico/critical_section.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// TASK API +//--------------------------------------------------------------------+ +#ifndef RP2040_USB_HOST_MODE +static inline void osal_task_delay(uint32_t msec) +{ + sleep_ms(msec); +} +#endif + +//--------------------------------------------------------------------+ +// Binary Semaphore API +//--------------------------------------------------------------------+ +typedef struct semaphore osal_semaphore_def_t, *osal_semaphore_t; + +static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef) +{ + sem_init(semdef, 0, 255); + return semdef; +} + +static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) +{ + sem_release(sem_hdl); + return true; +} + +static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec) +{ + return sem_acquire_timeout_ms(sem_hdl, msec); +} + +static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl) +{ + sem_reset(sem_hdl, 0); +} + +//--------------------------------------------------------------------+ +// MUTEX API +// Within tinyusb, mutex is never used in ISR context +//--------------------------------------------------------------------+ +typedef struct mutex osal_mutex_def_t, *osal_mutex_t; + +static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef) +{ + mutex_init(mdef); + return mdef; +} + +static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec) +{ + return mutex_enter_timeout_ms(mutex_hdl, msec); +} + +static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl) +{ + mutex_exit(mutex_hdl); + return true; +} + +//--------------------------------------------------------------------+ +// QUEUE API +//--------------------------------------------------------------------+ +#include "common/tusb_fifo.h" + +#if TUSB_OPT_HOST_ENABLED +extern void hcd_int_disable(uint8_t rhport); +extern void hcd_int_enable(uint8_t rhport); +#endif + +typedef struct +{ + tu_fifo_t ff; + struct critical_section critsec; // osal_queue may be used in IRQs, so need critical section +} osal_queue_def_t; + +typedef osal_queue_def_t* osal_queue_t; + +// role device/host is used by OS NONE for mutex (disable usb isr) only +#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \ + uint8_t _name##_buf[_depth*sizeof(_type)]; \ + osal_queue_def_t _name = { \ + .ff = { \ + .buffer = _name##_buf, \ + .depth = _depth, \ + .item_size = sizeof(_type), \ + .overwritable = false, \ + }\ + } + +// lock queue by disable USB interrupt +static inline void _osal_q_lock(osal_queue_t qhdl) +{ + critical_section_enter_blocking(&qhdl->critsec); +} + +// unlock queue +static inline void _osal_q_unlock(osal_queue_t qhdl) +{ + critical_section_exit(&qhdl->critsec); +} + +static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) +{ + critical_section_init(&qdef->critsec); + tu_fifo_clear(&qdef->ff); + return (osal_queue_t) qdef; +} + +static inline bool osal_queue_receive(osal_queue_t qhdl, void* data) +{ + // TODO: revisit... docs say that mutexes are never used from IRQ context, + // however osal_queue_recieve may be. therefore my assumption is that + // the fifo mutex is not populated for queues used from an IRQ context + assert(!qhdl->ff.mutex); + + _osal_q_lock(qhdl); + bool success = tu_fifo_read(&qhdl->ff, data); + _osal_q_unlock(qhdl); + + return success; +} + +static inline bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr) +{ + // TODO: revisit... docs say that mutexes are never used from IRQ context, + // however osal_queue_recieve may be. therefore my assumption is that + // the fifo mutex is not populated for queues used from an IRQ context + assert(!qhdl->ff.mutex); + + _osal_q_lock(qhdl); + bool success = tu_fifo_write(&qhdl->ff, data); + _osal_q_unlock(qhdl); + + TU_ASSERT(success); + + return success; +} + +static inline bool osal_queue_empty(osal_queue_t qhdl) +{ + // TODO: revisit; whether this is true or not currently, tu_fifo_empty is a single + // volatile read. + + // Skip queue lock/unlock since this function is primarily called + // with interrupt disabled before going into low power mode + return tu_fifo_empty(&qhdl->ff); +} + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_OSAL_PICO_H_ */ diff --git a/src/osal/osal_rtthread.h b/src/osal/osal_rtthread.h new file mode 100644 index 000000000..d5c062ac1 --- /dev/null +++ b/src/osal/osal_rtthread.h @@ -0,0 +1,130 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 tfx2001 ([email protected]) + * + * 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_OSAL_RTTHREAD_H_ +#define _TUSB_OSAL_RTTHREAD_H_ + +// RT-Thread Headers +#include "rtthread.h" + +#ifdef __cplusplus +extern "C" { +#endif + +//--------------------------------------------------------------------+ +// TASK API +//--------------------------------------------------------------------+ +static inline void osal_task_delay(uint32_t msec) { + rt_thread_mdelay(msec); +} + +//--------------------------------------------------------------------+ +// Semaphore API +//--------------------------------------------------------------------+ +typedef struct rt_semaphore osal_semaphore_def_t; +typedef rt_sem_t osal_semaphore_t; + +static inline osal_semaphore_t +osal_semaphore_create(osal_semaphore_def_t *semdef) { + rt_sem_init(semdef, "tusb", 0, RT_IPC_FLAG_FIFO); + return semdef; +} + +static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) { + (void) in_isr; + return rt_sem_release(sem_hdl) == RT_EOK; +} + +static inline bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec) { + return rt_sem_take(sem_hdl, rt_tick_from_millisecond(msec)) == RT_EOK; +} + +static inline void osal_semaphore_reset(osal_semaphore_t const sem_hdl) { + // TODO: implement +} + +//--------------------------------------------------------------------+ +// MUTEX API (priority inheritance) +//--------------------------------------------------------------------+ +typedef struct rt_mutex osal_mutex_def_t; +typedef rt_mutex_t osal_mutex_t; + +static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t *mdef) { + rt_mutex_init(mdef, "tusb", RT_IPC_FLAG_FIFO); + return mdef; +} + +static inline bool osal_mutex_lock(osal_mutex_t mutex_hdl, uint32_t msec) { + return rt_mutex_take(mutex_hdl, rt_tick_from_millisecond(msec)) == RT_EOK; +} + +static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl) { + return rt_mutex_release(mutex_hdl) == RT_EOK; +} + +//--------------------------------------------------------------------+ +// QUEUE API +//--------------------------------------------------------------------+ + +// role device/host is used by OS NONE for mutex (disable usb isr) only +#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \ + static _type _name##_##buf[_depth]; \ + osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf }; + +typedef struct { + uint16_t depth; + uint16_t item_sz; + void *buf; + + struct rt_messagequeue sq; +} osal_queue_def_t; + +typedef rt_mq_t osal_queue_t; + +static inline osal_queue_t osal_queue_create(osal_queue_def_t *qdef) { + rt_mq_init(&(qdef->sq), "tusb", qdef->buf, qdef->item_sz, + qdef->item_sz * qdef->depth, RT_IPC_FLAG_FIFO); + return &(qdef->sq); +} + +static inline bool osal_queue_receive(osal_queue_t qhdl, void *data) { + return rt_mq_recv(qhdl, data, qhdl->msg_size, RT_WAITING_FOREVER) == RT_EOK; +} + +static inline bool osal_queue_send(osal_queue_t qhdl, void const *data, bool in_isr) { + (void) in_isr; + return rt_mq_send(qhdl, (void *)data, qhdl->msg_size) == RT_EOK; +} + +static inline bool osal_queue_empty(osal_queue_t qhdl) { + return (qhdl->entry) == 0; +} + +#ifdef __cplusplus +} +#endif + +#endif /* _TUSB_OSAL_RTTHREAD_H_ */ diff --git a/src/portable/raspberrypi/rp2040/dcd_rp2040.c b/src/portable/raspberrypi/rp2040/dcd_rp2040.c new file mode 100644 index 000000000..95b0963a3 --- /dev/null +++ b/src/portable/raspberrypi/rp2040/dcd_rp2040.c @@ -0,0 +1,481 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * 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 TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_RP2040 + +#include "pico.h" +#include "rp2040_usb.h" + +#if TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX +#include "pico/fix/rp2040_usb_device_enumeration.h" +#endif + + +#include "device/dcd.h" + +/*------------------------------------------------------------------*/ +/* Low level controller + *------------------------------------------------------------------*/ + +#define usb_hw_set hw_set_alias(usb_hw) +#define usb_hw_clear hw_clear_alias(usb_hw) + +// Init these in dcd_init +static uint8_t *next_buffer_ptr; + +// Endpoints 0-15, direction 0 for out and 1 for in. +static struct hw_endpoint hw_endpoints[16][2] = {0}; + +static inline struct hw_endpoint *hw_endpoint_get_by_num(uint8_t num, uint8_t in) +{ + return &hw_endpoints[num][in]; +} + +static struct hw_endpoint *hw_endpoint_get_by_addr(uint8_t ep_addr) +{ + uint8_t num = tu_edpt_number(ep_addr); + uint8_t in = (ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0; + return hw_endpoint_get_by_num(num, in); +} +static void _hw_endpoint_alloc(struct hw_endpoint *ep) +{ + uint size = TU_MIN(64, ep->wMaxPacketSize); + + // Assumes single buffered for now + ep->hw_data_buf = next_buffer_ptr; + next_buffer_ptr += size; + // Bits 0-5 are ignored by the controller so make sure these are 0 + if ((uintptr_t)next_buffer_ptr & 0b111111u) + { + // Round up to the next 64 + uint32_t fixptr = (uintptr_t)next_buffer_ptr; + fixptr &= ~0b111111u; + fixptr += 64; + pico_info("Rounding non 64 byte boundary buffer up from %x to %x\n", (uintptr_t)next_buffer_ptr, fixptr); + next_buffer_ptr = (uint8_t*)fixptr; + } + assert(((uintptr_t)next_buffer_ptr & 0b111111u) == 0); + uint dpram_offset = hw_data_offset(ep->hw_data_buf); + assert(hw_data_offset(next_buffer_ptr) <= USB_DPRAM_MAX); + + pico_info("Alloced %d bytes at offset 0x%x (0x%p) for ep %d %s\n", + size, + dpram_offset, + ep->hw_data_buf, + ep->num, + ep_dir_string[ep->in]); + + // Fill in endpoint control register with buffer offset + uint32_t reg = EP_CTRL_ENABLE_BITS + | EP_CTRL_INTERRUPT_PER_BUFFER + | (ep->transfer_type << EP_CTRL_BUFFER_TYPE_LSB) + | dpram_offset; + + *ep->endpoint_control = reg; +} + +static void _hw_endpoint_init(struct hw_endpoint *ep, uint8_t ep_addr, uint wMaxPacketSize, uint8_t transfer_type) +{ + uint8_t num = tu_edpt_number(ep_addr); + bool in = ep_addr & TUSB_DIR_IN_MASK; + ep->ep_addr = ep_addr; + ep->in = in; + // For device, IN is a tx transfer and OUT is an rx transfer + ep->rx = in == false; + ep->num = num; + // Response to a setup packet on EP0 starts with pid of 1 + ep->next_pid = num == 0 ? 1u : 0u; + + // Add some checks around the max packet size + if (transfer_type == TUSB_XFER_ISOCHRONOUS) + { + if (wMaxPacketSize > USB_MAX_ISO_PACKET_SIZE) + { + panic("Isochronous wMaxPacketSize %d too large", wMaxPacketSize); + } + } + else + { + if (wMaxPacketSize > USB_MAX_PACKET_SIZE) + { + panic("Isochronous wMaxPacketSize %d too large", wMaxPacketSize); + } + } + + ep->wMaxPacketSize = wMaxPacketSize; + ep->transfer_type = transfer_type; + + // Every endpoint has a buffer control register in dpram + if (ep->in) + { + ep->buffer_control = &usb_dpram->ep_buf_ctrl[num].in; + } + else + { + ep->buffer_control = &usb_dpram->ep_buf_ctrl[num].out; + } + + // Clear existing buffer control state + *ep->buffer_control = 0; + + if (ep->num == 0) + { + // EP0 has no endpoint control register because + // the buffer offsets are fixed + ep->endpoint_control = NULL; + + // Buffer offset is fixed + ep->hw_data_buf = (uint8_t*)&usb_dpram->ep0_buf_a[0]; + } + else + { + // Set the endpoint control register (starts at EP1, hence num-1) + if (in) + { + ep->endpoint_control = &usb_dpram->ep_ctrl[num-1].in; + } + else + { + ep->endpoint_control = &usb_dpram->ep_ctrl[num-1].out; + } + + // Now if it hasn't already been done + //alloc a buffer and fill in endpoint control register + if(!(ep->configured)) + { + _hw_endpoint_alloc(ep); + } + } + + ep->configured = true; +} + +#if 0 // todo unused +static void _hw_endpoint_close(struct hw_endpoint *ep) +{ + // Clear hardware registers and then zero the struct + // Clears endpoint enable + *ep->endpoint_control = 0; + // Clears buffer available, etc + *ep->buffer_control = 0; + // Clear any endpoint state + memset(ep, 0, sizeof(struct hw_endpoint)); +} + +static void hw_endpoint_close(uint8_t ep_addr) +{ + struct hw_endpoint *ep = hw_endpoint_get_by_addr(ep_addr); + _hw_endpoint_close(ep); +} +#endif + +static void hw_endpoint_init(uint8_t ep_addr, uint wMaxPacketSize, uint8_t bmAttributes) +{ + struct hw_endpoint *ep = hw_endpoint_get_by_addr(ep_addr); + _hw_endpoint_init(ep, ep_addr, wMaxPacketSize, bmAttributes); +} + +static void hw_endpoint_xfer(uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes, bool start) +{ + struct hw_endpoint *ep = hw_endpoint_get_by_addr(ep_addr); + _hw_endpoint_xfer(ep, buffer, total_bytes, start); +} + +static void hw_handle_buff_status(void) +{ + uint32_t remaining_buffers = usb_hw->buf_status; + pico_trace("buf_status 0x%08x\n", remaining_buffers); + uint bit = 1u; + for (uint i = 0; remaining_buffers && i < USB_MAX_ENDPOINTS * 2; i++) + { + if (remaining_buffers & bit) + { + uint __unused which = (usb_hw->buf_cpu_should_handle & bit) ? 1 : 0; + // Should be single buffered + assert(which == 0); + // clear this in advance + usb_hw_clear->buf_status = bit; + // IN transfer for even i, OUT transfer for odd i + struct hw_endpoint *ep = hw_endpoint_get_by_num(i >> 1u, !(i & 1u)); + // Continue xfer + bool done = _hw_endpoint_xfer_continue(ep); + if (done) + { + // Notify + dcd_event_xfer_complete(0, ep->ep_addr, ep->len, XFER_RESULT_SUCCESS, true); + hw_endpoint_reset_transfer(ep); + } + remaining_buffers &= ~bit; + } + bit <<= 1u; + } +} + +static void reset_ep0(void) +{ + // If we have finished this transfer on EP0 set pid back to 1 for next + // setup transfer. Also clear a stall in case + uint8_t addrs[] = {0x0, 0x80}; + for (uint i = 0 ; i < TU_ARRAY_SIZE(addrs); i++) + { + struct hw_endpoint *ep = hw_endpoint_get_by_addr(addrs[i]); + ep->next_pid = 1u; + ep->stalled = 0; + } +} + +static void ep0_0len_status(void) +{ + // Send 0len complete response on EP0 IN + reset_ep0(); + hw_endpoint_xfer(0x80, NULL, 0, true); +} + +static void _hw_endpoint_stall(struct hw_endpoint *ep) +{ + assert(!ep->stalled); + if (ep->num == 0) + { + // A stall on EP0 has to be armed so it can be cleared on the next setup packet + usb_hw_set->ep_stall_arm = ep->in ? USB_EP_STALL_ARM_EP0_IN_BITS : USB_EP_STALL_ARM_EP0_OUT_BITS; + } + _hw_endpoint_buffer_control_set_mask32(ep, USB_BUF_CTRL_STALL); + ep->stalled = true; +} + +static void hw_endpoint_stall(uint8_t ep_addr) +{ + struct hw_endpoint *ep = hw_endpoint_get_by_addr(ep_addr); + _hw_endpoint_stall(ep); +} + +static void _hw_endpoint_clear_stall(struct hw_endpoint *ep) +{ + if (ep->num == 0) + { + // Probably already been cleared but no harm + usb_hw_clear->ep_stall_arm = ep->in ? USB_EP_STALL_ARM_EP0_IN_BITS : USB_EP_STALL_ARM_EP0_OUT_BITS; + } + _hw_endpoint_buffer_control_clear_mask32(ep, USB_BUF_CTRL_STALL); + ep->stalled = false; +} + +static void hw_endpoint_clear_stall(uint8_t ep_addr) +{ + struct hw_endpoint *ep = hw_endpoint_get_by_addr(ep_addr); + _hw_endpoint_clear_stall(ep); +} + +static void dcd_rp2040_irq(void) +{ + uint32_t status = usb_hw->ints; + uint32_t handled = 0; + + if (status & USB_INTS_SETUP_REQ_BITS) + { + handled |= USB_INTS_SETUP_REQ_BITS; + uint8_t const *setup = (uint8_t const *)&usb_dpram->setup_packet; + // Clear stall bits and reset pid + reset_ep0(); + // Pass setup packet to tiny usb + dcd_event_setup_received(0, setup, true); + usb_hw_clear->sie_status = USB_SIE_STATUS_SETUP_REC_BITS; + } + + if (status & USB_INTS_BUFF_STATUS_BITS) + { + handled |= USB_INTS_BUFF_STATUS_BITS; + hw_handle_buff_status(); + } + + if (status & USB_INTS_BUS_RESET_BITS) + { + pico_trace("BUS RESET (addr %d -> %d)\n", assigned_address, 0); + usb_hw->dev_addr_ctrl = 0; + handled |= USB_INTS_BUS_RESET_BITS; + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + usb_hw_clear->sie_status = USB_SIE_STATUS_BUS_RESET_BITS; +#if TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX + rp2040_usb_device_enumeration_fix(); +#endif + } + + if (status ^ handled) + { + panic("Unhandled IRQ 0x%x\n", (uint) (status ^ handled)); + } +} + +#define USB_INTS_ERROR_BITS ( \ + USB_INTS_ERROR_DATA_SEQ_BITS | \ + USB_INTS_ERROR_BIT_STUFF_BITS | \ + USB_INTS_ERROR_CRC_BITS | \ + USB_INTS_ERROR_RX_OVERFLOW_BITS | \ + USB_INTS_ERROR_RX_TIMEOUT_BITS) + +/*------------------------------------------------------------------*/ +/* Controller API + *------------------------------------------------------------------*/ +void dcd_init (uint8_t rhport) +{ + pico_trace("dcd_init %d\n", rhport); + assert(rhport == 0); + + // Reset hardware to default state + rp2040_usb_init(); + + irq_set_exclusive_handler(USBCTRL_IRQ, dcd_rp2040_irq); + memset(hw_endpoints, 0, sizeof(hw_endpoints)); + next_buffer_ptr = &usb_dpram->epx_data[0]; + + // EP0 always exists so init it now + // EP0 OUT + hw_endpoint_init(0x0, 64, 0); + // EP0 IN + hw_endpoint_init(0x80, 64, 0); + + // Initializes the USB peripheral for device mode and enables it. + // Don't need to enable the pull up here. Force VBUS + usb_hw->main_ctrl = USB_MAIN_CTRL_CONTROLLER_EN_BITS; + + // Enable individual controller IRQS here. Processor interrupt enable will be used + // for the global interrupt enable... + usb_hw->sie_ctrl = USB_SIE_CTRL_EP0_INT_1BUF_BITS; + usb_hw->inte = USB_INTS_BUFF_STATUS_BITS | USB_INTS_BUS_RESET_BITS | USB_INTS_SETUP_REQ_BITS; + + dcd_connect(rhport); +} + +void dcd_int_enable(uint8_t rhport) +{ + assert(rhport == 0); + irq_set_enabled(USBCTRL_IRQ, true); +} + +void dcd_int_disable(uint8_t rhport) +{ + assert(rhport == 0); + irq_set_enabled(USBCTRL_IRQ, false); +} + +void dcd_set_address (uint8_t rhport, uint8_t dev_addr) +{ + pico_trace("dcd_set_address %d %d\n", rhport, dev_addr); + assert(rhport == 0); + + // Can't set device address in hardware until status xfer has complete + ep0_0len_status(); +} + +void dcd_remote_wakeup(uint8_t rhport) +{ + pico_info("dcd_remote_wakeup %d is not supported yet\n", rhport); + assert(rhport == 0); +} + +// disconnect by disabling internal pull-up resistor on D+/D- +void dcd_disconnect(uint8_t rhport) +{ + pico_info("dcd_disconnect %d\n", rhport); + assert(rhport == 0); + usb_hw_clear->sie_ctrl = USB_SIE_CTRL_PULLUP_EN_BITS; +} + +// connect by enabling internal pull-up resistor on D+/D- +void dcd_connect(uint8_t rhport) +{ + pico_info("dcd_connect %d\n", rhport); + assert(rhport == 0); + usb_hw_set->sie_ctrl = USB_SIE_CTRL_PULLUP_EN_BITS; +} + +/*------------------------------------------------------------------*/ +/* DCD Endpoint port + *------------------------------------------------------------------*/ + +void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) +{ + pico_trace("dcd_edpt0_status_complete %d\n", rhport); + assert(rhport == 0); + + if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE && + request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && + request->bRequest == TUSB_REQ_SET_ADDRESS) + { + pico_trace("Set HW address %d\n", assigned_address); + usb_hw->dev_addr_ctrl = (uint8_t) request->wValue; + } + + reset_ep0(); +} + +bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) +{ + pico_info("dcd_edpt_open %d %02x\n", rhport, desc_edpt->bEndpointAddress); + assert(rhport == 0); + hw_endpoint_init(desc_edpt->bEndpointAddress, desc_edpt->wMaxPacketSize.size, desc_edpt->bmAttributes.xfer); + return true; +} + +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) +{ + assert(rhport == 0); + // True means start new xfer + hw_endpoint_xfer(ep_addr, buffer, total_bytes, true); + return true; +} + +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) +{ + pico_trace("dcd_edpt_stall %d %02x\n", rhport, ep_addr); + assert(rhport == 0); + hw_endpoint_stall(ep_addr); +} + +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) +{ + pico_trace("dcd_edpt_clear_stall %d %02x\n", rhport, ep_addr); + assert(rhport == 0); + hw_endpoint_clear_stall(ep_addr); +} + + +void dcd_edpt_close (uint8_t rhport, uint8_t ep_addr) +{ + // usbd.c says: In progress transfers on this EP may be delivered after this call + pico_trace("dcd_edpt_close %d %02x\n", rhport, ep_addr); + +} + +void dcd_int_handler(uint8_t rhport) +{ + (void) rhport; + dcd_rp2040_irq(); +} + +#endif diff --git a/src/portable/raspberrypi/rp2040/hcd_rp2040.c b/src/portable/raspberrypi/rp2040/hcd_rp2040.c new file mode 100644 index 000000000..efb2bd430 --- /dev/null +++ b/src/portable/raspberrypi/rp2040/hcd_rp2040.c @@ -0,0 +1,550 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * 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 TUSB_OPT_HOST_ENABLED && CFG_TUSB_MCU == OPT_MCU_RP2040 + +#include "pico.h" +#include "rp2040_usb.h" + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "osal/osal.h" + +#include "host/hcd.h" +#include "host/usbh.h" +#include "host/usbh_hcd.h" + +#define ROOT_PORT 0 + +//--------------------------------------------------------------------+ +// Low level rp2040 controller functions +//--------------------------------------------------------------------+ + +#ifndef PICO_USB_HOST_INTERRUPT_ENDPOINTS +#define PICO_USB_HOST_INTERRUPT_ENDPOINTS (USB_MAX_ENDPOINTS - 1) +#endif +static_assert(PICO_USB_HOST_INTERRUPT_ENDPOINTS <= USB_MAX_ENDPOINTS, ""); + +// Host mode uses one shared endpoint register for non-interrupt endpoint +struct hw_endpoint eps[1 + PICO_USB_HOST_INTERRUPT_ENDPOINTS]; +#define epx (eps[0]) + +#define usb_hw_set hw_set_alias(usb_hw) +#define usb_hw_clear hw_clear_alias(usb_hw) + +// Used for hcd pipe busy. +// todo still a bit wasteful +// top bit set if valid +uint8_t dev_ep_map[CFG_TUSB_HOST_DEVICE_MAX][1 + PICO_USB_HOST_INTERRUPT_ENDPOINTS][2]; + +// Flags we set by default in sie_ctrl (we add other bits on top) +static uint32_t sie_ctrl_base = USB_SIE_CTRL_SOF_EN_BITS | + USB_SIE_CTRL_KEEP_ALIVE_EN_BITS | + USB_SIE_CTRL_PULLDOWN_EN_BITS | + USB_SIE_CTRL_EP0_INT_1BUF_BITS; + +static struct hw_endpoint *get_dev_ep(uint8_t dev_addr, uint8_t ep_addr) +{ + uint8_t num = tu_edpt_number(ep_addr); + if (num == 0) { + return &epx; + } + uint8_t in = (ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0; + uint mapping = dev_ep_map[dev_addr-1][num][in]; + pico_trace("Get dev addr %d ep %d = %d\n", dev_addr, ep_addr, mapping); + return mapping >= 128 ? eps + (mapping & 0x7fu) : NULL; +} + +static void set_dev_ep(uint8_t dev_addr, uint8_t ep_addr, struct hw_endpoint *ep) +{ + uint8_t num = tu_edpt_number(ep_addr); + uint8_t in = (ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0; + uint32_t index = ep - eps; + hard_assert(index < TU_ARRAY_SIZE(eps)); + // todo revisit why dev_addr can be 0 here + if (dev_addr) { + dev_ep_map[dev_addr-1][num][in] = 128u | index; + } + pico_trace("Set dev addr %d ep %d = %d\n", dev_addr, ep_addr, index); +} + +static inline uint8_t dev_speed(void) +{ + return (usb_hw->sie_status & USB_SIE_STATUS_SPEED_BITS) >> USB_SIE_STATUS_SPEED_LSB; +} + +static bool need_pre(uint8_t dev_addr) +{ + // If this device is different to the speed of the root device + // (i.e. is a low speed device on a full speed hub) then need pre + return hcd_port_speed_get(0) != tuh_device_get_speed(dev_addr); +} + +static void hw_xfer_complete(struct hw_endpoint *ep, xfer_result_t xfer_result) +{ + // Mark transfer as done before we tell the tinyusb stack + uint8_t dev_addr = ep->dev_addr; + uint8_t ep_addr = ep->ep_addr; + uint total_len = ep->total_len; + hw_endpoint_reset_transfer(ep); + hcd_event_xfer_complete(dev_addr, ep_addr, total_len, xfer_result, true); +} + +static void _handle_buff_status_bit(uint bit, struct hw_endpoint *ep) +{ + usb_hw_clear->buf_status = bit; + bool done = _hw_endpoint_xfer_continue(ep); + if (done) + { + hw_xfer_complete(ep, XFER_RESULT_SUCCESS); + } +} + +static void hw_handle_buff_status(void) +{ + uint32_t remaining_buffers = usb_hw->buf_status; + pico_trace("buf_status 0x%08x\n", remaining_buffers); + + // Check EPX first + uint bit = 0b1; + if (remaining_buffers & bit) + { + remaining_buffers &= ~bit; + struct hw_endpoint *ep = &epx; + _handle_buff_status_bit(bit, ep); + } + + // Check interrupt endpoints + for (uint i = 1; i <= USB_HOST_INTERRUPT_ENDPOINTS && remaining_buffers; i++) + { + // EPX is bit 0 + // IEP1 is bit 2 + // IEP2 is bit 4 + // IEP3 is bit 6 + // etc + bit = 1 << (i*2); + + if (remaining_buffers & bit) + { + remaining_buffers &= ~bit; + _handle_buff_status_bit(bit, &eps[i]); + } + } + + if (remaining_buffers) + { + panic("Unhandled buffer %d\n", remaining_buffers); + } +} + +static void hw_trans_complete(void) +{ + struct hw_endpoint *ep = &epx; + assert(ep->active); + + if (ep->sent_setup) + { + pico_trace("Sent setup packet\n"); + hw_xfer_complete(ep, XFER_RESULT_SUCCESS); + } + else + { + // Don't care. Will handle this in buff status + return; + } +} + +static void hcd_rp2040_irq(void) +{ + uint32_t status = usb_hw->ints; + uint32_t handled = 0; + + if (status & USB_INTS_HOST_CONN_DIS_BITS) + { + handled |= USB_INTS_HOST_CONN_DIS_BITS; + + if (dev_speed()) + { + hcd_event_device_attach(ROOT_PORT, true); + } + else + { + hcd_event_device_remove(ROOT_PORT, true); + } + + // Clear speed change interrupt + usb_hw_clear->sie_status = USB_SIE_STATUS_SPEED_BITS; + } + + if (status & USB_INTS_TRANS_COMPLETE_BITS) + { + handled |= USB_INTS_TRANS_COMPLETE_BITS; + usb_hw_clear->sie_status = USB_SIE_STATUS_TRANS_COMPLETE_BITS; + hw_trans_complete(); + } + + if (status & USB_INTS_BUFF_STATUS_BITS) + { + handled |= USB_INTS_BUFF_STATUS_BITS; + hw_handle_buff_status(); + } + + if (status & USB_INTS_STALL_BITS) + { + // We have rx'd a stall from the device + pico_trace("Stall REC\n"); + handled |= USB_INTS_STALL_BITS; + usb_hw_clear->sie_status = USB_SIE_STATUS_STALL_REC_BITS; + hw_xfer_complete(&epx, XFER_RESULT_STALLED); + } + + if (status & USB_INTS_ERROR_RX_TIMEOUT_BITS) + { + handled |= USB_INTS_ERROR_RX_TIMEOUT_BITS; + usb_hw_clear->sie_status = USB_SIE_STATUS_RX_TIMEOUT_BITS; + } + + if (status & USB_INTS_ERROR_DATA_SEQ_BITS) + { + usb_hw_clear->sie_status = USB_SIE_STATUS_DATA_SEQ_ERROR_BITS; + panic("Data Seq Error \n"); + } + + if (status ^ handled) + { + panic("Unhandled IRQ 0x%x\n", (uint) (status ^ handled)); + } +} + +static struct hw_endpoint *_next_free_interrupt_ep(void) +{ + struct hw_endpoint *ep = NULL; + for (uint i = 1; i < TU_ARRAY_SIZE(eps); i++) + { + ep = &eps[i]; + if (!ep->configured) + { + // Will be configured by _hw_endpoint_init / _hw_endpoint_allocate + ep->interrupt_num = i - 1; + return ep; + } + } + return ep; +} + +static struct hw_endpoint *_hw_endpoint_allocate(uint8_t transfer_type) +{ + struct hw_endpoint *ep = NULL; + if (transfer_type == TUSB_XFER_INTERRUPT) + { + ep = _next_free_interrupt_ep(); + pico_info("Allocate interrupt ep %d\n", ep->interrupt_num); + assert(ep); + ep->buffer_control = &usbh_dpram->int_ep_buffer_ctrl[ep->interrupt_num].ctrl; + ep->endpoint_control = &usbh_dpram->int_ep_ctrl[ep->interrupt_num].ctrl; + // 0x180 for epx + // 0x1c0 for intep0 + // 0x200 for intep1 + // etc + ep->hw_data_buf = &usbh_dpram->epx_data[64 * (ep->interrupt_num + 1)]; + } + else + { + ep = &epx; + ep->buffer_control = &usbh_dpram->epx_buf_ctrl; + ep->endpoint_control = &usbh_dpram->epx_ctrl; + ep->hw_data_buf = &usbh_dpram->epx_data[0]; + } + return ep; +} + +static void _hw_endpoint_init(struct hw_endpoint *ep, uint8_t dev_addr, uint8_t ep_addr, uint wMaxPacketSize, uint8_t transfer_type, uint8_t bmInterval) +{ + // Already has data buffer, endpoint control, and buffer control allocated at this point + assert(ep->endpoint_control); + assert(ep->buffer_control); + assert(ep->hw_data_buf); + + uint8_t num = tu_edpt_number(ep_addr); + bool in = ep_addr & TUSB_DIR_IN_MASK; + ep->ep_addr = ep_addr; + ep->dev_addr = dev_addr; + ep->in = in; + // For host, IN to host == RX, anything else rx == false + ep->rx = in == true; + ep->num = num; + // Response to a setup packet on EP0 starts with pid of 1 + ep->next_pid = num == 0 ? 1u : 0u; + ep->wMaxPacketSize = wMaxPacketSize; + ep->transfer_type = transfer_type; + + pico_trace("hw_endpoint_init dev %d ep %d %s xfer %d\n", ep->dev_addr, ep->num, ep_dir_string[ep->in], ep->transfer_type); + pico_trace("dev %d ep %d %s setup buffer @ 0x%p\n", ep->dev_addr, ep->num, ep_dir_string[ep->in], ep->hw_data_buf); + uint dpram_offset = hw_data_offset(ep->hw_data_buf); + // Bits 0-5 should be 0 + assert(!(dpram_offset & 0b111111)); + + // Fill in endpoint control register with buffer offset + uint32_t ep_reg = EP_CTRL_ENABLE_BITS + | EP_CTRL_INTERRUPT_PER_BUFFER + | (ep->transfer_type << EP_CTRL_BUFFER_TYPE_LSB) + | dpram_offset; + ep_reg |= bmInterval ? (bmInterval - 1) << EP_CTRL_HOST_INTERRUPT_INTERVAL_LSB : 0; + *ep->endpoint_control = ep_reg; + pico_trace("endpoint control (0x%p) <- 0x%x\n", ep->endpoint_control, ep_reg); + ep->configured = true; + + if (bmInterval) + { + // This is an interrupt endpoint + // so need to set up interrupt endpoint address control register with: + // device address + // endpoint number / direction + // preamble + uint32_t reg = dev_addr | (ep->num << USB_ADDR_ENDP1_ENDPOINT_LSB); + // Assert the interrupt endpoint is IN_TO_HOST + assert(ep->in); + + if (need_pre(dev_addr)) + { + reg |= USB_ADDR_ENDP1_INTEP_PREAMBLE_BITS; + } + usb_hw->int_ep_addr_ctrl[ep->interrupt_num] = reg; + + // Finally, enable interrupt that endpoint + usb_hw_set->int_ep_ctrl = 1 << (ep->interrupt_num + 1); + + // If it's an interrupt endpoint we need to set up the buffer control + // register + + } +} + +static void hw_endpoint_init(uint8_t dev_addr, const tusb_desc_endpoint_t *ep_desc) +{ + // Allocated differently based on if it's an interrupt endpoint or not + struct hw_endpoint *ep = _hw_endpoint_allocate(ep_desc->bmAttributes.xfer); + _hw_endpoint_init(ep, + dev_addr, + ep_desc->bEndpointAddress, + ep_desc->wMaxPacketSize.size, + ep_desc->bmAttributes.xfer, + ep_desc->bInterval); + // Map this struct to ep@device address + set_dev_ep(dev_addr, ep_desc->bEndpointAddress, ep); +} + +//--------------------------------------------------------------------+ +// HCD API +//--------------------------------------------------------------------+ +bool hcd_init(void) +{ + pico_trace("hcd_init\n"); + + // Reset any previous state + rp2040_usb_init(); + + irq_set_exclusive_handler(USBCTRL_IRQ, hcd_rp2040_irq); + + // clear epx and interrupt eps + memset(&eps, 0, sizeof(eps)); + + // Enable in host mode with SOF / Keep alive on + usb_hw->main_ctrl = USB_MAIN_CTRL_CONTROLLER_EN_BITS | USB_MAIN_CTRL_HOST_NDEVICE_BITS; + usb_hw->sie_ctrl = sie_ctrl_base; + usb_hw->inte = USB_INTE_BUFF_STATUS_BITS | + USB_INTE_HOST_CONN_DIS_BITS | + USB_INTE_HOST_RESUME_BITS | + USB_INTE_STALL_BITS | + USB_INTE_TRANS_COMPLETE_BITS | + USB_INTE_ERROR_RX_TIMEOUT_BITS | + USB_INTE_ERROR_DATA_SEQ_BITS ; + + return true; +} + +void hcd_port_reset(uint8_t rhport) +{ + pico_trace("hcd_port_reset\n"); + assert(rhport == 0); + // TODO: Nothing to do here yet. Perhaps need to reset some state? +} + +bool hcd_port_connect_status(uint8_t rhport) +{ + pico_trace("hcd_port_connect_status\n"); + assert(rhport == 0); + return usb_hw->sie_status & USB_SIE_STATUS_SPEED_BITS; +} + +tusb_speed_t hcd_port_speed_get(uint8_t rhport) +{ + pico_trace("hcd_port_speed_get\n"); + assert(rhport == 0); + // TODO: Should enumval this register + switch (dev_speed()) + { + case 1: + return TUSB_SPEED_LOW; + case 2: + return TUSB_SPEED_FULL; + default: + panic("Invalid speed\n"); + } +} + +// Close all opened endpoint belong to this device +void hcd_device_close(uint8_t rhport, uint8_t dev_addr) +{ + pico_trace("hcd_device_close %d\n", dev_addr); +} + +void hcd_int_enable(uint8_t rhport) +{ + assert(rhport == 0); + irq_set_enabled(USBCTRL_IRQ, true); +} + +void hcd_int_disable(uint8_t rhport) +{ + // todo we should check this is disabling from the correct core; note currently this is never called + assert(rhport == 0); + irq_set_enabled(USBCTRL_IRQ, false); +} + +bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) +{ + pico_info("hcd_edpt_xfer dev_addr %d, ep_addr 0x%x, len %d\n", dev_addr, ep_addr, buflen); + + // Get appropriate ep. Either EPX or interrupt endpoint + struct hw_endpoint *ep = get_dev_ep(dev_addr, ep_addr); + assert(ep); + + if (ep_addr != ep->ep_addr) + { + // Direction has flipped so re init it but with same properties + _hw_endpoint_init(ep, dev_addr, ep_addr, ep->wMaxPacketSize, ep->transfer_type, 0); + } + + // True indicates this is the start of the transfer + _hw_endpoint_xfer(ep, buffer, buflen, true); + + // If a normal transfer (non-interrupt) then initiate using + // sie ctrl registers. Otherwise interrupt ep registers should + // already be configured + if (ep == &epx) { + // That has set up buffer control, endpoint control etc + // for host we have to initiate the transfer + usb_hw->dev_addr_ctrl = dev_addr | ep->num << USB_ADDR_ENDP_ENDPOINT_LSB; + uint32_t flags = USB_SIE_CTRL_START_TRANS_BITS | sie_ctrl_base; + flags |= ep->rx ? USB_SIE_CTRL_RECEIVE_DATA_BITS : USB_SIE_CTRL_SEND_DATA_BITS; + // Set pre if we are a low speed device on full speed hub + flags |= need_pre(dev_addr) ? USB_SIE_CTRL_PREAMBLE_EN_BITS : 0; + usb_hw->sie_ctrl = flags; + } + + return true; +} + +bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) +{ + pico_info("hcd_setup_send dev_addr %d\n", dev_addr); + + // Copy data into setup packet buffer + memcpy((void*)&usbh_dpram->setup_packet[0], setup_packet, 8); + + // Configure EP0 struct with setup info for the trans complete + struct hw_endpoint *ep = _hw_endpoint_allocate(0); + // EP0 out + _hw_endpoint_init(ep, dev_addr, 0x00, ep->wMaxPacketSize, 0, 0); + assert(ep->configured); + assert(ep->num == 0 && !ep->in); + ep->total_len = 8; + ep->transfer_size = 8; + ep->active = true; + ep->sent_setup = true; + + // Set device address + usb_hw->dev_addr_ctrl = dev_addr; + // Set pre if we are a low speed device on full speed hub + uint32_t flags = sie_ctrl_base | USB_SIE_CTRL_SEND_SETUP_BITS | USB_SIE_CTRL_START_TRANS_BITS; + flags |= need_pre(dev_addr) ? USB_SIE_CTRL_PREAMBLE_EN_BITS : 0; + usb_hw->sie_ctrl = flags; + return true; +} + +uint32_t hcd_uframe_number(uint8_t rhport) +{ + // Microframe number is (125us) but we are max full speed so return miliseconds * 8 + return usb_hw->sof_rd * 8; +} + +bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) +{ + pico_trace("hcd_edpt_open dev_addr %d, ep_addr %d\n", dev_addr, ep_desc->bEndpointAddress); + hw_endpoint_init(dev_addr, ep_desc); + return true; +} + +bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) +{ + // EPX is shared, so multiple device addresses and endpoint addresses share that + // so if any transfer is active on epx, we are busy. Interrupt endpoints have their own + // EPX so ep->active will only be busy if there is a pending transfer on that interrupt endpoint + // on that device + pico_trace("hcd_edpt_busy dev addr %d ep_addr 0x%x\n", dev_addr, ep_addr); + struct hw_endpoint *ep = get_dev_ep(dev_addr, ep_addr); + assert(ep); + bool busy = ep->active; + pico_trace("busy == %d\n", busy); + return busy; +} + +bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr) +{ + panic("hcd_pipe_stalled"); +} + +bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr) +{ + panic("hcd_clear_stall"); + return true; +} + +bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete) +{ + pico_trace("hcd_pipe_xfer dev_addr %d, ep_addr 0x%x, total_bytes %d, int_on_complete %d\n", + dev_addr, ep_addr, total_bytes, int_on_complete); + + // Same logic as hcd_edpt_xfer as far as I am concerned + hcd_edpt_xfer(0, dev_addr, ep_addr, buffer, total_bytes); + + return true; +} +#endif diff --git a/src/portable/raspberrypi/rp2040/rp2040_usb.c b/src/portable/raspberrypi/rp2040/rp2040_usb.c new file mode 100644 index 000000000..5c536e314 --- /dev/null +++ b/src/portable/raspberrypi/rp2040/rp2040_usb.c @@ -0,0 +1,283 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * 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_TUSB_MCU == OPT_MCU_RP2040 + +#include <stdlib.h> +#include "rp2040_usb.h" +#include "hardware/clocks.h" + +// Direction strings for debug +const char *ep_dir_string[] = { + "out", + "in", +}; + +static inline void _hw_endpoint_lock_update(struct hw_endpoint *ep, int delta) { + // todo add critsec as necessary to prevent issues between worker and IRQ... + // note that this is perhaps as simple as disabling IRQs because it would make + // sense to have worker and IRQ on same core, however I think using critsec is about equivalent. +} + +static inline void _hw_endpoint_update_last_buf(struct hw_endpoint *ep) +{ + ep->last_buf = ep->len + ep->transfer_size == ep->total_len; +} + +void rp2040_usb_init(void) +{ + // Reset usb controller + reset_block(RESETS_RESET_USBCTRL_BITS); + unreset_block_wait(RESETS_RESET_USBCTRL_BITS); + + // Clear any previous state just in case + memset(usb_hw, 0, sizeof(*usb_hw)); + memset(usb_dpram, 0, sizeof(*usb_dpram)); + + // Mux to phy + usb_hw->muxing = USB_USB_MUXING_TO_PHY_BITS | USB_USB_MUXING_SOFTCON_BITS; + usb_hw->pwr = USB_USB_PWR_VBUS_DETECT_BITS | USB_USB_PWR_VBUS_DETECT_OVERRIDE_EN_BITS; +} + +void hw_endpoint_reset_transfer(struct hw_endpoint *ep) +{ + ep->stalled = false; + ep->active = false; + ep->sent_setup = false; + ep->total_len = 0; + ep->len = 0; + ep->transfer_size = 0; + ep->user_buf = 0; +} + +void _hw_endpoint_buffer_control_update32(struct hw_endpoint *ep, uint32_t and_mask, uint32_t or_mask) { + uint32_t value = 0; + if (and_mask) { + value = *ep->buffer_control & and_mask; + } + if (or_mask) { + value |= or_mask; + if (or_mask & USB_BUF_CTRL_AVAIL) { + if (*ep->buffer_control & USB_BUF_CTRL_AVAIL) { + panic("ep %d %s was already available", ep->num, ep_dir_string[ep->in]); + } + *ep->buffer_control = value & ~USB_BUF_CTRL_AVAIL; + // 12 cycle delay.. (should be good for 48*12Mhz = 576Mhz) + // Don't need delay in host mode as host is in charge +#ifndef RP2040_USB_HOST_MODE + __asm volatile ( + "b 1f\n" + "1: b 1f\n" + "1: b 1f\n" + "1: b 1f\n" + "1: b 1f\n" + "1: b 1f\n" + "1:\n" + : : : "memory"); +#endif + } + } + *ep->buffer_control = value; +} + +void _hw_endpoint_start_next_buffer(struct hw_endpoint *ep) +{ + // Prepare buffer control register value + uint32_t val = ep->transfer_size | USB_BUF_CTRL_AVAIL; + + if (!ep->rx) + { + // Copy data from user buffer to hw buffer + memcpy(ep->hw_data_buf, &ep->user_buf[ep->len], ep->transfer_size); + // Mark as full + val |= USB_BUF_CTRL_FULL; + } + + // PID + val |= ep->next_pid ? USB_BUF_CTRL_DATA1_PID : USB_BUF_CTRL_DATA0_PID; + ep->next_pid ^= 1u; + + // Is this the last buffer? Only really matters for host mode. Will trigger + // the trans complete irq but also stop it polling. We only really care about + // trans complete for setup packets being sent + if (ep->last_buf) + { + pico_trace("Last buf (%d bytes left)\n", ep->transfer_size); + val |= USB_BUF_CTRL_LAST; + } + + // Finally, write to buffer_control which will trigger the transfer + // the next time the controller polls this dpram address + _hw_endpoint_buffer_control_set_value32(ep, val); + pico_trace("buffer control (0x%p) <- 0x%x\n", ep->buffer_control, val); +} + + +void _hw_endpoint_xfer_start(struct hw_endpoint *ep, uint8_t *buffer, uint16_t total_len) +{ + _hw_endpoint_lock_update(ep, 1); + pico_trace("Start transfer of total len %d on ep %d %s\n", total_len, ep->num, ep_dir_string[ep->in]); + if (ep->active) + { + // TODO: Is this acceptable for interrupt packets? + pico_warn("WARN: starting new transfer on already active ep %d %s\n", ep->num, ep_dir_string[ep->in]); + + hw_endpoint_reset_transfer(ep); + } + + // Fill in info now that we're kicking off the hw + ep->total_len = total_len; + ep->len = 0; + // FIXME: What if low speed + ep->transfer_size = total_len > 64 ? 64 : total_len; + ep->active = true; + ep->user_buf = buffer; + // Recalculate if this is the last buffer + _hw_endpoint_update_last_buf(ep); + ep->buf_sel = 0; + + _hw_endpoint_start_next_buffer(ep); + _hw_endpoint_lock_update(ep, -1); +} + +void _hw_endpoint_xfer_sync(struct hw_endpoint *ep) +{ + // Update hw endpoint struct with info from hardware + // after a buff status interrupt + + // Get the buffer state and amount of bytes we have + // transferred + uint32_t buf_ctrl = _hw_endpoint_buffer_control_get_value32(ep); + uint transferred_bytes = buf_ctrl & USB_BUF_CTRL_LEN_MASK; + +#ifdef RP2040_USB_HOST_MODE + // tag::host_buf_sel_fix[] + if (ep->buf_sel == 1) + { + // Host can erroneously write status to top half of buf_ctrl register + buf_ctrl = buf_ctrl >> 16; + } + // Flip buf sel for host + ep->buf_sel ^= 1u; + // end::host_buf_sel_fix[] +#endif + + // We are continuing a transfer here. If we are TX, we have successfullly + // sent some data can increase the length we have sent + if (!ep->rx) + { + assert(!(buf_ctrl & USB_BUF_CTRL_FULL)); + pico_trace("tx %d bytes (buf_ctrl 0x%08x)\n", transferred_bytes, buf_ctrl); + ep->len += transferred_bytes; + } + else + { + // If we are OUT we have recieved some data, so can increase the length + // we have recieved AFTER we have copied it to the user buffer at the appropriate + // offset + pico_trace("rx %d bytes (buf_ctrl 0x%08x)\n", transferred_bytes, buf_ctrl); + assert(buf_ctrl & USB_BUF_CTRL_FULL); + memcpy(&ep->user_buf[ep->len], ep->hw_data_buf, transferred_bytes); + ep->len += transferred_bytes; + } + + // Sometimes the host will send less data than we expect... + // If this is a short out transfer update the total length of the transfer + // to be the current length + if ((ep->rx) && (transferred_bytes < ep->transfer_size)) + { + pico_trace("Short rx transfer\n"); + // Reduce total length as this is last packet + ep->total_len = ep->len; + } +} + +// Returns true if transfer is complete +bool _hw_endpoint_xfer_continue(struct hw_endpoint *ep) +{ + _hw_endpoint_lock_update(ep, 1); + // Part way through a transfer + if (!ep->active) + { + panic("Can't continue xfer on inactive ep %d %s", ep->num, ep_dir_string); + } + + // Update EP struct from hardware state + _hw_endpoint_xfer_sync(ep); + + // Now we have synced our state with the hardware. Is there more data to transfer? + uint remaining_bytes = ep->total_len - ep->len; + ep->transfer_size = remaining_bytes > 64 ? 64 : remaining_bytes; + _hw_endpoint_update_last_buf(ep); + + // Can happen because of programmer error so check for it + if (ep->len > ep->total_len) + { + panic("Transferred more data than expected"); + } + + // If we are done then notify tinyusb + if (ep->len == ep->total_len) + { + pico_trace("Completed transfer of %d bytes on ep %d %s\n", + ep->len, ep->num, ep_dir_string[ep->in]); + // Notify caller we are done so it can notify the tinyusb + // stack + _hw_endpoint_lock_update(ep, -1); + return true; + } + else + { + _hw_endpoint_start_next_buffer(ep); + } + + _hw_endpoint_lock_update(ep, -1); + // More work to do + return false; +} + +void _hw_endpoint_xfer(struct hw_endpoint *ep, uint8_t *buffer, uint16_t total_len, bool start) +{ + // Trace + pico_trace("hw_endpoint_xfer ep %d %s", ep->num, ep_dir_string[ep->in]); + pico_trace(" total_len %d, start=%d\n", total_len, start); + + assert(ep->configured); + + + if (start) + { + _hw_endpoint_xfer_start(ep, buffer, total_len); + } + else + { + _hw_endpoint_xfer_continue(ep); + } +} + +#endif diff --git a/src/portable/raspberrypi/rp2040/rp2040_usb.h b/src/portable/raspberrypi/rp2040/rp2040_usb.h new file mode 100644 index 000000000..7c3234e8d --- /dev/null +++ b/src/portable/raspberrypi/rp2040/rp2040_usb.h @@ -0,0 +1,124 @@ +#ifndef RP2040_COMMON_H_ +#define RP2040_COMMON_H_ + +#if defined(RP2040_USB_HOST_MODE) && defined(RP2040_USB_DEVICE_MODE) +#error TinyUSB device and host mode not supported at the same time +#endif + +#include "common/tusb_common.h" + +#include "pico.h" +#include "hardware/structs/usb.h" +#include "hardware/irq.h" +#include "hardware/resets.h" + +#if defined(PICO_RP2040_USB_DEVICE_ENUMERATION_FIX) && !defined(TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX) +#define TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX PICO_RP2040_USB_DEVICE_ENUMERATION_FIX +#endif + +// For memset +#include <string.h> + +#if false && !defined(NDEBUG) +#define pico_trace(format,args...) printf(format, ## args) +#else +#define pico_trace(format,...) ((void)0) +#endif + +#if false && !defined(NDEBUG) +#define pico_info(format,args...) printf(format, ## args) +#else +#define pico_info(format,...) ((void)0) +#endif + +#if false && !defined(NDEBUG) +#define pico_warn(format,args...) printf(format, ## args) +#else +#define pico_warn(format,...) ((void)0) +#endif + +// Hardware information per endpoint +struct hw_endpoint +{ + // Is this a valid struct + bool configured; + // EP direction + bool in; + // EP num (not including direction) + uint8_t num; + + // Transfer direction (i.e. IN is rx for host but tx for device) + // allows us to common up transfer functions + bool rx; + + uint8_t ep_addr; + uint8_t next_pid; + + // Endpoint control register + io_rw_32 *endpoint_control; + // Buffer control register + io_rw_32 *buffer_control; + + // Buffer pointer in usb dpram + uint8_t *hw_data_buf; + + // Have we been stalled + bool stalled; + + // Current transfer information + bool active; + uint total_len; + uint len; + // Amount of data with the hardware + uint transfer_size; + // Only needed for host mode + bool last_buf; + // HOST BUG. Host will incorrect write status to top half of buffer + // control register when doing transfers > 1 packet + uint8_t buf_sel; + // User buffer in main memory + uint8_t *user_buf; + + // Data needed from EP descriptor + uint wMaxPacketSize; + // Interrupt, bulk, etc + uint8_t transfer_type; + + // Only needed for host + uint8_t dev_addr; + bool sent_setup; + // If interrupt endpoint + uint8_t interrupt_num; +}; + +void rp2040_usb_init(void); + +void hw_endpoint_reset_transfer(struct hw_endpoint *ep); +void _hw_endpoint_xfer(struct hw_endpoint *ep, uint8_t *buffer, uint16_t total_len, bool start); +void _hw_endpoint_start_next_buffer(struct hw_endpoint *ep); +void _hw_endpoint_xfer_start(struct hw_endpoint *ep, uint8_t *buffer, uint16_t total_len); +void _hw_endpoint_xfer_sync(struct hw_endpoint *ep); +bool _hw_endpoint_xfer_continue(struct hw_endpoint *ep); +void _hw_endpoint_buffer_control_update32(struct hw_endpoint *ep, uint32_t and_mask, uint32_t or_mask); +static inline uint32_t _hw_endpoint_buffer_control_get_value32(struct hw_endpoint *ep) { + return *ep->buffer_control; +} +static inline void _hw_endpoint_buffer_control_set_value32(struct hw_endpoint *ep, uint32_t value) { + return _hw_endpoint_buffer_control_update32(ep, 0, value); +} +static inline void _hw_endpoint_buffer_control_set_mask32(struct hw_endpoint *ep, uint32_t value) { + return _hw_endpoint_buffer_control_update32(ep, ~value, value); +} +static inline void _hw_endpoint_buffer_control_clear_mask32(struct hw_endpoint *ep, uint32_t value) { + return _hw_endpoint_buffer_control_update32(ep, ~value, 0); +} + +static inline uintptr_t hw_data_offset(uint8_t *buf) +{ + // Remove usb base from buffer pointer + return (uintptr_t)buf ^ (uintptr_t)usb_dpram; +} + +extern const char *ep_dir_string[]; + +#endif diff --git a/src/portable/sony/cxd56/dcd_cxd56.c b/src/portable/sony/cxd56/dcd_cxd56.c index 9269903a5..88027ccaa 100644 --- a/src/portable/sony/cxd56/dcd_cxd56.c +++ b/src/portable/sony/cxd56/dcd_cxd56.c @@ -1,4 +1,4 @@ -/* +/* * The MIT License (MIT) * * Copyright 2019 Sony Semiconductor Solutions Corporation @@ -33,14 +33,23 @@ #include <nuttx/arch.h> #include "device/dcd.h" +#include "osal/osal.h" #define CXD56_EPNUM (7) +#define CXD56_SETUP_QUEUE_DEPTH (4) +#define CXD56_MAX_DATA_OUT_SIZE (64) + +OSAL_QUEUE_DEF(OPT_MODE_DEVICE, _setup_queue_def, CXD56_SETUP_QUEUE_DEPTH, struct usb_ctrlreq_s); struct usbdcd_driver_s { struct usbdevclass_driver_s usbdevclass_driver; FAR struct usbdev_ep_s *ep[CXD56_EPNUM]; FAR struct usbdev_req_s *req[CXD56_EPNUM]; + osal_queue_t setup_queue; + bool setup_processed; + FAR uint8_t dataout[CXD56_MAX_DATA_OUT_SIZE]; + size_t outlen; }; static struct usbdcd_driver_s usbdcd_driver; @@ -118,14 +127,26 @@ static void _dcd_unbind(FAR struct usbdevclass_driver_s *driver, FAR struct usbd } static int _dcd_setup(FAR struct usbdevclass_driver_s *driver, FAR struct usbdev_s *dev, - FAR const struct usb_ctrlreq_s *ctrl, FAR uint8_t *dataout, size_t outlen) + FAR const struct usb_ctrlreq_s *ctrl, FAR uint8_t *dataout, size_t outlen) { (void) driver; (void) dev; - (void) dataout; - (void) outlen; - dcd_event_setup_received(0, (uint8_t *)ctrl, true); + if (usbdcd_driver.setup_processed) + { + usbdcd_driver.setup_processed = false; + dcd_event_setup_received(0, (uint8_t *) ctrl, true); + } + else + { + osal_queue_send(usbdcd_driver.setup_queue, ctrl, true); + } + + if (outlen > 0 && outlen <= CXD56_MAX_DATA_OUT_SIZE) + { + memcpy(usbdcd_driver.dataout, dataout, outlen); + usbdcd_driver.outlen = outlen; + } return 0; } @@ -161,6 +182,8 @@ void dcd_init(uint8_t rhport) usbdcd_driver.usbdevclass_driver.speed = USB_SPEED_HIGH; usbdcd_driver.usbdevclass_driver.ops = &g_driverops; + usbdcd_driver.setup_processed = true; + usbdcd_driver.setup_queue = osal_queue_create(&_setup_queue_def); usbdev_register(&usbdcd_driver.usbdevclass_driver); } @@ -191,7 +214,7 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) void dcd_remote_wakeup(uint8_t rhport) { (void) rhport; - + DEV_WAKEUP(usbdev); } @@ -277,6 +300,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t to { (void) rhport; + bool ret = true; uint8_t epnum = tu_edpt_number(ep_addr); if (epnum >= CXD56_EPNUM) @@ -284,25 +308,53 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t to return false; } - usbdcd_driver.req[epnum]->len = total_bytes; - usbdcd_driver.req[epnum]->priv = (void *)((uint32_t)ep_addr); - usbdcd_driver.req[epnum]->flags = 0; - - if (total_bytes) + if (epnum == 0) { - usbdcd_driver.req[epnum]->buf = buffer; + if (total_bytes == 0) + { + dcd_event_xfer_complete(0, ep_addr, 0, XFER_RESULT_SUCCESS, false); + } + else if (ep_addr == 0x00 && total_bytes == usbdcd_driver.outlen) + { + memcpy(buffer, usbdcd_driver.dataout, usbdcd_driver.outlen); + dcd_event_xfer_complete(0, ep_addr, total_bytes, XFER_RESULT_SUCCESS, false); + usbdcd_driver.outlen = 0; + } + else + { + usbdcd_driver.req[epnum]->len = total_bytes; + usbdcd_driver.req[epnum]->priv = (void *)((uint32_t)ep_addr); + usbdcd_driver.req[epnum]->flags = total_bytes < usbdcd_driver.ep[epnum]->maxpacket ? USBDEV_REQFLAGS_NULLPKT : 0; + usbdcd_driver.req[epnum]->buf = buffer; + + if (EP_SUBMIT(usbdcd_driver.ep[epnum], usbdcd_driver.req[epnum]) < 0) + { + ret = false; + } + } + + usbdcd_driver.setup_processed = true; + struct usb_ctrlreq_s ctrl; + + if (osal_queue_receive(usbdcd_driver.setup_queue, &ctrl)) + { + dcd_event_setup_received(0, (uint8_t *)&ctrl, false); + } } else { - return true; - } + usbdcd_driver.req[epnum]->len = total_bytes; + usbdcd_driver.req[epnum]->priv = (void *)((uint32_t)ep_addr); + usbdcd_driver.req[epnum]->flags = total_bytes < usbdcd_driver.ep[epnum]->maxpacket ? USBDEV_REQFLAGS_NULLPKT : 0; + usbdcd_driver.req[epnum]->buf = buffer; - if (EP_SUBMIT(usbdcd_driver.ep[epnum], usbdcd_driver.req[epnum]) < 0) - { - return false; + if (EP_SUBMIT(usbdcd_driver.ep[epnum], usbdcd_driver.req[epnum]) < 0) + { + ret = false; + } } - return true; + return ret; } void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) @@ -322,7 +374,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) { (void) rhport; - + uint8_t epnum = tu_edpt_number(ep_addr); if (epnum >= CXD56_EPNUM) diff --git a/src/tusb.h b/src/tusb.h index 8b0dd103c..cc82c440d 100644 --- a/src/tusb.h +++ b/src/tusb.h @@ -92,7 +92,7 @@ #include "class/usbtmc/usbtmc_device.h" #endif - #if CFG_TUD_DFU_RT + #if CFG_TUD_DFU_RUNTIME #include "class/dfu/dfu_rt_device.h" #endif diff --git a/src/tusb_option.h b/src/tusb_option.h index 65a06bfa7..6cbdefbf1 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -28,7 +28,7 @@ #define _TUSB_OPTION_H_ #define TUSB_VERSION_MAJOR 0 -#define TUSB_VERSION_MINOR 7 +#define TUSB_VERSION_MINOR 8 #define TUSB_VERSION_REVISION 0 #define TUSB_VERSION_STRING TU_STRING(TUSB_VERSION_MAJOR) "." TU_STRING(TUSB_VERSION_MINOR) "." TU_STRING(TUSB_VERSION_REVISION) @@ -97,9 +97,11 @@ // Dialog #define OPT_MCU_DA1469X 1000 ///< Dialog Semiconductor DA1469x -// NXP Kinetis -#define OPT_MCU_MKL25ZXX 1100 ///< NXP MKL25Zxx +// Raspberry Pi +#define OPT_MCU_RP2040 1100 ///< Raspberry Pi RP2040 +// NXP Kinetis +#define OPT_MCU_MKL25ZXX 1200 ///< NXP MKL25Zxx /** @} */ @@ -110,6 +112,8 @@ #define OPT_OS_FREERTOS 2 ///< FreeRTOS #define OPT_OS_MYNEWT 3 ///< Mynewt OS #define OPT_OS_CUSTOM 4 ///< Custom OS is implemented by application +#define OPT_OS_PICO 5 ///< Raspberry Pi Pico SDK +#define OPT_OS_RTTHREAD 6 ///< RT-Thread /** @} */ @@ -229,8 +233,8 @@ #define CFG_TUD_USBTMC 0 #endif -#ifndef CFG_TUD_DFU_RT - #define CFG_TUD_DFU_RT 0 +#ifndef CFG_TUD_DFU_RUNTIME + #define CFG_TUD_DFU_RUNTIME 0 #endif #ifndef CFG_TUD_NET |
