Merge branch 'master' into port-ft90x

This commit is contained in:
Gordon McNab
2021-12-08 08:36:43 +00:00
318 changed files with 31702 additions and 3551 deletions
-12
View File
@@ -494,18 +494,6 @@ typedef enum
/// All remaining definitions are taken from the descriptor descriptions in the UAC2 main specification
/// Isochronous End Point Attributes
typedef enum
{
TUSB_ISO_EP_ATT_NO_SYNC = 0x00,
TUSB_ISO_EP_ATT_ASYNCHRONOUS = 0x04,
TUSB_ISO_EP_ATT_ADAPTIVE = 0x08,
TUSB_ISO_EP_ATT_SYNCHRONOUS = 0x0C,
TUSB_ISO_EP_ATT_DATA = 0x00, ///< Data End Point
TUSB_ISO_EP_ATT_EXPLICIT_FB = 0x10, ///< Feedback End Point
TUSB_ISO_EP_ATT_IMPLICIT_FB = 0x20, ///< Data endpoint that also serves as an implicit feedback
} tusb_iso_ep_attribute_t;
/// Audio Class-Control Values UAC2
typedef enum
{
+27 -9
View File
@@ -64,10 +64,19 @@
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
// Use ring buffer if it's available, some MCUs need extra RAM requirements
#ifndef TUD_AUDIO_PREFER_RING_BUFFER
#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX
#define TUD_AUDIO_PREFER_RING_BUFFER 0
#else
#define TUD_AUDIO_PREFER_RING_BUFFER 1
#endif
#endif
// Linear buffer in case target MCU is not capable of handling a ring buffer FIFO e.g. no hardware buffer
// is available or driver is would need to be changed dramatically
// Only STM32 synopsys use non-linear buffer for now
// Only STM32 synopsys and dcd_transdimension use non-linear buffer for now
// Synopsys detection copied from dcd_synopsys.c (refactor later on)
#if defined (STM32F105x8) || defined (STM32F105xB) || defined (STM32F105xC) || \
defined (STM32F107xB) || defined (STM32F107xC)
@@ -90,11 +99,19 @@
CFG_TUSB_MCU == OPT_MCU_RX63X || \
CFG_TUSB_MCU == OPT_MCU_RX65X || \
CFG_TUSB_MCU == OPT_MCU_RX72N || \
CFG_TUSB_MCU == OPT_MCU_GD32VF103
CFG_TUSB_MCU == OPT_MCU_GD32VF103 || \
CFG_TUSB_MCU == OPT_MCU_LPC18XX || \
CFG_TUSB_MCU == OPT_MCU_LPC43XX || \
CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || \
CFG_TUSB_MCU == OPT_MCU_MSP432E4
#if TUD_AUDIO_PREFER_RING_BUFFER
#define USE_LINEAR_BUFFER 0
#else
#define USE_LINEAR_BUFFER 1
#endif
#else
#define USE_LINEAR_BUFFER 1
#endif
// Declaration of buffers
@@ -1553,20 +1570,21 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const *
{
if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT)
{
TU_ASSERT(usbd_edpt_open(rhport, (tusb_desc_endpoint_t const *)p_desc));
tusb_desc_endpoint_t const* desc_ep = (tusb_desc_endpoint_t const *) p_desc;
TU_ASSERT(usbd_edpt_open(rhport, desc_ep));
uint8_t ep_addr = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress;
uint8_t const ep_addr = desc_ep->bEndpointAddress;
//TODO: We need to set EP non busy since this is not taken care of right now in ep_close() - THIS IS A WORKAROUND!
usbd_edpt_clear_stall(rhport, ep_addr);
#if CFG_TUD_AUDIO_ENABLE_EP_IN
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && ((tusb_desc_endpoint_t const *) p_desc)->bmAttributes.usage == 0x00) // Check if usage is data EP
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && desc_ep->bmAttributes.usage == 0x00) // Check if usage is data EP
{
// Save address
audio->ep_in = ep_addr;
audio->ep_in_as_intf_num = itf;
audio->ep_in_sz = ((tusb_desc_endpoint_t const *) p_desc)->wMaxPacketSize.size;
audio->ep_in_sz = tu_edpt_packet_size(desc_ep);
// If software encoding is enabled, parse for the corresponding parameters - doing this here means only AS interfaces with EPs get scanned for parameters
#if CFG_TUD_AUDIO_ENABLE_ENCODING
@@ -1600,7 +1618,7 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const *
// Save address
audio->ep_out = ep_addr;
audio->ep_out_as_intf_num = itf;
audio->ep_out_sz = ((tusb_desc_endpoint_t const *) p_desc)->wMaxPacketSize.size;
audio->ep_out_sz = tu_edpt_packet_size(desc_ep);
#if CFG_TUD_AUDIO_ENABLE_DECODING
audiod_parse_for_AS_params(audio, p_desc_parse_for_params, p_desc_end, itf);
@@ -1619,7 +1637,7 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const *
#if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP
// In case of asynchronous EP, call Cb after ep_fb is set
if (!(((tusb_desc_endpoint_t const *) p_desc)->bmAttributes.sync == 0x01 && audio->ep_fb == 0))
if ( !(desc_ep->bmAttributes.sync == 0x01 && audio->ep_fb == 0) )
{
if (tud_audio_set_itf_cb) TU_VERIFY(tud_audio_set_itf_cb(rhport, p_request));
}
@@ -1636,7 +1654,7 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const *
}
#if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && ((tusb_desc_endpoint_t const *) p_desc)->bmAttributes.usage == 1) // Check if usage is explicit data feedback
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && desc_ep->bmAttributes.usage == 1) // Check if usage is explicit data feedback
{
audio->ep_fb = ep_addr;
+62 -58
View File
@@ -112,74 +112,78 @@ uint16_t btd_open(uint8_t rhport, tusb_desc_interface_t const *itf_desc, uint16_
TUD_BT_APP_SUBCLASS == itf_desc->bInterfaceSubClass &&
TUD_BT_PROTOCOL_PRIMARY_CONTROLLER == itf_desc->bInterfaceProtocol, 0);
// Distinguish interface by number of endpoints, as both interface have same class, subclass and protocol
if (itf_desc->bNumEndpoints == 3 && max_len >= hci_itf_size)
{
_btd_itf.itf_num = itf_desc->bInterfaceNumber;
TU_ASSERT(itf_desc->bNumEndpoints == 3 && max_len >= hci_itf_size);
desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc);
_btd_itf.itf_num = itf_desc->bInterfaceNumber;
TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType && TUSB_XFER_INTERRUPT == desc_ep->bmAttributes.xfer, 0);
TU_ASSERT(usbd_edpt_open(rhport, desc_ep), 0);
_btd_itf.ep_ev = desc_ep->bEndpointAddress;
desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc);
// Open endpoint pair
TU_ASSERT(usbd_open_edpt_pair(rhport, tu_desc_next(desc_ep), 2, TUSB_XFER_BULK, &_btd_itf.ep_acl_out,
&_btd_itf.ep_acl_in), 0);
TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType && TUSB_XFER_INTERRUPT == desc_ep->bmAttributes.xfer, 0);
TU_ASSERT(usbd_edpt_open(rhport, desc_ep), 0);
_btd_itf.ep_ev = desc_ep->bEndpointAddress;
// Prepare for incoming data from host
TU_ASSERT(usbd_edpt_xfer(rhport, _btd_itf.ep_acl_out, _btd_itf.epout_buf, CFG_TUD_BTH_DATA_EPSIZE), 0);
// Open endpoint pair
TU_ASSERT(usbd_open_edpt_pair(rhport, tu_desc_next(desc_ep), 2, TUSB_XFER_BULK, &_btd_itf.ep_acl_out,
&_btd_itf.ep_acl_in), 0);
drv_len = hci_itf_size;
}
else if (itf_desc->bNumEndpoints == 2 && max_len >= iso_alt_itf_size)
{
uint8_t dir;
itf_desc = (tusb_desc_interface_t const *)tu_desc_next(tu_desc_next(tu_desc_next(desc_ep)));
// Prepare for incoming data from host
TU_ASSERT(usbd_edpt_xfer(rhport, _btd_itf.ep_acl_out, _btd_itf.epout_buf, CFG_TUD_BTH_DATA_EPSIZE), 0);
drv_len = hci_itf_size;
// Ensure this is still BT Primary Controller
TU_ASSERT(TUSB_CLASS_WIRELESS_CONTROLLER == itf_desc->bInterfaceClass &&
TUD_BT_APP_SUBCLASS == itf_desc->bInterfaceSubClass &&
TUD_BT_PROTOCOL_PRIMARY_CONTROLLER == itf_desc->bInterfaceProtocol, 0);
TU_ASSERT(itf_desc->bNumEndpoints == 2 && max_len >= iso_alt_itf_size + drv_len);
uint8_t dir;
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(itf_desc);
TU_ASSERT(itf_desc->bAlternateSetting < CFG_TUD_BTH_ISO_ALT_COUNT, 0);
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT, 0);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
_btd_itf.ep_voice[dir] = desc_ep->bEndpointAddress;
// Store endpoint size for alternative
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t) tu_edpt_packet_size(desc_ep);
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(desc_ep);
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT, 0);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
_btd_itf.ep_voice[dir] = desc_ep->bEndpointAddress;
// Store endpoint size for alternative
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t) tu_edpt_packet_size(desc_ep);
drv_len += iso_alt_itf_size;
for (int i = 1; i < CFG_TUD_BTH_ISO_ALT_COUNT && drv_len + iso_alt_itf_size <= max_len; ++i) {
// Make sure rest of alternatives matches
itf_desc = (tusb_desc_interface_t const *)tu_desc_next(desc_ep);
if (itf_desc->bDescriptorType != TUSB_DESC_INTERFACE ||
TUSB_CLASS_WIRELESS_CONTROLLER != itf_desc->bInterfaceClass ||
TUD_BT_APP_SUBCLASS != itf_desc->bInterfaceSubClass ||
TUD_BT_PROTOCOL_PRIMARY_CONTROLLER != itf_desc->bInterfaceProtocol)
{
// Not an Iso interface instance
break;
}
TU_ASSERT(itf_desc->bAlternateSetting < CFG_TUD_BTH_ISO_ALT_COUNT, 0);
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(itf_desc);
TU_ASSERT(itf_desc->bAlternateSetting < CFG_TUD_BTH_ISO_ALT_COUNT, 0);
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT, 0);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
_btd_itf.ep_voice[dir] = desc_ep->bEndpointAddress;
// Store endpoint size for alternative
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t)desc_ep->wMaxPacketSize.size;
// Verify that alternative endpoint are same as first ones
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT &&
_btd_itf.ep_voice[dir] == desc_ep->bEndpointAddress, 0);
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t) tu_edpt_packet_size(desc_ep);
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(desc_ep);
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT, 0);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
_btd_itf.ep_voice[dir] = desc_ep->bEndpointAddress;
// Store endpoint size for alternative
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t)desc_ep->wMaxPacketSize.size;
// Verify that alternative endpoint are same as first ones
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT &&
_btd_itf.ep_voice[dir] == desc_ep->bEndpointAddress, 0);
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t) tu_edpt_packet_size(desc_ep);
drv_len += iso_alt_itf_size;
for (int i = 1; i < CFG_TUD_BTH_ISO_ALT_COUNT && drv_len + iso_alt_itf_size <= max_len; ++i) {
// Make sure rest of alternatives matches
itf_desc = (tusb_desc_interface_t const *)tu_desc_next(desc_ep);
if (itf_desc->bDescriptorType != TUSB_DESC_INTERFACE ||
TUSB_CLASS_WIRELESS_CONTROLLER != itf_desc->bInterfaceClass ||
TUD_BT_APP_SUBCLASS != itf_desc->bInterfaceSubClass ||
TUD_BT_PROTOCOL_PRIMARY_CONTROLLER != itf_desc->bInterfaceProtocol)
{
// Not an Iso interface instance
break;
}
TU_ASSERT(itf_desc->bAlternateSetting < CFG_TUD_BTH_ISO_ALT_COUNT, 0);
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(itf_desc);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
// Verify that alternative endpoint are same as first ones
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT &&
_btd_itf.ep_voice[dir] == desc_ep->bEndpointAddress, 0);
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t)desc_ep->wMaxPacketSize.size;
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(desc_ep);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
// Verify that alternative endpoint are same as first ones
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT &&
_btd_itf.ep_voice[dir] == desc_ep->bEndpointAddress, 0);
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t)desc_ep->wMaxPacketSize.size;
drv_len += iso_alt_itf_size;
}
}
return drv_len;
@@ -214,14 +218,14 @@ bool btd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t c
}
else return false;
return tud_control_xfer(rhport, request, &_btd_itf.hci_cmd, request->wLength);
return tud_control_xfer(rhport, request, &_btd_itf.hci_cmd, sizeof(_btd_itf.hci_cmd));
}
else if ( stage == CONTROL_STAGE_DATA )
{
// Handle class request only
TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
if (tud_bt_hci_cmd_cb) tud_bt_hci_cmd_cb(&_btd_itf.hci_cmd, request->wLength);
if (tud_bt_hci_cmd_cb) tud_bt_hci_cmd_cb(&_btd_itf.hci_cmd, tu_min16(request->wLength, sizeof(_btd_itf.hci_cmd)));
}
return true;
+35 -36
View File
@@ -58,31 +58,32 @@ typedef enum
/// Communication Interface Subclass Codes
typedef enum
{
CDC_COMM_SUBCLASS_DIRECT_LINE_CONTROL_MODEL = 0x01 , ///< Direct Line Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL , ///< Abstract Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL , ///< Telephone Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_MULTICHANNEL_CONTROL_MODEL , ///< Multi-Channel Control Model [USBISDN1.2]
CDC_COMM_SUBCLASS_CAPI_CONTROL_MODEL , ///< CAPI Control Model [USBISDN1.2]
CDC_COMM_SUBCLASS_ETHERNET_CONTROL_MODEL , ///< Ethernet Networking Control Model [USBECM1.2]
CDC_COMM_SUBCLASS_ATM_NETWORKING_CONTROL_MODEL , ///< ATM Networking Control Model [USBATM1.2]
CDC_COMM_SUBCLASS_WIRELESS_HANDSET_CONTROL_MODEL , ///< Wireless Handset Control Model [USBWMC1.1]
CDC_COMM_SUBCLASS_DEVICE_MANAGEMENT , ///< Device Management [USBWMC1.1]
CDC_COMM_SUBCLASS_MOBILE_DIRECT_LINE_MODEL , ///< Mobile Direct Line Model [USBWMC1.1]
CDC_COMM_SUBCLASS_OBEX , ///< OBEX [USBWMC1.1]
CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model [USBEEM1.0]
CDC_COMM_SUBCLASS_DIRECT_LINE_CONTROL_MODEL = 0x01 , ///< Direct Line Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL = 0x02 , ///< Abstract Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL = 0x03 , ///< Telephone Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_MULTICHANNEL_CONTROL_MODEL = 0x04 , ///< Multi-Channel Control Model [USBISDN1.2]
CDC_COMM_SUBCLASS_CAPI_CONTROL_MODEL = 0x05 , ///< CAPI Control Model [USBISDN1.2]
CDC_COMM_SUBCLASS_ETHERNET_CONTROL_MODEL = 0x06 , ///< Ethernet Networking Control Model [USBECM1.2]
CDC_COMM_SUBCLASS_ATM_NETWORKING_CONTROL_MODEL = 0x07 , ///< ATM Networking Control Model [USBATM1.2]
CDC_COMM_SUBCLASS_WIRELESS_HANDSET_CONTROL_MODEL = 0x08 , ///< Wireless Handset Control Model [USBWMC1.1]
CDC_COMM_SUBCLASS_DEVICE_MANAGEMENT = 0x09 , ///< Device Management [USBWMC1.1]
CDC_COMM_SUBCLASS_MOBILE_DIRECT_LINE_MODEL = 0x0A , ///< Mobile Direct Line Model [USBWMC1.1]
CDC_COMM_SUBCLASS_OBEX = 0x0B , ///< OBEX [USBWMC1.1]
CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL = 0x0C , ///< Ethernet Emulation Model [USBEEM1.0]
CDC_COMM_SUBCLASS_NETWORK_CONTROL_MODEL = 0x0D ///< Network Control Model [USBNCM1.0]
} cdc_comm_sublcass_type_t;
/// Communication Interface Protocol Codes
typedef enum
{
CDC_COMM_PROTOCOL_NONE = 0x00 , ///< No specific protocol
CDC_COMM_PROTOCOL_ATCOMMAND , ///< AT Commands: V.250 etc
CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101 , ///< AT Commands defined by PCCA-101
CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101_AND_ANNEXO , ///< AT Commands defined by PCCA-101 & Annex O
CDC_COMM_PROTOCOL_ATCOMMAND_GSM_707 , ///< AT Commands defined by GSM 07.07
CDC_COMM_PROTOCOL_ATCOMMAND_3GPP_27007 , ///< AT Commands defined by 3GPP 27.007
CDC_COMM_PROTOCOL_ATCOMMAND_CDMA , ///< AT Commands defined by TIA for CDMA
CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model
CDC_COMM_PROTOCOL_NONE = 0x00 , ///< No specific protocol
CDC_COMM_PROTOCOL_ATCOMMAND = 0x01 , ///< AT Commands: V.250 etc
CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101 = 0x02 , ///< AT Commands defined by PCCA-101
CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101_AND_ANNEXO = 0x03 , ///< AT Commands defined by PCCA-101 & Annex O
CDC_COMM_PROTOCOL_ATCOMMAND_GSM_707 = 0x04 , ///< AT Commands defined by GSM 07.07
CDC_COMM_PROTOCOL_ATCOMMAND_3GPP_27007 = 0x05 , ///< AT Commands defined by 3GPP 27.007
CDC_COMM_PROTOCOL_ATCOMMAND_CDMA = 0x06 , ///< AT Commands defined by TIA for CDMA
CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL = 0x07 ///< Ethernet Emulation Model
} cdc_comm_protocol_type_t;
//------------- SubType Descriptor in COMM Functional Descriptor -------------//
@@ -114,7 +115,8 @@ typedef enum
CDC_FUNC_DESC_COMMAND_SET = 0x16 , ///< Command Set Functional Descriptor
CDC_FUNC_DESC_COMMAND_SET_DETAIL = 0x17 , ///< Command Set Detail Functional Descriptor
CDC_FUNC_DESC_TELEPHONE_CONTROL_MODEL = 0x18 , ///< Telephone Control Model Functional Descriptor
CDC_FUNC_DESC_OBEX_SERVICE_IDENTIFIER = 0x19 ///< OBEX Service Identifier Functional Descriptor
CDC_FUNC_DESC_OBEX_SERVICE_IDENTIFIER = 0x19 , ///< OBEX Service Identifier Functional Descriptor
CDC_FUNC_DESC_NCM = 0x1A , ///< NCM Functional Descriptor
}cdc_func_desc_type_t;
//--------------------------------------------------------------------+
@@ -122,7 +124,8 @@ typedef enum
//--------------------------------------------------------------------+
// SUBCLASS code of Data Interface is not used and should/must be zero
/// Data Interface Protocol Codes
// Data Interface Protocol Codes
typedef enum{
CDC_DATA_PROTOCOL_ISDN_BRI = 0x30, ///< Physical interface protocol for ISDN BRI
CDC_DATA_PROTOCOL_HDLC = 0x31, ///< HDLC
@@ -147,7 +150,6 @@ typedef enum
{
CDC_REQUEST_SEND_ENCAPSULATED_COMMAND = 0x00, ///< is used to issue a command in the format of the supported control protocol of the Communications Class interface
CDC_REQUEST_GET_ENCAPSULATED_RESPONSE = 0x01, ///< is used to request a response in the format of the supported control protocol of the Communications Class interface.
CDC_REQUEST_SET_COMM_FEATURE = 0x02,
CDC_REQUEST_GET_COMM_FEATURE = 0x03,
CDC_REQUEST_CLEAR_COMM_FEATURE = 0x04,
@@ -194,21 +196,18 @@ typedef enum
// Management Elemenent Notification (Notification Endpoint)
//--------------------------------------------------------------------+
/// Communication Interface Management Element Notification Codes
/// 6.3 Notification Codes
typedef enum
{
NETWORK_CONNECTION = 0x00, ///< This notification allows the device to notify the host about network connection status.
RESPONSE_AVAILABLE = 0x01, ///< This notification allows the device to notify the hostthat a response is available. This response can be retrieved with a subsequent \ref CDC_REQUEST_GET_ENCAPSULATED_RESPONSE request.
AUX_JACK_HOOK_STATE = 0x08,
RING_DETECT = 0x09,
SERIAL_STATE = 0x20,
CALL_STATE_CHANGE = 0x28,
LINE_STATE_CHANGE = 0x29,
CONNECTION_SPEED_CHANGE = 0x2A, ///< This notification allows the device to inform the host-networking driver that a change in either the upstream or the downstream bit rate of the connection has occurred
MDLM_SEMANTIC_MODEL_NOTIFICATION = 0x40,
CDC_NOTIF_NETWORK_CONNECTION = 0x00, ///< This notification allows the device to notify the host about network connection status.
CDC_NOTIF_RESPONSE_AVAILABLE = 0x01, ///< This notification allows the device to notify the hostthat a response is available. This response can be retrieved with a subsequent \ref CDC_REQUEST_GET_ENCAPSULATED_RESPONSE request.
CDC_NOTIF_AUX_JACK_HOOK_STATE = 0x08,
CDC_NOTIF_RING_DETECT = 0x09,
CDC_NOTIF_SERIAL_STATE = 0x20,
CDC_NOTIF_CALL_STATE_CHANGE = 0x28,
CDC_NOTIF_LINE_STATE_CHANGE = 0x29,
CDC_NOTIF_CONNECTION_SPEED_CHANGE = 0x2A, ///< This notification allows the device to inform the host-networking driver that a change in either the upstream or the downstream bit rate of the connection has occurred
CDC_NOTIF_MDLM_SEMANTIC_MODEL_NOTIFICATION = 0x40,
}cdc_notification_request_t;
//--------------------------------------------------------------------+
+7 -5
View File
@@ -80,7 +80,7 @@ typedef struct
//--------------------------------------------------------------------+
CFG_TUSB_MEM_SECTION static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC];
static void _prep_out_transaction (cdcd_interface_t* p_cdc)
static bool _prep_out_transaction (cdcd_interface_t* p_cdc)
{
uint8_t const rhport = TUD_OPT_RHPORT;
uint16_t available = tu_fifo_remaining(&p_cdc->rx_ff);
@@ -89,21 +89,23 @@ static void _prep_out_transaction (cdcd_interface_t* p_cdc)
// 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_cdc->epout_buf), );
TU_VERIFY(available >= sizeof(p_cdc->epout_buf));
// claim endpoint
TU_VERIFY(usbd_edpt_claim(rhport, p_cdc->ep_out), );
TU_VERIFY(usbd_edpt_claim(rhport, p_cdc->ep_out));
// fifo can be changed before endpoint is claimed
available = tu_fifo_remaining(&p_cdc->rx_ff);
if ( available >= sizeof(p_cdc->epout_buf) )
{
usbd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epout_buf, sizeof(p_cdc->epout_buf));
return usbd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epout_buf, sizeof(p_cdc->epout_buf));
}else
{
// Release endpoint since we don't make any transfer
usbd_edpt_release(rhport, p_cdc->ep_out);
return false;
}
}
@@ -229,7 +231,7 @@ void cdcd_init(void)
{
cdcd_interface_t* p_cdc = &_cdcd_itf[i];
p_cdc->wanted_char = -1;
p_cdc->wanted_char = (char) -1;
// default line coding is : stop bit = 1, parity = none, data bits = 8
p_cdc->line_coding.bit_rate = 115200;
+4 -4
View File
@@ -82,7 +82,7 @@ int32_t tud_cdc_n_read_char (uint8_t itf);
void tud_cdc_n_read_flush (uint8_t itf);
// Get a byte from FIFO at the specified position without removing it
bool tud_cdc_n_peek (uint8_t itf, uint8_t* u8);
bool tud_cdc_n_peek (uint8_t itf, uint8_t* ui8);
// Write bytes to TX FIFO, data may remain in the FIFO for a while
uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize);
@@ -116,7 +116,7 @@ static inline uint32_t tud_cdc_available (void);
static inline int32_t tud_cdc_read_char (void);
static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize);
static inline void tud_cdc_read_flush (void);
static inline bool tud_cdc_peek (uint8_t* u8);
static inline bool tud_cdc_peek (uint8_t* ui8);
static inline uint32_t tud_cdc_write_char (char ch);
static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize);
@@ -206,9 +206,9 @@ static inline void tud_cdc_read_flush (void)
tud_cdc_n_read_flush(0);
}
static inline bool tud_cdc_peek (uint8_t* u8)
static inline bool tud_cdc_peek (uint8_t* ui8)
{
return tud_cdc_n_peek(0, u8);
return tud_cdc_n_peek(0, ui8);
}
static inline uint32_t tud_cdc_write_char (char ch)
+1 -1
View File
@@ -105,7 +105,7 @@ bool tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool i
uint8_t const ep_out = cdch_data[dev_addr-1].ep_out;
if ( usbh_edpt_busy(dev_addr, ep_out) ) return false;
return usbh_edpt_xfer(dev_addr, ep_out, (void *) p_data, length);
return usbh_edpt_xfer(dev_addr, ep_out, (void*)(uintptr_t) p_data, length);
}
bool tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify)
+1 -1
View File
@@ -190,7 +190,7 @@ uint16_t dfu_moded_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc,
_dfu_ctx.attrs = func_desc->bAttributes;
// CFG_TUD_DFU_XFER_BUFSIZE has to be set to the buffer size used in TUD_DFU_DESCRIPTOR
uint16_t const transfer_size = tu_le16toh( tu_unaligned_read16((uint8_t*) func_desc + offsetof(tusb_desc_dfu_functional_t, wTransferSize)) );
uint16_t const transfer_size = tu_le16toh( tu_unaligned_read16((uint8_t const*) func_desc + offsetof(tusb_desc_dfu_functional_t, wTransferSize)) );
TU_ASSERT(transfer_size <= CFG_TUD_DFU_XFER_BUFSIZE, drv_len);
return drv_len;
+8 -8
View File
@@ -206,8 +206,8 @@ uint16_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint1
//------------- HID descriptor -------------//
p_desc = tu_desc_next(p_desc);
TU_ASSERT(HID_DESC_TYPE_HID == tu_desc_type(p_desc), 0);
p_hid->hid_descriptor = (tusb_hid_descriptor_hid_t const *) p_desc;
TU_ASSERT(HID_DESC_TYPE_HID == p_hid->hid_descriptor->bDescriptorType, 0);
//------------- Endpoint Descriptor -------------//
p_desc = tu_desc_next(p_desc);
@@ -216,10 +216,10 @@ uint16_t hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint1
if ( desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT ) p_hid->itf_protocol = desc_itf->bInterfaceProtocol;
p_hid->protocol_mode = HID_PROTOCOL_REPORT; // Per Specs: default is report mode
p_hid->itf_num = desc_itf->bInterfaceNumber;
p_hid->itf_num = desc_itf->bInterfaceNumber;
// Use offsetof to avoid pointer to the odd/misaligned address
memcpy(&p_hid->report_desc_len, (uint8_t*) p_hid->hid_descriptor + offsetof(tusb_hid_descriptor_hid_t, wReportLength), 2);
p_hid->report_desc_len = tu_unaligned_read16((uint8_t const*) p_hid->hid_descriptor + offsetof(tusb_hid_descriptor_hid_t, wReportLength));
// Prepare for output endpoint
if (p_hid->ep_out)
@@ -256,13 +256,13 @@ bool hidd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t
if (request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_HID)
{
TU_VERIFY(p_hid->hid_descriptor != NULL);
TU_VERIFY(tud_control_xfer(rhport, request, (void*) p_hid->hid_descriptor, p_hid->hid_descriptor->bLength));
TU_VERIFY(p_hid->hid_descriptor);
TU_VERIFY(tud_control_xfer(rhport, request, (void*)(uintptr_t) p_hid->hid_descriptor, p_hid->hid_descriptor->bLength));
}
else if (request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT)
{
uint8_t const * desc_report = tud_hid_descriptor_report_cb(hid_itf);
tud_control_xfer(rhport, request, (void*) desc_report, p_hid->report_desc_len);
tud_control_xfer(rhport, request, (void*)(uintptr_t) desc_report, p_hid->report_desc_len);
}
else
{
@@ -282,7 +282,7 @@ bool hidd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t
uint8_t const report_id = tu_u16_low(request->wValue);
uint8_t* report_buf = p_hid->epin_buf;
uint16_t req_len = request->wLength;
uint16_t req_len = tu_min16(request->wLength, CFG_TUD_HID_EP_BUFSIZE);
uint16_t xferlen = 0;
@@ -314,7 +314,7 @@ bool hidd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t
uint8_t const report_id = tu_u16_low(request->wValue);
uint8_t const* report_buf = p_hid->epout_buf;
uint16_t report_len = request->wLength;
uint16_t report_len = tu_min16(request->wLength, CFG_TUD_HID_EP_BUFSIZE);
// If host request a specific Report ID, extract report ID in buffer before invoking callback
if ( (report_id != HID_REPORT_TYPE_INVALID) && (report_len > 1) && (report_id == report_buf[0]) )
+44 -44
View File
@@ -195,16 +195,7 @@ static inline bool tud_hid_gamepad_report(uint8_t report_id, int8_t x, int8_t y
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_CONSTANT ) ,\
/* 6-byte Keycodes */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\
HID_USAGE_MIN ( 0 ) ,\
HID_USAGE_MAX_N ( 255, 2 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX_N( 255, 2 ) ,\
HID_REPORT_COUNT ( 6 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
/* 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \
/* Output 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\
HID_USAGE_MIN ( 1 ) ,\
HID_USAGE_MAX ( 5 ) ,\
@@ -215,6 +206,15 @@ static inline bool tud_hid_gamepad_report(uint8_t report_id, int8_t x, int8_t y
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 3 ) ,\
HID_OUTPUT ( HID_CONSTANT ) ,\
/* 6-byte Keycodes */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\
HID_USAGE_MIN ( 0 ) ,\
HID_USAGE_MAX_N ( 255, 2 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX_N( 255, 2 ) ,\
HID_REPORT_COUNT ( 6 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
HID_COLLECTION_END \
// Mouse Report Descriptor Template
@@ -310,8 +310,8 @@ static inline bool tud_hid_gamepad_report(uint8_t report_id, int8_t x, int8_t y
HID_COLLECTION_END \
// Gamepad Report Descriptor Template
// 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) |
// with 32 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 (4 bytes) |
#define TUD_HID_REPORT_DESC_GAMEPAD(...) \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\
@@ -319,37 +319,37 @@ static inline bool tud_hid_gamepad_report(uint8_t report_id, int8_t x, int8_t y
/* 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 ) ,\
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 ) ,\
HID_USAGE_MAX ( 32 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX ( 1 ) ,\
HID_REPORT_COUNT ( 32 ) ,\
HID_REPORT_SIZE ( 1 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
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 ) ,\
/* 32 bit Button Map */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\
HID_USAGE_MIN ( 1 ) ,\
HID_USAGE_MAX ( 32 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX ( 1 ) ,\
HID_REPORT_COUNT ( 32 ) ,\
HID_REPORT_SIZE ( 1 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
HID_COLLECTION_END \
// HID Generic Input & Output
@@ -364,14 +364,14 @@ static inline bool tud_hid_gamepad_report(uint8_t report_id, int8_t x, int8_t y
/* Input */ \
HID_USAGE ( 0x02 ),\
HID_LOGICAL_MIN ( 0x00 ),\
HID_LOGICAL_MAX ( 0xff ),\
HID_LOGICAL_MAX_N ( 0xff, 2 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT( report_size ),\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
/* Output */ \
HID_USAGE ( 0x03 ),\
HID_LOGICAL_MIN ( 0x00 ),\
HID_LOGICAL_MAX ( 0xff ),\
HID_LOGICAL_MAX_N ( 0xff, 2 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT( report_size ),\
HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
+9 -1
View File
@@ -291,7 +291,15 @@ bool hidh_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *de
tusb_desc_endpoint_t const * desc_ep = (tusb_desc_endpoint_t const *) p_desc;
TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType);
// first endpoint may be OUT, skip to IN endpoint
// TODO also open endpoint OUT
if(tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_OUT)
{
p_desc = tu_desc_next(p_desc);
desc_ep = (tusb_desc_endpoint_t const *) p_desc;
TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType);
}
TU_ASSERT( usbh_edpt_open(rhport, dev_addr, desc_ep) );
hidh_interface_t* hid_itf = get_instance(dev_addr, hid_dev->inst_count);
@@ -299,7 +307,7 @@ bool hidh_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *de
hid_itf->itf_num = desc_itf->bInterfaceNumber;
hid_itf->ep_in = desc_ep->bEndpointAddress;
hid_itf->epin_size = desc_ep->wMaxPacketSize.size;
hid_itf->epin_size = tu_edpt_packet_size(desc_ep);
// Assume bNumDescriptors = 1
hid_itf->report_desc_type = desc_hid->bReportType;
+7
View File
@@ -279,6 +279,12 @@ uint32_t tud_midi_n_stream_write(uint8_t itf, uint8_t cable_num, uint8_t const*
stream->buffer[0] = (cable_num << 4) | msg;
stream->total = 4;
}
else if ( msg == 0xC || msg == 0xD)
{
// Channel Voice Messages, two-byte variants (Program Change and Channel Pressure)
stream->buffer[0] = (cable_num << 4) | msg;
stream->total = 3;
}
else if ( msg == 0xf )
{
// System message
@@ -433,6 +439,7 @@ uint16_t midid_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint
break;
}
}
TU_ASSERT(p_midi);
p_midi->itf_num = desc_midi->bInterfaceNumber;
(void) p_midi->itf_num;
+402 -168
View File
@@ -1,4 +1,4 @@
/*
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
@@ -46,7 +46,8 @@ enum
MSC_STAGE_CMD = 0,
MSC_STAGE_DATA,
MSC_STAGE_STATUS,
MSC_STAGE_STATUS_SENT
MSC_STAGE_STATUS_SENT,
MSC_STAGE_NEED_RESET,
};
typedef struct
@@ -61,7 +62,7 @@ typedef struct
// Bulk Only Transfer (BOT) Protocol
uint8_t stage;
uint32_t total_len;
uint32_t total_len; // byte to be transferred, can be smaller than total_bytes in cbw
uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage
// Sense Response Data
@@ -78,7 +79,55 @@ CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t _mscd_buf[CFG_TUD_MSC_EP_
//--------------------------------------------------------------------+
static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_t* buffer, uint32_t bufsize);
static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc);
static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc);
static void proc_write10_new_data(uint8_t rhport, mscd_interface_t* p_msc, uint32_t xferred_bytes);
TU_ATTR_ALWAYS_INLINE static inline bool is_data_in(uint8_t dir)
{
return tu_bit_test(dir, 7);
}
static inline bool send_csw(uint8_t rhport, mscd_interface_t* p_msc)
{
// Data residue is always = host expect - actual transferred
p_msc->csw.data_residue = p_msc->cbw.total_bytes - p_msc->xferred_len;
p_msc->stage = MSC_STAGE_STATUS_SENT;
return usbd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t));
}
static inline bool prepare_cbw(uint8_t rhport, mscd_interface_t* p_msc)
{
p_msc->stage = MSC_STAGE_CMD;
return usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t));
}
static void fail_scsi_op(uint8_t rhport, mscd_interface_t* p_msc, uint8_t status)
{
msc_cbw_t const * p_cbw = &p_msc->cbw;
msc_csw_t * p_csw = &p_msc->csw;
p_csw->status = status;
p_csw->data_residue = p_msc->cbw.total_bytes - p_msc->xferred_len;
p_msc->stage = MSC_STAGE_STATUS;
// failed but sense key is not set: default to Illegal Request
if ( p_msc->sense_key == 0 ) tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00);
// If there is data stage and not yet complete, stall it
if ( p_cbw->total_bytes && p_csw->data_residue )
{
if ( is_data_in(p_cbw->dir) )
{
usbd_edpt_stall(rhport, p_msc->ep_in);
}
else
{
usbd_edpt_stall(rhport, p_msc->ep_out);
}
}
}
static inline uint32_t rdwr10_get_lba(uint8_t const command[])
{
@@ -89,15 +138,65 @@ static inline uint32_t rdwr10_get_lba(uint8_t const command[])
return tu_ntohl(lba);
}
static inline uint16_t rdwr10_get_blockcount(uint8_t const command[])
static inline uint16_t rdwr10_get_blockcount(msc_cbw_t const* cbw)
{
// use offsetof to avoid pointer to the odd/misaligned address
uint16_t const block_count = tu_unaligned_read16(command + offsetof(scsi_write10_t, block_count));
// block count is in Big Endian
uint16_t const block_count = tu_unaligned_read16(cbw->command + offsetof(scsi_write10_t, block_count));
return tu_ntohs(block_count);
}
static inline uint16_t rdwr10_get_blocksize(msc_cbw_t const* cbw)
{
// first extract block count in the command
uint16_t const block_count = rdwr10_get_blockcount(cbw);
// invalid block count
if (block_count == 0) return 0;
return (uint16_t) (cbw->total_bytes / block_count);
}
uint8_t rdwr10_validate_cmd(msc_cbw_t const* cbw)
{
uint8_t status = MSC_CSW_STATUS_PASSED;
uint16_t const block_count = rdwr10_get_blockcount(cbw);
if ( cbw->total_bytes == 0 )
{
if ( block_count )
{
TU_LOG(MSC_DEBUG, " SCSI case 2 (Hn < Di) or case 3 (Hn < Do) \r\n");
status = MSC_CSW_STATUS_PHASE_ERROR;
}else
{
// no data transfer, only exist in complaint test suite
}
}else
{
if ( SCSI_CMD_READ_10 == cbw->command[0] && !is_data_in(cbw->dir) )
{
TU_LOG(MSC_DEBUG, " SCSI case 10 (Ho <> Di)\r\n");
status = MSC_CSW_STATUS_PHASE_ERROR;
}
else if ( SCSI_CMD_WRITE_10 == cbw->command[0] && is_data_in(cbw->dir) )
{
TU_LOG(MSC_DEBUG, " SCSI case 8 (Hi <> Do)\r\n");
status = MSC_CSW_STATUS_PHASE_ERROR;
}
else if ( 0 == block_count )
{
TU_LOG(MSC_DEBUG, " SCSI case 4 Hi > Dn (READ10) or case 9 Ho > Dn (WRITE10) \r\n");
status = MSC_CSW_STATUS_FAILED;
}
else if ( cbw->total_bytes / block_count == 0 )
{
TU_LOG(MSC_DEBUG, " Computed block size = 0. SCSI case 7 Hi < Di (READ10) or case 13 Ho < Do (WRIT10)\r\n");
status = MSC_CSW_STATUS_PHASE_ERROR;
}
}
return status;
}
//--------------------------------------------------------------------+
// Debug
//--------------------------------------------------------------------+
@@ -164,7 +263,7 @@ uint16_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint1
// msc driver length is fixed
uint16_t const drv_len = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t);
// Max length mus be at least 1 interface + 2 endpoints
// Max length must be at least 1 interface + 2 endpoints
TU_ASSERT(max_len >= drv_len, 0);
mscd_interface_t * p_msc = &_mscd_itf;
@@ -174,35 +273,93 @@ uint16_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint1
TU_ASSERT( usbd_open_edpt_pair(rhport, tu_desc_next(itf_desc), 2, TUSB_XFER_BULK, &p_msc->ep_out, &p_msc->ep_in), 0 );
// Prepare for Command Block Wrapper
if ( !usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) )
{
TU_LOG_FAILED();
TU_BREAKPOINT();
}
TU_ASSERT( prepare_cbw(rhport, p_msc), drv_len);
return drv_len;
}
static void proc_bot_reset(mscd_interface_t* p_msc)
{
p_msc->stage = MSC_STAGE_CMD;
p_msc->total_len = 0;
p_msc->xferred_len = 0;
p_msc->sense_key = 0;
p_msc->add_sense_code = 0;
p_msc->add_sense_qualifier = 0;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool mscd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * p_request)
bool mscd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request)
{
// nothing to do with DATA & ACK stage
if (stage != CONTROL_STAGE_SETUP) return true;
// Handle class request only
TU_VERIFY(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
mscd_interface_t* p_msc = &_mscd_itf;
switch ( p_request->bRequest )
// Clear Endpoint Feature (stall) for recovery
if ( TUSB_REQ_TYPE_STANDARD == request->bmRequestType_bit.type &&
TUSB_REQ_RCPT_ENDPOINT == request->bmRequestType_bit.recipient &&
TUSB_REQ_CLEAR_FEATURE == request->bRequest &&
TUSB_REQ_FEATURE_EDPT_HALT == request->wValue )
{
uint8_t const ep_addr = tu_u16_low(request->wIndex);
if ( p_msc->stage == MSC_STAGE_NEED_RESET )
{
// reset recovery is required to recover from this stage
// Clear Stall request cannot resolve this -> continue to stall endpoint
usbd_edpt_stall(rhport, ep_addr);
}
else
{
if ( ep_addr == p_msc->ep_in )
{
if ( p_msc->stage == MSC_STAGE_STATUS )
{
// resume sending SCSI status if we are in this stage previously before stalled
TU_ASSERT( send_csw(rhport, p_msc) );
}
}
else if ( ep_addr == p_msc->ep_out )
{
if ( p_msc->stage == MSC_STAGE_CMD )
{
// part of reset recovery (probably due to invalid CBW) -> prepare for new command
// Note: skip if already queued previously
if ( usbd_edpt_ready(rhport, p_msc->ep_out) )
{
TU_ASSERT( prepare_cbw(rhport, p_msc) );
}
}
}
}
return true;
}
// From this point only handle class request only
TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
switch ( request->bRequest )
{
case MSC_REQ_RESET:
// TODO: Actually reset interface.
tud_control_status(rhport, p_request);
TU_LOG(MSC_DEBUG, " MSC BOT Reset\r\n");
TU_VERIFY(request->wValue == 0 && request->wLength == 0);
// driver state reset
proc_bot_reset(p_msc);
tud_control_status(rhport, request);
break;
case MSC_REQ_GET_MAX_LUN:
{
TU_LOG(MSC_DEBUG, " MSC Get Max Lun\r\n");
TU_VERIFY(request->wValue == 0 && request->wLength == 1);
uint8_t maxlun = 1;
if (tud_msc_get_maxlun_cb) maxlun = tud_msc_get_maxlun_cb();
TU_VERIFY(maxlun);
@@ -210,7 +367,7 @@ bool mscd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t
// MAX LUN is minus 1 by specs
maxlun--;
tud_control_xfer(rhport, p_request, &maxlun, 1);
tud_control_xfer(rhport, request, &maxlun, 1);
}
break;
@@ -222,6 +379,8 @@ bool mscd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t
bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
{
(void) event;
mscd_interface_t* p_msc = &_mscd_itf;
msc_cbw_t const * p_cbw = &p_msc->cbw;
msc_csw_t * p_csw = &p_msc->csw;
@@ -233,46 +392,79 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t
// Complete IN while waiting for CMD is usually Status of previous SCSI op, ignore it
if(ep_addr != p_msc->ep_out) return true;
TU_ASSERT( event == XFER_RESULT_SUCCESS &&
xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE );
if ( !(xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE) )
{
TU_LOG(MSC_DEBUG, " SCSI CBW is not valid\r\n");
// BOT 6.6.1 If CBW is not valid stall both endpoints until reset recovery
p_msc->stage = MSC_STAGE_NEED_RESET;
// invalid CBW stall both endpoints
usbd_edpt_stall(rhport, p_msc->ep_in);
usbd_edpt_stall(rhport, p_msc->ep_out);
return false;
}
TU_LOG(MSC_DEBUG, " SCSI Command: %s\r\n", tu_lookup_find(&_msc_scsi_cmd_table, p_cbw->command[0]));
// TU_LOG_MEM(MSC_DEBUG, p_cbw, xferred_bytes, 2);
//TU_LOG_MEM(MSC_DEBUG, p_cbw, xferred_bytes, 2);
p_csw->signature = MSC_CSW_SIGNATURE;
p_csw->tag = p_cbw->tag;
p_csw->data_residue = 0;
p_csw->status = MSC_CSW_STATUS_PASSED;
/*------------- Parse command and prepare DATA -------------*/
p_msc->stage = MSC_STAGE_DATA;
p_msc->total_len = p_cbw->total_bytes;
p_msc->xferred_len = 0;
if (SCSI_CMD_READ_10 == p_cbw->command[0])
// Read10 or Write10
if ( (SCSI_CMD_READ_10 == p_cbw->command[0]) || (SCSI_CMD_WRITE_10 == p_cbw->command[0]) )
{
proc_read10_cmd(rhport, p_msc);
}
else if (SCSI_CMD_WRITE_10 == p_cbw->command[0])
{
proc_write10_cmd(rhport, p_msc);
uint8_t const status = rdwr10_validate_cmd(p_cbw);
if ( status != MSC_CSW_STATUS_PASSED)
{
fail_scsi_op(rhport, p_msc, status);
}else if ( p_cbw->total_bytes )
{
if (SCSI_CMD_READ_10 == p_cbw->command[0])
{
proc_read10_cmd(rhport, p_msc);
}else
{
proc_write10_cmd(rhport, p_msc);
}
}else
{
// no data transfer, only exist in complaint test suite
p_msc->stage = MSC_STAGE_STATUS;
}
}
else
{
// For other SCSI commands
// 1. OUT : queue transfer (invoke app callback after done)
// 2. IN & Zero: Process if is built-in, else Invoke app callback. Skip DATA if zero length
if ( (p_cbw->total_bytes > 0 ) && !tu_bit_test(p_cbw->dir, 7) )
if ( (p_cbw->total_bytes > 0 ) && !is_data_in(p_cbw->dir) )
{
// queue transfer
TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->total_len) );
if (p_cbw->total_bytes > sizeof(_mscd_buf))
{
TU_LOG(MSC_DEBUG, " SCSI reject non READ10/WRITE10 with large data\r\n");
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
}else
{
// Didn't check for case 9 (Ho > Dn), which requires examining scsi command first
// but it is OK to just receive data then responded with failed status
TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->total_len) );
}
}else
{
int32_t resplen;
// First process if it is a built-in commands
resplen = proc_builtin_scsi(p_cbw->lun, p_cbw->command, _mscd_buf, sizeof(_mscd_buf));
int32_t resplen = proc_builtin_scsi(p_cbw->lun, p_cbw->command, _mscd_buf, sizeof(_mscd_buf));
// Not built-in, invoke user callback
// Invoke user callback if not built-in
if ( (resplen < 0) && (p_msc->sense_key == 0) )
{
resplen = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len);
@@ -280,28 +472,35 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t
if ( resplen < 0 )
{
p_msc->total_len = 0;
p_csw->status = MSC_CSW_STATUS_FAILED;
p_msc->stage = MSC_STAGE_STATUS;
// failed but senskey is not set: default to Illegal Request
if ( p_msc->sense_key == 0 ) tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00);
// Stall bulk In if needed
if (p_cbw->total_bytes) usbd_edpt_stall(rhport, p_msc->ep_in);
// unsupported command
TU_LOG(MSC_DEBUG, " SCSI unsupported command\r\n");
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
}
else if (resplen == 0)
{
if (p_cbw->total_bytes)
{
// 6.7 The 13 Cases: case 4 (Hi > Dn)
// TU_LOG(MSC_DEBUG, " SCSI case 4 (Hi > Dn): %lu\r\n", p_cbw->total_bytes);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
}else
{
// case 1 Hn = Dn: all good
p_msc->stage = MSC_STAGE_STATUS;
}
}
else
{
p_msc->total_len = (uint32_t) resplen;
p_csw->status = MSC_CSW_STATUS_PASSED;
if (p_msc->total_len)
if ( p_cbw->total_bytes == 0 )
{
TU_ASSERT( p_cbw->total_bytes >= p_msc->total_len ); // cannot return more than host expect
TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->total_len) );
// 6.7 The 13 Cases: case 2 (Hn < Di)
// TU_LOG(MSC_DEBUG, " SCSI case 2 (Hn < Di): %lu\r\n", p_cbw->total_bytes);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
}else
{
p_msc->stage = MSC_STAGE_STATUS;
// cannot return more than host expect
p_msc->total_len = tu_min32((uint32_t) resplen, p_cbw->total_bytes);
TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->total_len) );
}
}
}
@@ -312,87 +511,51 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t
TU_LOG(MSC_DEBUG, " SCSI Data\r\n");
//TU_LOG_MEM(MSC_DEBUG, _mscd_buf, xferred_bytes, 2);
// OUT transfer, invoke callback if needed
if ( !tu_bit_test(p_cbw->dir, 7) )
if (SCSI_CMD_READ_10 == p_cbw->command[0])
{
if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] )
p_msc->xferred_len += xferred_bytes;
if ( p_msc->xferred_len >= p_msc->total_len )
{
// Data Stage is complete
p_msc->stage = MSC_STAGE_STATUS;
}else
{
proc_read10_cmd(rhport, p_msc);
}
}
else if (SCSI_CMD_WRITE_10 == p_cbw->command[0])
{
proc_write10_new_data(rhport, p_msc, xferred_bytes);
}
else
{
p_msc->xferred_len += xferred_bytes;
// OUT transfer, invoke callback if needed
if ( !is_data_in(p_cbw->dir) )
{
int32_t cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len);
if ( cb_result < 0 )
{
p_csw->status = MSC_CSW_STATUS_FAILED;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
// unsupported command
TU_LOG(MSC_DEBUG, " SCSI unsupported command\r\n");
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
}else
{
p_csw->status = MSC_CSW_STATUS_PASSED;
// TODO haven't implement this scenario any further yet
}
}
if ( p_msc->xferred_len >= p_msc->total_len )
{
// Data Stage is complete
p_msc->stage = MSC_STAGE_STATUS;
}
else
{
uint16_t const block_sz = p_cbw->total_bytes / rdwr10_get_blockcount(p_cbw->command);
// Adjust lba with transferred bytes
uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz);
// Application can consume smaller bytes
int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, xferred_bytes);
if ( nbytes < 0 )
{
// negative means error -> skip to status phase, status in CSW set to failed
p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len;
p_csw->status = MSC_CSW_STATUS_FAILED;
p_msc->stage = MSC_STAGE_STATUS;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
break;
}else
{
// Application consume less than what we got (including zero)
if ( nbytes < (int32_t) xferred_bytes )
{
if ( nbytes > 0 )
{
p_msc->xferred_len += nbytes;
memmove(_mscd_buf, _mscd_buf+nbytes, xferred_bytes-nbytes);
}
// simulate an transfer complete with adjusted parameters --> this driver callback will fired again
dcd_event_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, XFER_RESULT_SUCCESS, false);
return true; // skip the rest
}
else
{
// Application consume all bytes in our buffer. Nothing to do, process with normal flow
}
}
}
}
// Accumulate data so far
p_msc->xferred_len += xferred_bytes;
if ( p_msc->xferred_len >= p_msc->total_len )
{
// Data Stage is complete
p_msc->stage = MSC_STAGE_STATUS;
}
else
{
// READ10 & WRITE10 Can be executed with large bulk of data e.g write 8K bytes (several flash write)
// We break it into multiple smaller command whose data size is up to CFG_TUD_MSC_EP_BUFSIZE
if (SCSI_CMD_READ_10 == p_cbw->command[0])
{
proc_read10_cmd(rhport, p_msc);
}
else if (SCSI_CMD_WRITE_10 == p_cbw->command[0])
{
proc_write10_cmd(rhport, p_msc);
}else
{
// No other command take more than one transfer yet -> unlikely error
// This scenario with command that take more than one transfer is already rejected at Command stage
TU_BREAKPOINT();
}
}
@@ -406,7 +569,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t
// Wait for the Status phase to complete
if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) )
{
TU_LOG(MSC_DEBUG, " SCSI Status: %u\r\n", p_csw->status);
TU_LOG(MSC_DEBUG, " SCSI Status = %u\r\n", p_csw->status);
// TU_LOG_MEM(MSC_DEBUG, p_csw, xferred_bytes, 2);
// Invoke complete callback if defined
@@ -427,11 +590,11 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t
break;
}
// Move to default CMD stage
p_msc->stage = MSC_STAGE_CMD;
// Queue for the next CBW
TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) );
TU_ASSERT( prepare_cbw(rhport, p_msc) );
}else
{
// Any xfer ended here is consider unknown error, ignore it
TU_LOG1(" Warning expect SCSI Status but received unknown data\r\n");
}
break;
@@ -440,22 +603,30 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t
if ( p_msc->stage == MSC_STAGE_STATUS )
{
// Either endpoints is stalled, need to wait until it is cleared by host
if ( usbd_edpt_stalled(rhport, p_msc->ep_in) || usbd_edpt_stalled(rhport, p_msc->ep_out) )
// skip status if epin is currently stalled, will do it when received Clear Stall request
if ( !usbd_edpt_stalled(rhport, p_msc->ep_in) )
{
// simulate an transfer complete with adjusted parameters --> this driver callback will fired again
// and response with status phase after halted endpoints are cleared.
// note: use ep_out to prevent confusing with STATUS complete
dcd_event_xfer_complete(rhport, p_msc->ep_out, 0, XFER_RESULT_SUCCESS, false);
if ( (p_cbw->total_bytes > p_msc->xferred_len) && is_data_in(p_cbw->dir) )
{
// 6.7 The 13 Cases: case 5 (Hi > Di): STALL before status
// TU_LOG(MSC_DEBUG, " SCSI case 5 (Hi > Di): %lu > %lu\r\n", p_cbw->total_bytes, p_msc->xferred_len);
usbd_edpt_stall(rhport, p_msc->ep_in);
}else
{
TU_ASSERT( send_csw(rhport, p_msc) );
}
}
else
{
// Move to Status Sent stage
p_msc->stage = MSC_STAGE_STATUS_SENT;
// Send SCSI Status
TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t)));
#if TU_CHECK_MCU(OPT_MCU_CXD56)
// WORKAROUND: cxd56 has its own nuttx usb stack which does not forward Set/ClearFeature(Endpoint) to DCD.
// There is no way for us to know when EP is un-stall, therefore we will unconditionally un-stall here and
// hope everything will work
if ( usbd_edpt_stalled(rhport, p_msc->ep_in) )
{
usbd_edpt_clear_stall(rhport, p_msc->ep_in);
send_csw(rhport, p_msc);
}
#endif
}
return true;
@@ -472,6 +643,8 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_
(void) bufsize; // TODO refractor later
int32_t resplen;
mscd_interface_t* p_msc = &_mscd_itf;
switch ( scsi_cmd[0] )
{
case SCSI_CMD_TEST_UNIT_READY:
@@ -482,7 +655,7 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_
resplen = - 1;
// If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable
if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
if ( p_msc->sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
}
break;
@@ -498,7 +671,7 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_
resplen = - 1;
// If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable
if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
if ( p_msc->sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
}
}
break;
@@ -519,7 +692,7 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_
resplen = -1;
// If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable
if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
if ( p_msc->sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
}else
{
scsi_read_capacity10_resp_t read_capa10;
@@ -555,7 +728,7 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_
resplen = -1;
// If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable
if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
if ( p_msc->sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
}else
{
read_fmt_capa.block_num = tu_htonl(block_count);
@@ -600,9 +773,11 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_
};
bool writable = true;
if (tud_msc_is_writable_cb) {
writable = tud_msc_is_writable_cb(lun);
if ( tud_msc_is_writable_cb )
{
writable = tud_msc_is_writable_cb(lun);
}
mode_resp.write_protected = !writable;
resplen = sizeof(mode_resp);
@@ -620,9 +795,9 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_
sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_resp_t) - 8;
sense_rsp.sense_key = _mscd_itf.sense_key;
sense_rsp.add_sense_code = _mscd_itf.add_sense_code;
sense_rsp.add_sense_qualifier = _mscd_itf.add_sense_qualifier;
sense_rsp.sense_key = p_msc->sense_key;
sense_rsp.add_sense_code = p_msc->add_sense_code;
sense_rsp.add_sense_qualifier = p_msc->add_sense_qualifier;
resplen = sizeof(sense_rsp);
memcpy(buffer, &sense_rsp, resplen);
@@ -641,13 +816,9 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_
static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc)
{
msc_cbw_t const * p_cbw = &p_msc->cbw;
msc_csw_t * p_csw = &p_msc->csw;
uint16_t const block_cnt = rdwr10_get_blockcount(p_cbw->command);
TU_ASSERT(block_cnt, ); // prevent div by zero
uint16_t const block_sz = p_cbw->total_bytes / block_cnt;
TU_ASSERT(block_sz, ); // prevent div by zero
// block size already verified not zero
uint16_t const block_sz = rdwr10_get_blocksize(p_cbw);
// Adjust lba with transferred bytes
uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz);
@@ -656,16 +827,18 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc)
int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len);
// Application can consume smaller bytes
nbytes = tud_msc_read10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes);
uint32_t const offset = p_msc->xferred_len % block_sz;
nbytes = tud_msc_read10_cb(p_cbw->lun, lba, offset, _mscd_buf, (uint32_t) nbytes);
if ( nbytes < 0 )
{
// negative means error -> pipe is stalled & status in CSW set to failed
p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len;
p_csw->status = MSC_CSW_STATUS_FAILED;
// negative means error -> endpoint is stalled & status in CSW set to failed
TU_LOG(MSC_DEBUG, " tud_msc_read10_cb() return -1\r\n");
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
usbd_edpt_stall(rhport, p_msc->ep_in);
// Sense = Flash not ready for access
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_MEDIUM_ERROR, 0x33, 0x00);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
}
else if ( nbytes == 0 )
{
@@ -682,16 +855,18 @@ static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc)
{
msc_cbw_t const * p_cbw = &p_msc->cbw;
bool writable = true;
if (tud_msc_is_writable_cb) {
if ( tud_msc_is_writable_cb )
{
writable = tud_msc_is_writable_cb(p_cbw->lun);
}
if (!writable) {
msc_csw_t* p_csw = &p_msc->csw;
p_csw->data_residue = p_cbw->total_bytes;
p_csw->status = MSC_CSW_STATUS_FAILED;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_DATA_PROTECT, 0x27, 0x00); // Sense = Write protected
usbd_edpt_stall(rhport, p_msc->ep_out);
if ( !writable )
{
// Not writable, complete this SCSI op with error
// Sense = Write protected
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_DATA_PROTECT, 0x27, 0x00);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
return;
}
@@ -702,4 +877,63 @@ static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc)
TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, nbytes), );
}
// process new data arrived from WRITE10
static void proc_write10_new_data(uint8_t rhport, mscd_interface_t* p_msc, uint32_t xferred_bytes)
{
msc_cbw_t const * p_cbw = &p_msc->cbw;
// block size already verified not zero
uint16_t const block_sz = rdwr10_get_blocksize(p_cbw);
// Adjust lba with transferred bytes
uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz);
// Invoke callback to consume new data
uint32_t const offset = p_msc->xferred_len % block_sz;
int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, offset, _mscd_buf, xferred_bytes);
if ( nbytes < 0 )
{
// negative means error -> failed this scsi op
TU_LOG(MSC_DEBUG, " tud_msc_write10_cb() return -1\r\n");
// update actual byte before failed
p_msc->xferred_len += xferred_bytes;
// Sense = Flash not ready for access
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_MEDIUM_ERROR, 0x33, 0x00);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
}else
{
// Application consume less than what we got (including zero)
if ( (uint32_t) nbytes < xferred_bytes )
{
if ( nbytes > 0 )
{
p_msc->xferred_len += nbytes;
memmove(_mscd_buf, _mscd_buf+nbytes, xferred_bytes-nbytes);
}
// simulate an transfer complete with adjusted parameters --> callback will be invoked with adjusted parameter
dcd_event_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, XFER_RESULT_SUCCESS, false);
}
else
{
// Application consume all bytes in our buffer
p_msc->xferred_len += xferred_bytes;
if ( p_msc->xferred_len >= p_msc->total_len )
{
// Data Stage is complete
p_msc->stage = MSC_STAGE_STATUS;
}else
{
// prepare to receive more data from host
proc_write10_cmd(rhport, p_msc);
}
}
}
}
#endif
+1 -1
View File
@@ -140,7 +140,7 @@ TU_ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun);
// Invoked when command in tud_msc_scsi_cb is complete
TU_ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t lun, uint8_t const scsi_cmd[16]);
// Hook to make a mass storage device read-only. TODO remove
// Invoked to check if device is writable as part of SCSI WRITE10
TU_ATTR_WEAK bool tud_msc_is_writable_cb(uint8_t lun);
//--------------------------------------------------------------------+
+1 -1
View File
@@ -263,7 +263,7 @@ bool tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * buffer, uint32_
memcpy(cbw.command, &cmd_write10, cbw.cmd_len);
return tuh_msc_scsi_command(dev_addr, &cbw, (void*) buffer, complete_cb);
return tuh_msc_scsi_command(dev_addr, &cbw, (void*)(uintptr_t) buffer, complete_cb);
}
#if 0
@@ -27,7 +27,7 @@
#include "tusb_option.h"
#if ( TUSB_OPT_DEVICE_ENABLED && CFG_TUD_NET )
#if ( TUSB_OPT_DEVICE_ENABLED && CFG_TUD_ECM_RNDIS )
#include "device/usbd.h"
#include "device/usbd_pvt.h"
@@ -119,6 +119,8 @@ static void do_in_xfer(uint8_t *buf, uint16_t len)
void netd_report(uint8_t *buf, uint16_t len)
{
// skip if previous report not yet acknowledged by host
if ( usbd_edpt_busy(TUD_OPT_RHPORT, _netd_itf.ep_notif) ) return;
usbd_edpt_xfer(TUD_OPT_RHPORT, _netd_itf.ep_notif, buf, len);
}
@@ -407,8 +409,10 @@ bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_
return true;
}
bool tud_network_can_xmit(void)
bool tud_network_can_xmit(uint16_t size)
{
(void)size;
return can_xmit;
}
+69
View File
@@ -0,0 +1,69 @@
/*
* 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_NCM_H_
#define _TUSB_NCM_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
// Table 4.3 Data Class Interface Protocol Codes
typedef enum
{
NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK = 0x01
} ncm_data_interface_protocol_code_t;
// Table 6.2 Class-Specific Request Codes for Network Control Model subclass
typedef enum
{
NCM_SET_ETHERNET_MULTICAST_FILTERS = 0x40,
NCM_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x41,
NCM_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x42,
NCM_SET_ETHERNET_PACKET_FILTER = 0x43,
NCM_GET_ETHERNET_STATISTIC = 0x44,
NCM_GET_NTB_PARAMETERS = 0x80,
NCM_GET_NET_ADDRESS = 0x81,
NCM_SET_NET_ADDRESS = 0x82,
NCM_GET_NTB_FORMAT = 0x83,
NCM_SET_NTB_FORMAT = 0x84,
NCM_GET_NTB_INPUT_SIZE = 0x85,
NCM_SET_NTB_INPUT_SIZE = 0x86,
NCM_GET_MAX_DATAGRAM_SIZE = 0x87,
NCM_SET_MAX_DATAGRAM_SIZE = 0x88,
NCM_GET_CRC_MODE = 0x89,
NCM_SET_CRC_MODE = 0x8A,
} ncm_request_code_t;
#ifdef __cplusplus
}
#endif
#endif
+510
View File
@@ -0,0 +1,510 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Jacob Berg Potter
* Copyright (c) 2020 Peter Lawrence
* Copyright (c) 2019 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.
*/
#include "tusb_option.h"
#if ( TUSB_OPT_DEVICE_ENABLED && CFG_TUD_NCM )
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "net_device.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
#define NTH16_SIGNATURE 0x484D434E
#define NDP16_SIGNATURE_NCM0 0x304D434E
#define NDP16_SIGNATURE_NCM1 0x314D434E
typedef struct TU_ATTR_PACKED
{
uint16_t wLength;
uint16_t bmNtbFormatsSupported;
uint32_t dwNtbInMaxSize;
uint16_t wNdbInDivisor;
uint16_t wNdbInPayloadRemainder;
uint16_t wNdbInAlignment;
uint16_t wReserved;
uint32_t dwNtbOutMaxSize;
uint16_t wNdbOutDivisor;
uint16_t wNdbOutPayloadRemainder;
uint16_t wNdbOutAlignment;
uint16_t wNtbOutMaxDatagrams;
} ntb_parameters_t;
typedef struct TU_ATTR_PACKED
{
uint32_t dwSignature;
uint16_t wHeaderLength;
uint16_t wSequence;
uint16_t wBlockLength;
uint16_t wNdpIndex;
} nth16_t;
typedef struct TU_ATTR_PACKED
{
uint16_t wDatagramIndex;
uint16_t wDatagramLength;
} ndp16_datagram_t;
typedef struct TU_ATTR_PACKED
{
uint32_t dwSignature;
uint16_t wLength;
uint16_t wNextNdpIndex;
ndp16_datagram_t datagram[];
} ndp16_t;
typedef union TU_ATTR_PACKED {
struct {
nth16_t nth;
ndp16_t ndp;
};
uint8_t data[CFG_TUD_NCM_IN_NTB_MAX_SIZE];
} transmit_ntb_t;
struct ecm_notify_struct
{
tusb_control_request_t header;
uint32_t downlink, uplink;
};
typedef struct
{
uint8_t itf_num; // Index number of Management Interface, +1 for Data Interface
uint8_t itf_data_alt; // Alternate setting of Data Interface. 0 : inactive, 1 : active
uint8_t ep_notif;
uint8_t ep_in;
uint8_t ep_out;
const ndp16_t *ndp;
uint8_t num_datagrams, current_datagram_index;
enum {
REPORT_SPEED,
REPORT_CONNECTED,
REPORT_DONE
} report_state;
bool report_pending;
uint8_t current_ntb; // Index in transmit_ntb[] that is currently being filled with datagrams
uint8_t datagram_count; // Number of datagrams in transmit_ntb[current_ntb]
uint16_t next_datagram_offset; // Offset in transmit_ntb[current_ntb].data to place the next datagram
uint16_t ntb_in_size; // Maximum size of transmitted (IN to host) NTBs; initially CFG_TUD_NCM_IN_NTB_MAX_SIZE
uint8_t max_datagrams_per_ntb; // Maximum number of datagrams per NTB; initially CFG_TUD_NCM_MAX_DATAGRAMS_PER_NTB
uint16_t nth_sequence; // Sequence number counter for transmitted NTBs
bool transferring;
} ncm_interface_t;
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static const ntb_parameters_t ntb_parameters = {
.wLength = sizeof(ntb_parameters_t),
.bmNtbFormatsSupported = 0x01,
.dwNtbInMaxSize = CFG_TUD_NCM_IN_NTB_MAX_SIZE,
.wNdbInDivisor = 4,
.wNdbInPayloadRemainder = 0,
.wNdbInAlignment = CFG_TUD_NCM_ALIGNMENT,
.wReserved = 0,
.dwNtbOutMaxSize = CFG_TUD_NCM_OUT_NTB_MAX_SIZE,
.wNdbOutDivisor = 4,
.wNdbOutPayloadRemainder = 0,
.wNdbOutAlignment = CFG_TUD_NCM_ALIGNMENT,
.wNtbOutMaxDatagrams = 0
};
CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static transmit_ntb_t transmit_ntb[2];
CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t receive_ntb[CFG_TUD_NCM_OUT_NTB_MAX_SIZE];
static ncm_interface_t ncm_interface;
/*
* Set up the NTB state in ncm_interface to be ready to add datagrams.
*/
static void ncm_prepare_for_tx(void) {
ncm_interface.datagram_count = 0;
// datagrams start after all the headers
ncm_interface.next_datagram_offset = sizeof(nth16_t) + sizeof(ndp16_t)
+ ((CFG_TUD_NCM_MAX_DATAGRAMS_PER_NTB + 1) * sizeof(ndp16_datagram_t));
}
/*
* If not already transmitting, start sending the current NTB to the host and swap buffers
* to start filling the other one with datagrams.
*/
static void ncm_start_tx(void) {
if (ncm_interface.transferring) {
return;
}
transmit_ntb_t *ntb = &transmit_ntb[ncm_interface.current_ntb];
size_t ntb_length = ncm_interface.next_datagram_offset;
// Fill in NTB header
ntb->nth.dwSignature = NTH16_SIGNATURE;
ntb->nth.wHeaderLength = sizeof(nth16_t);
ntb->nth.wSequence = ncm_interface.nth_sequence++;
ntb->nth.wBlockLength = ntb_length;
ntb->nth.wNdpIndex = sizeof(nth16_t);
// Fill in NDP16 header and terminator
ntb->ndp.dwSignature = NDP16_SIGNATURE_NCM0;
ntb->ndp.wLength = sizeof(ndp16_t) + (ncm_interface.datagram_count + 1) * sizeof(ndp16_datagram_t);
ntb->ndp.wNextNdpIndex = 0;
ntb->ndp.datagram[ncm_interface.datagram_count].wDatagramIndex = 0;
ntb->ndp.datagram[ncm_interface.datagram_count].wDatagramLength = 0;
// Kick off an endpoint transfer
usbd_edpt_xfer(TUD_OPT_RHPORT, ncm_interface.ep_in, ntb->data, ntb_length);
ncm_interface.transferring = true;
// Swap to the other NTB and clear it out
ncm_interface.current_ntb = 1 - ncm_interface.current_ntb;
ncm_prepare_for_tx();
}
static struct ecm_notify_struct ncm_notify_connected =
{
.header = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_IN
},
.bRequest = CDC_NOTIF_NETWORK_CONNECTION,
.wValue = 1 /* Connected */,
.wLength = 0,
},
};
static struct ecm_notify_struct ncm_notify_speed_change =
{
.header = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_IN
},
.bRequest = CDC_NOTIF_CONNECTION_SPEED_CHANGE,
.wLength = 8,
},
.downlink = 10000000,
.uplink = 10000000,
};
void tud_network_recv_renew(void)
{
if (!ncm_interface.num_datagrams)
{
usbd_edpt_xfer(TUD_OPT_RHPORT, ncm_interface.ep_out, receive_ntb, sizeof(receive_ntb));
return;
}
const ndp16_t *ndp = ncm_interface.ndp;
const int i = ncm_interface.current_datagram_index;
ncm_interface.current_datagram_index++;
ncm_interface.num_datagrams--;
tud_network_recv_cb(receive_ntb + ndp->datagram[i].wDatagramIndex, ndp->datagram[i].wDatagramLength);
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void netd_init(void)
{
tu_memclr(&ncm_interface, sizeof(ncm_interface));
ncm_interface.ntb_in_size = CFG_TUD_NCM_IN_NTB_MAX_SIZE;
ncm_interface.max_datagrams_per_ntb = CFG_TUD_NCM_MAX_DATAGRAMS_PER_NTB;
ncm_prepare_for_tx();
}
void netd_reset(uint8_t rhport)
{
(void) rhport;
netd_init();
}
uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len)
{
// confirm interface hasn't already been allocated
TU_ASSERT(0 == ncm_interface.ep_notif, 0);
//------------- Management Interface -------------//
ncm_interface.itf_num = itf_desc->bInterfaceNumber;
uint16_t drv_len = sizeof(tusb_desc_interface_t);
uint8_t const * p_desc = tu_desc_next( itf_desc );
// Communication Functional Descriptors
while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len )
{
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
// notification endpoint (if any)
if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
{
TU_ASSERT( usbd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), 0 );
ncm_interface.ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress;
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
//------------- Data Interface -------------//
// - CDC-NCM data interface has 2 alternate settings
// - 0 : zero endpoints for inactive (default)
// - 1 : IN & OUT endpoints for transfer of NTBs
TU_ASSERT(TUSB_DESC_INTERFACE == tu_desc_type(p_desc), 0);
do
{
tusb_desc_interface_t const * data_itf_desc = (tusb_desc_interface_t const *) p_desc;
TU_ASSERT(TUSB_CLASS_CDC_DATA == data_itf_desc->bInterfaceClass, 0);
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
} while((TUSB_DESC_INTERFACE == tu_desc_type(p_desc)) && (drv_len <= max_len));
// Pair of endpoints
TU_ASSERT(TUSB_DESC_ENDPOINT == tu_desc_type(p_desc), 0);
TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &ncm_interface.ep_out, &ncm_interface.ep_in) );
drv_len += 2*sizeof(tusb_desc_endpoint_t);
return drv_len;
}
static void ncm_report(void)
{
if (ncm_interface.report_state == REPORT_SPEED) {
ncm_notify_speed_change.header.wIndex = ncm_interface.itf_num;
usbd_edpt_xfer(TUD_OPT_RHPORT, ncm_interface.ep_notif, (uint8_t *) &ncm_notify_speed_change, sizeof(ncm_notify_speed_change));
ncm_interface.report_state = REPORT_CONNECTED;
ncm_interface.report_pending = true;
} else if (ncm_interface.report_state == REPORT_CONNECTED) {
ncm_notify_connected.header.wIndex = ncm_interface.itf_num;
usbd_edpt_xfer(TUD_OPT_RHPORT, ncm_interface.ep_notif, (uint8_t *) &ncm_notify_connected, sizeof(ncm_notify_connected));
ncm_interface.report_state = REPORT_DONE;
ncm_interface.report_pending = true;
}
}
TU_ATTR_WEAK void tud_network_link_state_cb(bool state)
{
(void)state;
}
// Handle class control request
// return false to stall control endpoint (e.g unsupported request)
bool netd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request)
{
if ( stage != CONTROL_STAGE_SETUP ) return true;
switch ( request->bmRequestType_bit.type )
{
case TUSB_REQ_TYPE_STANDARD:
switch ( request->bRequest )
{
case TUSB_REQ_GET_INTERFACE:
{
uint8_t const req_itfnum = (uint8_t) request->wIndex;
TU_VERIFY(ncm_interface.itf_num + 1 == req_itfnum);
tud_control_xfer(rhport, request, &ncm_interface.itf_data_alt, 1);
}
break;
case TUSB_REQ_SET_INTERFACE:
{
uint8_t const req_itfnum = (uint8_t) request->wIndex;
uint8_t const req_alt = (uint8_t) request->wValue;
// Only valid for Data Interface with Alternate is either 0 or 1
TU_VERIFY(ncm_interface.itf_num + 1 == req_itfnum && req_alt < 2);
if (req_alt != ncm_interface.itf_data_alt) {
ncm_interface.itf_data_alt = req_alt;
if (ncm_interface.itf_data_alt) {
if (!usbd_edpt_busy(rhport, ncm_interface.ep_out)) {
tud_network_recv_renew(); // prepare for incoming datagrams
}
if (!ncm_interface.report_pending) {
ncm_report();
}
}
tud_network_link_state_cb(ncm_interface.itf_data_alt);
}
tud_control_status(rhport, request);
}
break;
// unsupported request
default: return false;
}
break;
case TUSB_REQ_TYPE_CLASS:
TU_VERIFY (ncm_interface.itf_num == request->wIndex);
if (NCM_GET_NTB_PARAMETERS == request->bRequest)
{
tud_control_xfer(rhport, request, (void*)&ntb_parameters, sizeof(ntb_parameters));
}
break;
// unsupported request
default: return false;
}
return true;
}
static void handle_incoming_datagram(uint32_t len)
{
uint32_t size = len;
if (len == 0) {
return;
}
TU_ASSERT(size >= sizeof(nth16_t), );
const nth16_t *hdr = (const nth16_t *)receive_ntb;
TU_ASSERT(hdr->dwSignature == NTH16_SIGNATURE, );
TU_ASSERT(hdr->wNdpIndex >= sizeof(nth16_t) && (hdr->wNdpIndex + sizeof(ndp16_t)) <= len, );
const ndp16_t *ndp = (const ndp16_t *)(receive_ntb + hdr->wNdpIndex);
TU_ASSERT(ndp->dwSignature == NDP16_SIGNATURE_NCM0 || ndp->dwSignature == NDP16_SIGNATURE_NCM1, );
TU_ASSERT(hdr->wNdpIndex + ndp->wLength <= len, );
int num_datagrams = (ndp->wLength - 12) / 4;
ncm_interface.current_datagram_index = 0;
ncm_interface.num_datagrams = 0;
ncm_interface.ndp = ndp;
for (int i = 0; i < num_datagrams && ndp->datagram[i].wDatagramIndex && ndp->datagram[i].wDatagramLength; i++)
{
ncm_interface.num_datagrams++;
}
tud_network_recv_renew();
}
bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
{
(void) rhport;
(void) result;
/* new datagram receive_ntb */
if (ep_addr == ncm_interface.ep_out )
{
handle_incoming_datagram(xferred_bytes);
}
/* data transmission finished */
if (ep_addr == ncm_interface.ep_in )
{
if (ncm_interface.transferring) {
ncm_interface.transferring = false;
}
// If there are datagrams queued up that we tried to send while this NTB was being emitted, send them now
if (ncm_interface.datagram_count && ncm_interface.itf_data_alt == 1) {
ncm_start_tx();
}
}
if (ep_addr == ncm_interface.ep_notif )
{
ncm_interface.report_pending = false;
ncm_report();
}
return true;
}
// poll network driver for its ability to accept another packet to transmit
bool tud_network_can_xmit(uint16_t size)
{
TU_VERIFY(ncm_interface.itf_data_alt == 1);
if (ncm_interface.datagram_count >= ncm_interface.max_datagrams_per_ntb) {
TU_LOG2("NTB full [by count]\r\n");
return false;
}
size_t next_datagram_offset = ncm_interface.next_datagram_offset;
if (next_datagram_offset + size > ncm_interface.ntb_in_size) {
TU_LOG2("ntb full [by size]\r\n");
return false;
}
return true;
}
void tud_network_xmit(void *ref, uint16_t arg)
{
transmit_ntb_t *ntb = &transmit_ntb[ncm_interface.current_ntb];
size_t next_datagram_offset = ncm_interface.next_datagram_offset;
uint16_t size = tud_network_xmit_cb(ntb->data + next_datagram_offset, ref, arg);
ntb->ndp.datagram[ncm_interface.datagram_count].wDatagramIndex = ncm_interface.next_datagram_offset;
ntb->ndp.datagram[ncm_interface.datagram_count].wDatagramLength = size;
ncm_interface.datagram_count++;
next_datagram_offset += size;
// round up so the next datagram is aligned correctly
next_datagram_offset += (CFG_TUD_NCM_ALIGNMENT - 1);
next_datagram_offset -= (next_datagram_offset % CFG_TUD_NCM_ALIGNMENT);
ncm_interface.next_datagram_offset = next_datagram_offset;
ncm_start_tx();
}
#endif
+43 -10
View File
@@ -30,14 +30,36 @@
#include "class/cdc/cdc.h"
#if CFG_TUD_ECM_RNDIS && CFG_TUD_NCM
#error "Cannot enable both ECM_RNDIS and NCM network drivers"
#endif
#include "ncm.h"
/* declared here, NOT in usb_descriptors.c, so that the driver can intelligently ZLP as needed */
#define CFG_TUD_NET_ENDPOINT_SIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
/* Maximum Tranmission Unit (in bytes) of the network, including Ethernet header */
/* Maximum Transmission Unit (in bytes) of the network, including Ethernet header */
#ifndef CFG_TUD_NET_MTU
#define CFG_TUD_NET_MTU 1514
#endif
#ifndef CFG_TUD_NCM_IN_NTB_MAX_SIZE
#define CFG_TUD_NCM_IN_NTB_MAX_SIZE 3200
#endif
#ifndef CFG_TUD_NCM_OUT_NTB_MAX_SIZE
#define CFG_TUD_NCM_OUT_NTB_MAX_SIZE 3200
#endif
#ifndef CFG_TUD_NCM_MAX_DATAGRAMS_PER_NTB
#define CFG_TUD_NCM_MAX_DATAGRAMS_PER_NTB 8
#endif
#ifndef CFG_TUD_NCM_ALIGNMENT
#define CFG_TUD_NCM_ALIGNMENT 4
#endif
#ifdef __cplusplus
extern "C" {
#endif
@@ -46,8 +68,18 @@
// Application API
//--------------------------------------------------------------------+
// client must provide this: initialize any network state back to the beginning
void tud_network_init_cb(void);
// indicate to network driver that client has finished with the packet provided to network_recv_cb()
void tud_network_recv_renew(void);
// poll network driver for its ability to accept another packet to transmit
bool tud_network_can_xmit(uint16_t size);
// if network_can_xmit() returns true, network_xmit() can be called once
void tud_network_xmit(void *ref, uint16_t arg);
//--------------------------------------------------------------------+
// Application Callbacks (WEAK is optional)
//--------------------------------------------------------------------+
// client must provide this: return false if the packet buffer was not accepted
bool tud_network_recv_cb(const uint8_t *src, uint16_t size);
@@ -55,18 +87,19 @@ bool tud_network_recv_cb(const uint8_t *src, uint16_t size);
// client must provide this: copy from network stack packet pointer to dst
uint16_t tud_network_xmit_cb(uint8_t *dst, void *ref, uint16_t arg);
//------------- ECM/RNDIS -------------//
// client must provide this: initialize any network state back to the beginning
void tud_network_init_cb(void);
// client must provide this: 48-bit MAC address
// TODO removed later since it is not part of tinyusb stack
extern const uint8_t tud_network_mac_address[6];
// indicate to network driver that client has finished with the packet provided to network_recv_cb()
void tud_network_recv_renew(void);
//------------- NCM -------------//
// poll network driver for its ability to accept another packet to transmit
bool tud_network_can_xmit(void);
// if network_can_xmit() returns true, network_xmit() can be called once
void tud_network_xmit(void *ref, uint16_t arg);
// callback to client providing optional indication of internal state of network driver
void tud_network_link_state_cb(bool state);
//--------------------------------------------------------------------+
// INTERNAL USBD-CLASS DRIVER API
+20 -24
View File
@@ -1,10 +1,3 @@
/*
* usbtmc.c
*
* Created on: Sep 9, 2019
* Author: nconrad
*/
/*
* The MIT License (MIT)
*
@@ -205,7 +198,7 @@ bool tud_usbtmc_transmit_dev_msg_data(
{
TU_ASSERT(usbtmc_state.capabilities->bmDevCapabilities.canEndBulkInOnTermChar);
TU_ASSERT(termCharRequested);
TU_ASSERT(((uint8_t*)data)[len-1u] == termChar);
TU_ASSERT(((uint8_t const*)data)[len-1u] == termChar);
}
#endif
@@ -228,7 +221,7 @@ bool tud_usbtmc_transmit_dev_msg_data(
memcpy((uint8_t*)(usbtmc_state.ep_bulk_in_buf) + headerLen, data, dataLen);
usbtmc_state.transfer_size_remaining = len - dataLen;
usbtmc_state.transfer_size_sent = dataLen;
usbtmc_state.devInBuffer = (uint8_t*)data + (dataLen);
usbtmc_state.devInBuffer = (uint8_t const*) data + (dataLen);
bool stateChanged =
atomicChangeState(STATE_TX_REQUESTED, (packetLen >= txBufLen) ? STATE_TX_INITIATED : STATE_TX_SHORTED);
@@ -287,7 +280,7 @@ uint16_t usbtmcd_open_cb(uint8_t rhport, tusb_desc_interface_t const * itf_desc,
tusb_desc_endpoint_t const *ep_desc = (tusb_desc_endpoint_t const *)p_desc;
switch(ep_desc->bmAttributes.xfer) {
case TUSB_XFER_BULK:
TU_ASSERT(ep_desc->wMaxPacketSize.size == USBTMCD_MAX_PACKET_SIZE, 0);
TU_ASSERT(tu_edpt_packet_size(ep_desc) == USBTMCD_MAX_PACKET_SIZE, 0);
if (tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN)
{
usbtmc_state.ep_bulk_in = ep_desc->bEndpointAddress;
@@ -508,13 +501,13 @@ bool usbtmcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint
case STATE_ABORTING_BULK_OUT:
TU_VERIFY(false);
return false; // Should be stalled by now, shouldn't have received a packet.
case STATE_TX_REQUESTED:
case STATE_TX_INITIATED:
case STATE_ABORTING_BULK_IN:
case STATE_ABORTING_BULK_IN_SHORTED:
case STATE_ABORTING_BULK_IN_ABORTED:
default:
TU_VERIFY(false);
}
}
@@ -528,37 +521,40 @@ bool usbtmcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint
case STATE_TX_INITIATED:
if(usbtmc_state.transfer_size_remaining >=sizeof(usbtmc_state.ep_bulk_in_buf))
{
{
// FIXME! This removes const below!
TU_VERIFY( usbd_edpt_xfer(rhport, usbtmc_state.ep_bulk_in,
(void*)usbtmc_state.devInBuffer,sizeof(usbtmc_state.ep_bulk_in_buf)));
(void*)(uintptr_t) usbtmc_state.devInBuffer, sizeof(usbtmc_state.ep_bulk_in_buf)));
usbtmc_state.devInBuffer += sizeof(usbtmc_state.ep_bulk_in_buf);
usbtmc_state.transfer_size_remaining -= sizeof(usbtmc_state.ep_bulk_in_buf);
usbtmc_state.transfer_size_sent += sizeof(usbtmc_state.ep_bulk_in_buf);
}
else // last packet
{
size_t packetLen = usbtmc_state.transfer_size_remaining;
memcpy(usbtmc_state.ep_bulk_in_buf, usbtmc_state.devInBuffer, usbtmc_state.transfer_size_remaining);
usbtmc_state.transfer_size_sent += sizeof(usbtmc_state.transfer_size_remaining);
usbtmc_state.transfer_size_remaining = 0;
usbtmc_state.devInBuffer = NULL;
TU_VERIFY( usbd_edpt_xfer(rhport, usbtmc_state.ep_bulk_in, usbtmc_state.ep_bulk_in_buf,(uint16_t)packetLen));
}
else // last packet
{
size_t packetLen = usbtmc_state.transfer_size_remaining;
memcpy(usbtmc_state.ep_bulk_in_buf, usbtmc_state.devInBuffer, usbtmc_state.transfer_size_remaining);
usbtmc_state.transfer_size_sent += sizeof(usbtmc_state.transfer_size_remaining);
usbtmc_state.transfer_size_remaining = 0;
usbtmc_state.devInBuffer = NULL;
TU_VERIFY( usbd_edpt_xfer(rhport, usbtmc_state.ep_bulk_in, usbtmc_state.ep_bulk_in_buf, (uint16_t)packetLen) );
if(((packetLen % USBTMCD_MAX_PACKET_SIZE) != 0) || (packetLen == 0 ))
{
usbtmc_state.state = STATE_TX_SHORTED;
}
}
return true;
case STATE_ABORTING_BULK_IN:
// need to send short packet (ZLP?)
TU_VERIFY( usbd_edpt_xfer(rhport, usbtmc_state.ep_bulk_in, usbtmc_state.ep_bulk_in_buf,(uint16_t)0u));
usbtmc_state.state = STATE_ABORTING_BULK_IN_SHORTED;
return true;
case STATE_ABORTING_BULK_IN_SHORTED:
/* Done. :)*/
usbtmc_state.state = STATE_ABORTING_BULK_IN_ABORTED;
return true;
return true;
default:
TU_ASSERT(false);
return false;
@@ -787,7 +783,7 @@ bool usbtmcd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request
{
TU_VERIFY(request->bmRequestType == 0xA1); // in,class,interface
TU_VERIFY(request->wLength == sizeof(*(usbtmc_state.capabilities)));
TU_VERIFY(tud_control_xfer(rhport, request, (void*)usbtmc_state.capabilities, sizeof(*usbtmc_state.capabilities)));
TU_VERIFY(tud_control_xfer(rhport, request, (void*)(uintptr_t) usbtmc_state.capabilities, sizeof(*usbtmc_state.capabilities)));
return true;
}
// USBTMC Optional Requests
-6
View File
@@ -1,9 +1,3 @@
/*
* usbtmc_device.h
*
* Created on: Sep 10, 2019
* Author: nconrad
*/
/*
* The MIT License (MIT)
*
+25 -16
View File
@@ -175,12 +175,12 @@ void vendord_reset(uint8_t rhport)
}
}
uint16_t vendord_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len)
uint16_t vendord_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint16_t max_len)
{
TU_VERIFY(TUSB_CLASS_VENDOR_SPECIFIC == itf_desc->bInterfaceClass, 0);
TU_VERIFY(TUSB_CLASS_VENDOR_SPECIFIC == desc_itf->bInterfaceClass, 0);
uint16_t const drv_len = sizeof(tusb_desc_interface_t) + itf_desc->bNumEndpoints*sizeof(tusb_desc_endpoint_t);
TU_VERIFY(max_len >= drv_len, 0);
uint8_t const * p_desc = tu_desc_next(desc_itf);
uint8_t const * desc_end = p_desc + max_len;
// Find available interface
vendord_interface_t* p_vendor = NULL;
@@ -194,21 +194,30 @@ uint16_t vendord_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, ui
}
TU_VERIFY(p_vendor, 0);
// Open endpoint pair with usbd helper
TU_ASSERT(usbd_open_edpt_pair(rhport, tu_desc_next(itf_desc), 2, TUSB_XFER_BULK, &p_vendor->ep_out, &p_vendor->ep_in), 0);
p_vendor->itf_num = itf_desc->bInterfaceNumber;
// Prepare for incoming data
if ( !usbd_edpt_xfer(rhport, p_vendor->ep_out, p_vendor->epout_buf, sizeof(p_vendor->epout_buf)) )
p_vendor->itf_num = desc_itf->bInterfaceNumber;
if (desc_itf->bNumEndpoints)
{
TU_LOG_FAILED();
TU_BREAKPOINT();
// skip non-endpoint descriptors
while ( (TUSB_DESC_ENDPOINT != tu_desc_type(p_desc)) && (p_desc < desc_end) )
{
p_desc = tu_desc_next(p_desc);
}
// Open endpoint pair with usbd helper
TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, desc_itf->bNumEndpoints, TUSB_XFER_BULK, &p_vendor->ep_out, &p_vendor->ep_in), 0);
p_desc += desc_itf->bNumEndpoints*sizeof(tusb_desc_endpoint_t);
// Prepare for incoming data
if ( p_vendor->ep_out )
{
TU_ASSERT(usbd_edpt_xfer(rhport, p_vendor->ep_out, p_vendor->epout_buf, sizeof(p_vendor->epout_buf)), 0);
}
if ( p_vendor->ep_in ) maybe_transmit(p_vendor);
}
maybe_transmit(p_vendor);
return drv_len;
return (uintptr_t) p_desc - (uintptr_t) desc_itf;
}
bool vendord_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
+4 -4
View File
@@ -44,7 +44,7 @@ bool tud_vendor_n_mounted (uint8_t itf);
uint32_t tud_vendor_n_available (uint8_t itf);
uint32_t tud_vendor_n_read (uint8_t itf, void* buffer, uint32_t bufsize);
bool tud_vendor_n_peek (uint8_t itf, uint8_t* u8);
bool tud_vendor_n_peek (uint8_t itf, uint8_t* ui8);
void tud_vendor_n_read_flush (uint8_t itf);
uint32_t tud_vendor_n_write (uint8_t itf, void const* buffer, uint32_t bufsize);
@@ -59,7 +59,7 @@ uint32_t tud_vendor_n_write_str (uint8_t itf, char const* str);
static inline bool tud_vendor_mounted (void);
static inline uint32_t tud_vendor_available (void);
static inline uint32_t tud_vendor_read (void* buffer, uint32_t bufsize);
static inline bool tud_vendor_peek (uint8_t* u8);
static inline bool tud_vendor_peek (uint8_t* ui8);
static inline void tud_vendor_read_flush (void);
static inline uint32_t tud_vendor_write (void const* buffer, uint32_t bufsize);
static inline uint32_t tud_vendor_write_str (char const* str);
@@ -96,9 +96,9 @@ static inline uint32_t tud_vendor_read (void* buffer, uint32_t bufsize)
return tud_vendor_n_read(0, buffer, bufsize);
}
static inline bool tud_vendor_peek (uint8_t* u8)
static inline bool tud_vendor_peek (uint8_t* ui8)
{
return tud_vendor_n_peek(0, u8);
return tud_vendor_n_peek(0, ui8);
}
static inline void tud_vendor_read_flush(void)
+480
View File
@@ -0,0 +1,480 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Koji KITAYAMA
*
* 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_VIDEO_H_
#define TUSB_VIDEO_H_
#include "common/tusb_common.h"
// Table 3-19 Color Matching Descriptor
typedef enum {
VIDEO_COLOR_PRIMARIES_UNDEFINED = 0x00,
VIDEO_COLOR_PRIMARIES_BT709, // sRGB (default)
VIDEO_COLOR_PRIMARIES_BT470_2M,
VIDEO_COLOR_PRIMARIES_BT470_2BG,
VIDEO_COLOR_PRIMARIES_SMPTE170M,
VIDEO_COLOR_PRIMARIES_SMPTE240M,
} video_color_primaries_t;
// Table 3-19 Color Matching Descriptor
typedef enum {
VIDEO_COLOR_XFER_CH_UNDEFINED = 0x00,
VIDEO_COLOR_XFER_CH_BT709, // default
VIDEO_COLOR_XFER_CH_BT470_2M,
VIDEO_COLOR_XFER_CH_BT470_2BG,
VIDEO_COLOR_XFER_CH_SMPTE170M,
VIDEO_COLOR_XFER_CH_SMPTE240M,
VIDEO_COLOR_XFER_CH_LINEAR,
VIDEO_COLOR_XFER_CH_SRGB,
} video_color_transfer_characteristics_t;
// Table 3-19 Color Matching Descriptor
typedef enum {
VIDEO_COLOR_COEF_UNDEFINED = 0x00,
VIDEO_COLOR_COEF_BT709,
VIDEO_COLOR_COEF_FCC,
VIDEO_COLOR_COEF_BT470_2BG,
VIDEO_COLOR_COEF_SMPTE170M, // BT.601 default
VIDEO_COLOR_COEF_SMPTE240M,
} video_color_matrix_coefficients_t;
/* 4.2.1.2 Request Error Code Control */
typedef enum {
VIDEO_ERROR_NONE = 0, /* The request succeeded. */
VIDEO_ERROR_NOT_READY,
VIDEO_ERROR_WRONG_STATE,
VIDEO_ERROR_POWER,
VIDEO_ERROR_OUT_OF_RANGE,
VIDEO_ERROR_INVALID_UNIT,
VIDEO_ERROR_INVALID_CONTROL,
VIDEO_ERROR_INVALID_REQUEST,
VIDEO_ERROR_INVALID_VALUE_WITHIN_RANGE,
VIDEO_ERROR_UNKNOWN = 0xFF,
} video_error_code_t;
/* A.2 Interface Subclass */
typedef enum {
VIDEO_SUBCLASS_UNDEFINED = 0x00,
VIDEO_SUBCLASS_CONTROL,
VIDEO_SUBCLASS_STREAMING,
VIDEO_SUBCLASS_INTERFACE_COLLECTION,
} video_subclass_type_t;
/* A.3 Interface Protocol */
typedef enum {
VIDEO_ITF_PROTOCOL_UNDEFINED = 0x00,
VIDEO_ITF_PROTOCOL_15,
} video_interface_protocol_code_t;
/* A.5 Class-Specific VideoControl Interface Descriptor Subtypes */
typedef enum {
VIDEO_CS_ITF_VC_UNDEFINED = 0x00,
VIDEO_CS_ITF_VC_HEADER,
VIDEO_CS_ITF_VC_INPUT_TERMINAL,
VIDEO_CS_ITF_VC_OUTPUT_TERMINAL,
VIDEO_CS_ITF_VC_SELECTOR_UNIT,
VIDEO_CS_ITF_VC_PROCESSING_UNIT,
VIDEO_CS_ITF_VC_EXTENSION_UNIT,
VIDEO_CS_ITF_VC_ENCODING_UNIT,
VIDEO_CS_ITF_VC_MAX,
} video_cs_vc_interface_subtype_t;
/* A.6 Class-Specific VideoStreaming Interface Descriptor Subtypes */
typedef enum {
VIDEO_CS_ITF_VS_UNDEFINED = 0x00,
VIDEO_CS_ITF_VS_INPUT_HEADER = 0x01,
VIDEO_CS_ITF_VS_OUTPUT_HEADER = 0x02,
VIDEO_CS_ITF_VS_STILL_IMAGE_FRAME = 0x03,
VIDEO_CS_ITF_VS_FORMAT_UNCOMPRESSED = 0x04,
VIDEO_CS_ITF_VS_FRAME_UNCOMPRESSED = 0x05,
VIDEO_CS_ITF_VS_FORMAT_MJPEG = 0x06,
VIDEO_CS_ITF_VS_FRAME_MJPEG = 0x07,
VIDEO_CS_ITF_VS_FORMAT_MPEG2TS = 0x0A,
VIDEO_CS_ITF_VS_FORMAT_DV = 0x0C,
VIDEO_CS_ITF_VS_COLORFORMAT = 0x0D,
VIDEO_CS_ITF_VS_FORMAT_FRAME_BASED = 0x10,
VIDEO_CS_ITF_VS_FRAME_FRAME_BASED = 0x11,
VIDEO_CS_ITF_VS_FORMAT_STREAM_BASED = 0x12,
VIDEO_CS_ITF_VS_FORMAT_H264 = 0x13,
VIDEO_CS_ITF_VS_FRAME_H264 = 0x14,
VIDEO_CS_ITF_VS_FORMAT_H264_SIMULCAST = 0x15,
VIDEO_CS_ITF_VS_FORMAT_VP8 = 0x16,
VIDEO_CS_ITF_VS_FRAME_VP8 = 0x17,
VIDEO_CS_ITF_VS_FORMAT_VP8_SIMULCAST = 0x18,
} video_cs_vs_interface_subtype_t;
/* A.7. Class-Specific Endpoint Descriptor Subtypes */
typedef enum {
VIDEO_CS_EP_UNDEFINED = 0x00,
VIDEO_CS_EP_GENERAL,
VIDEO_CS_EP_ENDPOINT,
VIDEO_CS_EP_INTERRUPT
} video_cs_ep_subtype_t;
/* A.8 Class-Specific Request Codes */
typedef enum {
VIDEO_REQUEST_UNDEFINED = 0x00,
VIDEO_REQUEST_SET_CUR = 0x01,
VIDEO_REQUEST_SET_CUR_ALL = 0x11,
VIDEO_REQUEST_GET_CUR = 0x81,
VIDEO_REQUEST_GET_MIN = 0x82,
VIDEO_REQUEST_GET_MAX = 0x83,
VIDEO_REQUEST_GET_RES = 0x84,
VIDEO_REQUEST_GET_LEN = 0x85,
VIDEO_REQUEST_GET_INFO = 0x86,
VIDEO_REQUEST_GET_DEF = 0x87,
VIDEO_REQUEST_GET_CUR_ALL = 0x91,
VIDEO_REQUEST_GET_MIN_ALL = 0x92,
VIDEO_REQUEST_GET_MAX_ALL = 0x93,
VIDEO_REQUEST_GET_RES_ALL = 0x94,
VIDEO_REQUEST_GET_DEF_ALL = 0x97
} video_control_request_t;
/* A.9.1 VideoControl Interface Control Selectors */
typedef enum {
VIDEO_VC_CTL_UNDEFINED = 0x00,
VIDEO_VC_CTL_VIDEO_POWER_MODE,
VIDEO_VC_CTL_REQUEST_ERROR_CODE,
} video_interface_control_selector_t;
/* A.9.8 VideoStreaming Interface Control Selectors */
typedef enum {
VIDEO_VS_CTL_UNDEFINED = 0x00,
VIDEO_VS_CTL_PROBE,
VIDEO_VS_CTL_COMMIT,
VIDEO_VS_CTL_STILL_PROBE,
VIDEO_VS_CTL_STILL_COMMIT,
VIDEO_VS_CTL_STILL_IMAGE_TRIGGER,
VIDEO_VS_CTL_STREAM_ERROR_CODE,
VIDEO_VS_CTL_GENERATE_KEY_FRAME,
VIDEO_VS_CTL_UPDATE_FRAME_SEGMENT,
VIDEO_VS_CTL_SYNCH_DELAY_CONTROL,
} video_interface_streaming_selector_t;
/* B. Terminal Types */
typedef enum {
// Terminal
VIDEO_TT_VENDOR_SPECIFIC = 0x0100,
VIDEO_TT_STREAMING = 0x0101,
// Input
VIDEO_ITT_VENDOR_SPECIFIC = 0x0200,
VIDEO_ITT_CAMERA = 0x0201,
VIDEO_ITT_MEDIA_TRANSPORT_INPUT = 0x0202,
// Output
VIDEO_OTT_VENDOR_SPECIFIC = 0x0300,
VIDEO_OTT_DISPLAY = 0x0301,
VIDEO_OTT_MEDIA_TRANSPORT_OUTPUT = 0x0302,
// External
VIDEO_ETT_VENDOR_SPEIFIC = 0x0400,
VIDEO_ETT_COMPOSITE_CONNECTOR = 0x0401,
VIDEO_ETT_SVIDEO_CONNECTOR = 0x0402,
VIDEO_ETT_COMPONENT_CONNECTOR = 0x0403,
} video_terminal_type_t;
//--------------------------------------------------------------------+
// Descriptors
//--------------------------------------------------------------------+
/* 2.3.4.2 */
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint16_t bcdUVC;
uint16_t wTotalLength;
uint32_t dwClockFrequency;
uint8_t bInCollection;
uint8_t baInterfaceNr[];
} tusb_desc_cs_video_ctl_itf_hdr_t;
/* 2.4.3.3 */
typedef struct TU_ATTR_PACKED {
uint8_t bHeaderLength;
union {
uint8_t bmHeaderInfo;
struct {
uint8_t FrameID: 1;
uint8_t EndOfFrame: 1;
uint8_t PresentationTime: 1;
uint8_t SourceClockReference: 1;
uint8_t PayloadSpecific: 1;
uint8_t StillImage: 1;
uint8_t Error: 1;
uint8_t EndOfHeader: 1;
};
};
} tusb_video_payload_header_t;
/* 3.9.2.1 */
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bNumFormats;
uint16_t wTotalLength;
uint8_t bEndpointAddress;
uint8_t bmInfo;
uint8_t bTerminalLink;
uint8_t bStillCaptureMethod;
uint8_t bTriggerSupport;
uint8_t bTriggerUsage;
uint8_t bControlSize;
uint8_t bmaControls[];
} tusb_desc_cs_video_stm_itf_in_hdr_t;
/* 3.9.2.2 */
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bNumFormats;
uint16_t wTotalLength;
uint8_t bEndpointAddress;
uint8_t bTerminalLink;
uint8_t bControlSize;
uint8_t bmaControls[];
} tusb_desc_cs_video_stm_itf_out_hdr_t;
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bNumFormats;
uint16_t wTotalLength;
uint8_t bEndpointAddress;
union {
struct {
uint8_t bmInfo;
uint8_t bTerminalLink;
uint8_t bStillCaptureMethod;
uint8_t bTriggerSupport;
uint8_t bTriggerUsage;
uint8_t bControlSize;
uint8_t bmaControls[];
} input;
struct {
uint8_t bEndpointAddress;
uint8_t bTerminalLink;
uint8_t bControlSize;
uint8_t bmaControls[];
} output;
};
} tusb_desc_cs_video_stm_itf_hdr_t;
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFormatIndex;
uint8_t bNumFrameDescriptors;
uint8_t guidFormat[16];
uint8_t bBitsPerPixel;
uint8_t bDefaultFrameIndex;
uint8_t bAspectRatioX;
uint8_t bAspectRatioY;
uint8_t bmInterlaceFlags;
uint8_t bCopyProtect;
} tusb_desc_cs_video_fmt_uncompressed_t;
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFrameIndex;
uint8_t bmCapabilities;
uint16_t wWidth;
uint16_t wHeight;
uint32_t dwMinBitRate;
uint32_t dwMaxBitRate;
uint32_t dwMaxVideoFrameBufferSize; /* deprecated */
uint32_t dwDefaultFrameInterval;
uint8_t bFrameIntervalType;
uint32_t dwFrameInterval[];
} tusb_desc_cs_video_frm_uncompressed_t;
//--------------------------------------------------------------------+
// Requests
//--------------------------------------------------------------------+
/* 4.3.1.1 */
typedef struct TU_ATTR_PACKED {
union {
uint8_t bmHint;
struct TU_ATTR_PACKED {
uint16_t dwFrameInterval: 1;
uint16_t wKeyFrameRatel : 1;
uint16_t wPFrameRate : 1;
uint16_t wCompQuality : 1;
uint16_t wCompWindowSize: 1;
uint16_t : 0;
} Hint;
};
uint8_t bFormatIndex;
uint8_t bFrameIndex;
uint32_t dwFrameInterval;
uint16_t wKeyFrameRate;
uint16_t wPFrameRate;
uint16_t wCompQuality;
uint16_t wCompWindowSize;
uint16_t wDelay;
uint32_t dwMaxVideoFrameSize;
uint32_t dwMaxPayloadTransferSize;
uint32_t dwClockFrequency;
union {
uint8_t bmFramingInfo;
struct TU_ATTR_PACKED {
uint8_t FrameID : 1;
uint8_t EndOfFrame: 1;
uint8_t EndOfSlice: 1;
uint8_t : 0;
} FramingInfo;
};
uint8_t bPreferedVersion;
uint8_t bMinVersion;
uint8_t bMaxVersion;
uint8_t bUsage;
uint8_t bBitDepthLuma;
uint8_t bmSettings;
uint8_t bMaxNumberOfRefFramesPlus1;
uint16_t bmRateControlModes;
uint64_t bmLayoutPerStream;
} video_probe_and_commit_control_t;
TU_VERIFY_STATIC( sizeof(video_probe_and_commit_control_t) == 48, "size is not correct");
#define TUD_VIDEO_DESC_IAD_LEN 8
#define TUD_VIDEO_DESC_STD_VC_LEN 9
#define TUD_VIDEO_DESC_CS_VC_LEN 12
#define TUD_VIDEO_DESC_INPUT_TERM_LEN 8
#define TUD_VIDEO_DESC_OUTPUT_TERM_LEN 9
#define TUD_VIDEO_DESC_CAMERA_TERM_LEN 18
#define TUD_VIDEO_DESC_STD_VS_LEN 9
#define TUD_VIDEO_DESC_CS_VS_IN_LEN 13
#define TUD_VIDEO_DESC_CS_VS_OUT_LEN 9
#define TUD_VIDEO_DESC_CS_VS_FMT_UNCOMPR_LEN 27
#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_CONT_LEN 38
#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_DISC_LEN 26
#define TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING_LEN 6
/* 2.2 compression formats */
#define TUD_VIDEO_GUID_YUY2 0x59,0x55,0x59,0x32,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_GUID_NV12 0x4E,0x56,0x31,0x32,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_GUID_M420 0x4D,0x34,0x32,0x30,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_GUID_I420 0x49,0x34,0x32,0x30,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_DESC_IAD(_firstitfs, _nitfs, _stridx) \
TUD_VIDEO_DESC_IAD_LEN, TUSB_DESC_INTERFACE_ASSOCIATION, \
_firstitfs, _nitfs, TUSB_CLASS_VIDEO, VIDEO_SUBCLASS_INTERFACE_COLLECTION, \
VIDEO_ITF_PROTOCOL_UNDEFINED, _stridx
#define TUD_VIDEO_DESC_STD_VC(_itfnum, _nEPs, _stridx) \
TUD_VIDEO_DESC_STD_VC_LEN, TUSB_DESC_INTERFACE, _itfnum, /* fixed to zero */ 0x00, \
_nEPs, TUSB_CLASS_VIDEO, VIDEO_SUBCLASS_CONTROL, VIDEO_ITF_PROTOCOL_15, _stridx
/* 3.7.2 */
#define TUD_VIDEO_DESC_CS_VC(_bcdUVC, _totallen, _clkfreq, ...) \
TUD_VIDEO_DESC_CS_VC_LEN + (TU_ARGS_NUM(__VA_ARGS__)), TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VC_HEADER, \
U16_TO_U8S_LE(_bcdUVC), U16_TO_U8S_LE((_totallen) + TUD_VIDEO_DESC_CS_VC_LEN + (TU_ARGS_NUM(__VA_ARGS__))), \
U32_TO_U8S_LE(_clkfreq), TU_ARGS_NUM(__VA_ARGS__), __VA_ARGS__
/* 3.7.2.1 */
#define TUD_VIDEO_DESC_INPUT_TERM(_tid, _tt, _at, _stridx) \
TUD_VIDEO_DESC_INPUT_TERM_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VC_INPUT_TERMINAL, \
_tid, U16_TO_U8S_LE(_tt), _at, _stridx
/* 3.7.2.2 */
#define TUD_VIDEO_DESC_OUTPUT_TERM(_tid, _tt, _at, _srcid, _stridx) \
TUD_VIDEO_DESC_OUTPUT_TERM_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VC_OUTPUT_TERMINAL, \
_tid, U16_TO_U8S_LE(_tt), _at, _srcid, _stridx
/* 3.7.2.3 */
#define TUD_VIDEO_DESC_CAMERA_TERM(_tid, _at, _stridx, _focal_min, _focal_max, _focal, _ctls) \
TUD_VIDEO_DESC_CAMERA_TERM_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VC_INPUT_TERMINAL, \
_tid, U16_TO_U8S_LE(VIDEO_ITT_CAMERA), _at, _stridx, \
U16_TO_U8S_LE(_focal_min), U16_TO_U8S_LE(_focal_max), U16_TO_U8S_LE(_focal), 3, \
TU_U32_BYTE0(_ctls), TU_U32_BYTE1(_ctls), TU_U32_BYTE2(_ctls)
/* 3.9.1 */
#define TUD_VIDEO_DESC_STD_VS(_itfnum, _alt, _epn, _stridx) \
TUD_VIDEO_DESC_STD_VS_LEN, TUSB_DESC_INTERFACE, _itfnum, _alt, \
_epn, TUSB_CLASS_VIDEO, VIDEO_SUBCLASS_STREAMING, VIDEO_ITF_PROTOCOL_15, _stridx
/* 3.9.2.1 */
#define TUD_VIDEO_DESC_CS_VS_INPUT(_numfmt, _totallen, _ep, _inf, _termlnk, _sticaptmeth, _trgspt, _trgusg, ...) \
TUD_VIDEO_DESC_CS_VS_IN_LEN + (_numfmt) * (TU_ARGS_NUM(__VA_ARGS__)), TUSB_DESC_CS_INTERFACE, \
VIDEO_CS_ITF_VS_INPUT_HEADER, _numfmt, \
U16_TO_U8S_LE((_totallen) + TUD_VIDEO_DESC_CS_VS_IN_LEN + (_numfmt) * (TU_ARGS_NUM(__VA_ARGS__))), \
_ep, _inf, _termlnk, _sticaptmeth, _trgspt, _trgusg, (TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__
/* 3.9.2.2 */
#define TUD_VIDEO_DESC_CS_VS_OUTPUT(_numfmt, _totallen, _ep, _inf, _termlnk, ...) \
TUD_VIDEO_DESC_CS_VS_OUT_LEN + (_numfmt) * (TU_ARGS_NUM(__VA_ARGS__)), TUSB_DESC_CS_INTERFACE, \
VIDEO_CS_ITF_VS_OUTPUT_HEADER, _numfmt, \
U16_TO_U8S_LE((_totallen) + TUD_VIDEO_DESC_CS_VS_OUT_LEN + (_numfmt) * (TU_ARGS_NUM(__VA_ARGS__))), \
_ep, _inf, _termlnk, (TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__
/* Uncompressed 3.1.1 */
#define TUD_VIDEO_GUID(_g0,_g1,_g2,_g3,_g4,_g5,_g6,_g7,_g8,_g9,_g10,_g11,_g12,_g13,_g14,_g15) _g0,_g1,_g2,_g3,_g4,_g5,_g6,_g7,_g8,_g9,_g10,_g11,_g12,_g13,_g14,_g15
#define TUD_VIDEO_DESC_CS_VS_FMT_UNCOMPR(_fmtidx, _numfrmdesc, \
_guid, _bitsperpix, _frmidx, _asrx, _asry, _interlace, _cp) \
TUD_VIDEO_DESC_CS_VS_FMT_UNCOMPR_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FORMAT_UNCOMPRESSED, \
_fmtidx, _numfrmdesc, TUD_VIDEO_GUID(_guid), \
_bitsperpix, _frmidx, _asrx, _asry, _interlace, _cp
/* Uncompressed 3.1.2 Table 3-3 */
#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_CONT(_frmidx, _cap, _width, _height, _minbr, _maxbr, _maxfrmbufsz, _frminterval, _minfrminterval, _maxfrminterval, _frmintervalstep) \
TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_CONT_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_UNCOMPRESSED, \
_frmidx, _cap, U16_TO_U8S_LE(_width), U16_TO_U8S_LE(_height), U32_TO_U8S_LE(_minbr), U32_TO_U8S_LE(_maxbr), \
U32_TO_U8S_LE(_maxfrmbufsz), U32_TO_U8S_LE(_frminterval), 0, \
U32_TO_U8S_LE(_minfrminterval), U32_TO_U8S_LE(_maxfrminterval), U32_TO_U8S_LE(_frmintervalstep)
/* Uncompressed 3.1.2 Table 3-4 */
#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_DISC(_frmidx, _cap, _width, _height, _minbr, _maxbr, _maxfrmbufsz, _frminterval, ...) \
TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_DISC_LEN + (TU_ARGS_NUM(__VA_ARGS__)) * 4, \
TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_UNCOMPRESSED, \
_frmidx, _cap, U16_TO_U8S_LE(_width), U16_TO_U8S_LE(_height), U32_TO_U8S_LE(_minbr), U32_TO_U8S_LE(_maxbr), \
U32_TO_U8S_LE(_maxfrmbufsz), U32_TO_U8S_LE(_frminterval), (TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__
/* 3.9.2.6 */
#define TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING(_color, _trns, _mat) \
TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING_LEN, \
TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_COLORFORMAT, \
_color, _trns, _mat
/* 3.10.1.1 */
#define TUD_VIDEO_DESC_EP_ISO(_ep, _epsize, _ep_interval) \
7, TUSB_DESC_ENDPOINT, _ep, TUSB_XFER_ISOCHRONOUS | TUSB_ISO_EP_ATT_ASYNCHRONOUS,\
U16_TO_U8S_LE(_epsize), _ep_interval
/* 3.10.1.2 */
#define TUD_VIDEO_DESC_EP_BULK(_ep, _epsize, _ep_interval) \
7, TUSB_DESC_ENDPOINT, _ep, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), _ep_interval
#endif
File diff suppressed because it is too large Load Diff
+97
View File
@@ -0,0 +1,97 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
* Copyright (c) 2021 Koji KITAYAMA
*
* 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_VIDEO_DEVICE_H_
#define TUSB_VIDEO_DEVICE_H_
#include "common/tusb_common.h"
#include "video.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application API (Multiple Ports)
// CFG_TUD_VIDEO > 1
//--------------------------------------------------------------------+
/** Return true if streaming
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index */
bool tud_video_n_streaming(uint_fast8_t ctl_idx, uint_fast8_t stm_idx);
/** Transfer a frame
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index
* @param[in] buffer Frame buffer. The caller must not use this buffer until the operation is completed.
* @param[in] bufsize Byte size of the frame buffer */
bool tud_video_n_frame_xfer(uint_fast8_t ctl_idx, uint_fast8_t stm_idx, void *buffer, size_t bufsize);
/*------------- Optional callbacks -------------*/
/** Invoked when compeletion of a frame transfer
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index */
TU_ATTR_WEAK void tud_video_frame_xfer_complete_cb(uint_fast8_t ctl_idx, uint_fast8_t stm_idx);
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
/** Invoked when SET_POWER_MODE request received
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index
* @return video_error_code_t */
TU_ATTR_WEAK int tud_video_power_mode_cb(uint_fast8_t ctl_idx, uint8_t power_mod);
/** Invoked when VS_COMMIT_CONTROL(SET_CUR) request received
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index
* @param[in] parameters Video streaming parameters
* @return video_error_code_t */
TU_ATTR_WEAK int tud_video_commit_cb(uint_fast8_t ctl_idx, uint_fast8_t stm_idx,
video_probe_and_commit_control_t const *parameters);
//--------------------------------------------------------------------+
// INTERNAL USBD-CLASS DRIVER API
//--------------------------------------------------------------------+
void videod_init (void);
void videod_reset (uint8_t rhport);
uint16_t videod_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool videod_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
bool videod_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif
+30 -53
View File
@@ -38,20 +38,21 @@
#define TU_MIN(_x, _y) ( ( (_x) < (_y) ) ? (_x) : (_y) )
#define TU_MAX(_x, _y) ( ( (_x) > (_y) ) ? (_x) : (_y) )
#define TU_U16_HIGH(u16) ((uint8_t) (((u16) >> 8) & 0x00ff))
#define TU_U16_LOW(u16) ((uint8_t) ((u16) & 0x00ff))
#define U16_TO_U8S_BE(u16) TU_U16_HIGH(u16), TU_U16_LOW(u16)
#define U16_TO_U8S_LE(u16) TU_U16_LOW(u16), TU_U16_HIGH(u16)
#define TU_U16_HIGH(_u16) ((uint8_t) (((_u16) >> 8) & 0x00ff))
#define TU_U16_LOW(_u16) ((uint8_t) ((_u16) & 0x00ff))
#define U16_TO_U8S_BE(_u16) TU_U16_HIGH(_u16), TU_U16_LOW(_u16)
#define U16_TO_U8S_LE(_u16) TU_U16_LOW(_u16), TU_U16_HIGH(_u16)
#define TU_U32_BYTE3(u32) ((uint8_t) ((((uint32_t) u32) >> 24) & 0x000000ff)) // MSB
#define TU_U32_BYTE2(u32) ((uint8_t) ((((uint32_t) u32) >> 16) & 0x000000ff))
#define TU_U32_BYTE1(u32) ((uint8_t) ((((uint32_t) u32) >> 8) & 0x000000ff))
#define TU_U32_BYTE0(u32) ((uint8_t) (((uint32_t) u32) & 0x000000ff)) // LSB
#define TU_U32_BYTE3(_u32) ((uint8_t) ((((uint32_t) _u32) >> 24) & 0x000000ff)) // MSB
#define TU_U32_BYTE2(_u32) ((uint8_t) ((((uint32_t) _u32) >> 16) & 0x000000ff))
#define TU_U32_BYTE1(_u32) ((uint8_t) ((((uint32_t) _u32) >> 8) & 0x000000ff))
#define TU_U32_BYTE0(_u32) ((uint8_t) (((uint32_t) _u32) & 0x000000ff)) // LSB
#define U32_TO_U8S_BE(u32) TU_U32_BYTE3(u32), TU_U32_BYTE2(u32), TU_U32_BYTE1(u32), TU_U32_BYTE0(u32)
#define U32_TO_U8S_LE(u32) TU_U32_BYTE0(u32), TU_U32_BYTE1(u32), TU_U32_BYTE2(u32), TU_U32_BYTE3(u32)
#define U32_TO_U8S_BE(_u32) TU_U32_BYTE3(_u32), TU_U32_BYTE2(_u32), TU_U32_BYTE1(_u32), TU_U32_BYTE0(_u32)
#define U32_TO_U8S_LE(_u32) TU_U32_BYTE0(_u32), TU_U32_BYTE1(_u32), TU_U32_BYTE2(_u32), TU_U32_BYTE3(_u32)
#define TU_BIT(n) (1UL << (n))
#define TU_GENMASK(h, l) ( (UINT32_MAX << (l)) & (UINT32_MAX >> (31 - (h))) )
//--------------------------------------------------------------------+
// Includes
@@ -105,13 +106,16 @@ TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_u16(uint8_t high, uint8_t low)
return (uint16_t) ((((uint16_t) high) << 8) | low);
}
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte3(uint32_t u32) { return TU_U32_BYTE3(u32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte2(uint32_t u32) { return TU_U32_BYTE2(u32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte1(uint32_t u32) { return TU_U32_BYTE1(u32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte0(uint32_t u32) { return TU_U32_BYTE0(u32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte3(uint32_t ui32) { return TU_U32_BYTE3(ui32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte2(uint32_t ui32) { return TU_U32_BYTE2(ui32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte1(uint32_t ui32) { return TU_U32_BYTE1(ui32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte0(uint32_t ui32) { return TU_U32_BYTE0(ui32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u16_high(uint16_t u16) { return TU_U16_HIGH(u16); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u16_low (uint16_t u16) { return TU_U16_LOW(u16); }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_u32_high16(uint32_t ui32) { return (uint16_t) (ui32 >> 16); }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_u32_low16 (uint32_t ui32) { return (uint16_t) (ui32 & 0x0000ffffu); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u16_high(uint16_t ui16) { return TU_U16_HIGH(ui16); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u16_low (uint16_t ui16) { return TU_U16_LOW(ui16); }
//------------- Bits -------------//
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_bit_set (uint32_t value, uint8_t pos) { return value | TU_BIT(pos); }
@@ -161,7 +165,6 @@ static inline uint8_t tu_log2(uint32_t value)
#if TUP_ARCH_STRICT_ALIGN
// Rely on compiler to generate correct code for unaligned access
typedef struct { uint16_t val; } TU_ATTR_PACKED tu_unaligned_uint16_t;
typedef struct { uint32_t val; } TU_ATTR_PACKED tu_unaligned_uint32_t;
@@ -227,45 +230,14 @@ TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write16(void* mem, uint16_
#else
// MCU that could access unaligned memory natively
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_unaligned_read32 (const void* mem ) { return *((uint32_t*) mem); }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_unaligned_read16 (const void* mem ) { return *((uint16_t*) mem); }
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_unaligned_read32 (const void* mem) { return *((uint32_t const *) mem); }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_unaligned_read16 (const void* mem) { return *((uint16_t const *) mem); }
TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write32 (void* mem, uint32_t value ) { *((uint32_t*) mem) = value; }
TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write16 (void* mem, uint16_t value ) { *((uint16_t*) mem) = value; }
#endif
/*------------------------------------------------------------------*/
/* Count number of arguments of __VA_ARGS__
* - reference https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s
* - _GET_NTH_ARG() takes args >= N (64) but only expand to Nth one (64th)
* - _RSEQ_N() is reverse sequential to N to add padding to have
* Nth position is the same as the number of arguments
* - ##__VA_ARGS__ is used to deal with 0 paramerter (swallows comma)
*------------------------------------------------------------------*/
#ifndef TU_ARGS_NUM
#define TU_ARGS_NUM(...) _TU_NARG(_0, ##__VA_ARGS__,_RSEQ_N())
#define _TU_NARG(...) _GET_NTH_ARG(__VA_ARGS__)
#define _GET_NTH_ARG( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define _RSEQ_N() \
62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
#endif
// To be removed
//------------- Binary constant -------------//
#if defined(__GNUC__) && !defined(__CC_ARM)
@@ -334,8 +306,8 @@ void tu_print_var(uint8_t const* buf, uint32_t bufsize)
#define TU_LOG1 tu_printf
#define TU_LOG1_MEM tu_print_mem
#define TU_LOG1_VAR(_x) tu_print_var((uint8_t const*)(_x), sizeof(*(_x)))
#define TU_LOG1_INT(_x) tu_printf(#_x " = %ld\r\n", (uint32_t) (_x) )
#define TU_LOG1_HEX(_x) tu_printf(#_x " = %lX\r\n", (uint32_t) (_x) )
#define TU_LOG1_INT(_x) tu_printf(#_x " = %ld\r\n", (unsigned long) (_x) )
#define TU_LOG1_HEX(_x) tu_printf(#_x " = %lX\r\n", (unsigned long) (_x) )
// Log Level 2: Warn
#if CFG_TUSB_DEBUG >= 2
@@ -369,12 +341,17 @@ typedef struct
static inline const char* tu_lookup_find(tu_lookup_table_t const* p_table, uint32_t key)
{
static char not_found[11];
for(uint16_t i=0; i<p_table->count; i++)
{
if (p_table->items[i].key == key) return p_table->items[i].data;
}
return NULL;
// not found return the key value in hex
sprintf(not_found, "0x%08lX", (unsigned long) key);
return not_found;
}
#endif // CFG_TUSB_DEBUG
+43
View File
@@ -32,6 +32,7 @@
#ifndef _TUSB_COMPILER_H_
#define _TUSB_COMPILER_H_
#define TU_TOKEN(x) x
#define TU_STRING(x) #x ///< stringify without expand
#define TU_XSTRING(x) TU_STRING(x) ///< expand then stringify
@@ -41,6 +42,8 @@
#define TU_XSTRCAT(a, b) TU_STRCAT(a, b) ///< expand then concat
#define TU_XSTRCAT3(a, b, c) TU_STRCAT3(a, b, c) ///< expand then concat 3 tokens
#define TU_INCLUDE_PATH(_dir,_file) TU_XSTRING( TU_TOKEN(_dir)TU_TOKEN(_file) )
#if defined __COUNTER__ && __COUNTER__ != __COUNTER__
#define _TU_COUNTER_ __COUNTER__
#else
@@ -64,6 +67,46 @@
#define TU_LITTLE_ENDIAN (0x12u)
#define TU_BIG_ENDIAN (0x21u)
/*------------------------------------------------------------------*/
/* Count number of arguments of __VA_ARGS__
* - reference https://stackoverflow.com/questions/2124339/c-preprocessor-va-args-number-of-arguments
* - _GET_NTH_ARG() takes args >= N (64) but only expand to Nth one (64th)
* - _RSEQ_N() is reverse sequential to N to add padding to have
* Nth position is the same as the number of arguments
* - ##__VA_ARGS__ is used to deal with 0 paramerter (swallows comma)
*------------------------------------------------------------------*/
#define TU_ARGS_NUM(...) _TU_NARG(_0, ##__VA_ARGS__,_RSEQ_N())
#define _TU_NARG(...) _GET_NTH_ARG(__VA_ARGS__)
#define _GET_NTH_ARG( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define _RSEQ_N() \
62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
// Apply an macro X to each of the arguments with an separated of choice
#define TU_ARGS_APPLY(_X, _s, ...) TU_XSTRCAT(_TU_ARGS_APPLY_, TU_ARGS_NUM(__VA_ARGS__))(_X, _s, __VA_ARGS__)
#define _TU_ARGS_APPLY_1(_X, _s, _a1) _X(_a1)
#define _TU_ARGS_APPLY_2(_X, _s, _a1, _a2) _X(_a1) _s _X(_a2)
#define _TU_ARGS_APPLY_3(_X, _s, _a1, _a2, _a3) _X(_a1) _s _TU_ARGS_APPLY_2(_X, _s, _a2, _a3)
#define _TU_ARGS_APPLY_4(_X, _s, _a1, _a2, _a3, _a4) _X(_a1) _s _TU_ARGS_APPLY_3(_X, _s, _a2, _a3, _a4)
#define _TU_ARGS_APPLY_5(_X, _s, _a1, _a2, _a3, _a4, _a5) _X(_a1) _s _TU_ARGS_APPLY_4(_X, _s, _a2, _a3, _a4, _a5)
#define _TU_ARGS_APPLY_6(_X, _s, _a1, _a2, _a3, _a4, _a5, _a6) _X(_a1) _s _TU_ARGS_APPLY_5(_X, _s, _a2, _a3, _a4, _a5, _a6)
#define _TU_ARGS_APPLY_7(_X, _s, _a1, _a2, _a3, _a4, _a5, _a6, _a7) _X(_a1) _s _TU_ARGS_APPLY_6(_X, _s, _a2, _a3, _a4, _a5, _a6, _a7)
#define _TU_ARGS_APPLY_8(_X, _s, _a1, _a2, _a3, _a4, _a5, _a6, _a7, _a8) _X(_a1) _s _TU_ARGS_APPLY_7(_X, _s, _a2, _a3, _a4, _a5, _a6, _a7, _a8)
//--------------------------------------------------------------------+
// Compiler porting with Attribute and Endian
//--------------------------------------------------------------------+
+2 -2
View File
@@ -102,7 +102,7 @@ static inline uint16_t _ff_mod(uint16_t idx, uint16_t depth)
// TODO generalize with configurable 1 byte or 4 byte each read
static void _ff_push_const_addr(uint8_t * ff_buf, const void * app_buf, uint16_t len)
{
volatile uint32_t * rx_fifo = (volatile uint32_t *) app_buf;
volatile const uint32_t * rx_fifo = (volatile const uint32_t *) app_buf;
// Reading full available 32 bit words from const app address
uint16_t full_words = len >> 2;
@@ -201,7 +201,7 @@ static void _ff_push_n(tu_fifo_t* f, void const * app_buf, uint16_t n, uint16_t
ff_buf += nLin_4n_bytes;
// There could be odd 1-3 bytes before the wrap-around boundary
volatile uint32_t * rx_fifo = (volatile uint32_t *) app_buf;
volatile const uint32_t * rx_fifo = (volatile const uint32_t *) app_buf;
uint8_t rem = nLin_bytes & 0x03;
if (rem > 0)
{
+34 -22
View File
@@ -47,8 +47,8 @@
typedef enum
{
TUSB_SPEED_FULL = 0,
TUSB_SPEED_LOW ,
TUSB_SPEED_HIGH,
TUSB_SPEED_LOW = 1,
TUSB_SPEED_HIGH = 2,
TUSB_SPEED_INVALID = 0xff,
}tusb_speed_t;
@@ -69,6 +69,18 @@ typedef enum
TUSB_DIR_IN_MASK = 0x80
}tusb_dir_t;
/// Isochronous End Point Attributes
typedef enum
{
TUSB_ISO_EP_ATT_NO_SYNC = 0x00,
TUSB_ISO_EP_ATT_ASYNCHRONOUS = 0x04,
TUSB_ISO_EP_ATT_ADAPTIVE = 0x08,
TUSB_ISO_EP_ATT_SYNCHRONOUS = 0x0C,
TUSB_ISO_EP_ATT_DATA = 0x00, ///< Data End Point
TUSB_ISO_EP_ATT_EXPLICIT_FB = 0x10, ///< Feedback End Point
TUSB_ISO_EP_ATT_IMPLICIT_FB = 0x20, ///< Data endpoint that also serves as an implicit feedback
}tusb_iso_ep_attribute_t;
/// USB Descriptor Types
typedef enum
{
@@ -337,32 +349,24 @@ TU_VERIFY_STATIC( sizeof(tusb_desc_interface_t) == 9, "size is not correct");
/// USB Endpoint Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< ENDPOINT Descriptor Type
uint8_t bLength ; // Size of this descriptor in bytes
uint8_t bDescriptorType ; // ENDPOINT Descriptor Type
uint8_t bEndpointAddress ; ///< The address of the endpoint on the USB device described by this descriptor. The address is encoded as follows: \n Bit 3...0: The endpoint number \n Bit 6...4: Reserved, reset to zero \n Bit 7: Direction, ignored for control endpoints 0 = OUT endpoint 1 = IN endpoint.
uint8_t bEndpointAddress ; // The address of the endpoint
struct TU_ATTR_PACKED {
uint8_t xfer : 2;
uint8_t sync : 2;
uint8_t usage : 2;
uint8_t xfer : 2; // Control, ISO, Bulk, Interrupt
uint8_t sync : 2; // None, Asynchronous, Adaptive, Synchronous
uint8_t usage : 2; // Data, Feedback, Implicit feedback
uint8_t : 2;
} bmAttributes ; ///< This field describes the endpoint's attributes when it is configured using the bConfigurationValue. \n Bits 1..0: Transfer Type \n- 00 = Control \n- 01 = Isochronous \n- 10 = Bulk \n- 11 = Interrupt \n If not an isochronous endpoint, bits 5..2 are reserved and must be set to zero. If isochronous, they are defined as follows: \n Bits 3..2: Synchronization Type \n- 00 = No Synchronization \n- 01 = Asynchronous \n- 10 = Adaptive \n- 11 = Synchronous \n Bits 5..4: Usage Type \n- 00 = Data endpoint \n- 01 = Feedback endpoint \n- 10 = Implicit feedback Data endpoint \n- 11 = Reserved \n Refer to Chapter 5 of USB 2.0 specification for more information. \n All other bits are reserved and must be reset to zero. Reserved bits must be ignored by the host.
} bmAttributes;
struct TU_ATTR_PACKED {
#if defined(__CCRX__)
//FIXME the original defined bit field has a problem with the CCRX toolchain, so only a size field is defined
uint16_t size;
#else
uint16_t size : 11; ///< Maximum packet size this endpoint is capable of sending or receiving when this configuration is selected. \n For isochronous endpoints, this value is used to reserve the bus time in the schedule, required for the per-(micro)frame data payloads. The pipe may, on an ongoing basis, actually use less bandwidth than that reserved. The device reports, if necessary, the actual bandwidth used via its normal, non-USB defined mechanisms. \n For all endpoints, bits 10..0 specify the maximum packet size (in bytes). \n For high-speed isochronous and interrupt endpoints: \n Bits 12..11 specify the number of additional transaction opportunities per microframe: \n- 00 = None (1 transaction per microframe) \n- 01 = 1 additional (2 per microframe) \n- 10 = 2 additional (3 per microframe) \n- 11 = Reserved \n Bits 15..13 are reserved and must be set to zero.
uint16_t hs_period_mult : 2;
uint16_t TU_RESERVED : 3;
#endif
}wMaxPacketSize;
uint8_t bInterval ; ///< Interval for polling endpoint for data transfers. Expressed in frames or microframes depending on the device operating speed (i.e., either 1 millisecond or 125 us units). \n- For full-/high-speed isochronous endpoints, this value must be in the range from 1 to 16. The bInterval value is used as the exponent for a \f$ 2^(bInterval-1) \f$ value; e.g., a bInterval of 4 means a period of 8 (\f$ 2^(4-1) \f$). \n- For full-/low-speed interrupt endpoints, the value of this field may be from 1 to 255. \n- For high-speed interrupt endpoints, the bInterval value is used as the exponent for a \f$ 2^(bInterval-1) \f$ value; e.g., a bInterval of 4 means a period of 8 (\f$ 2^(4-1) \f$) . This value must be from 1 to 16. \n- For high-speed bulk/control OUT endpoints, the bInterval must specify the maximum NAK rate of the endpoint. A value of 0 indicates the endpoint never NAKs. Other values indicate at most 1 NAK each bInterval number of microframes. This value must be in the range from 0 to 255. \n Refer to Chapter 5 of USB 2.0 specification for more information.
uint16_t wMaxPacketSize ; // Bit 10..0 : max packet size, bit 12..11 additional transaction per highspeed micro-frame
uint8_t bInterval ; // Polling interval, in frames or microframes depending on the operating speed
} tusb_desc_endpoint_t;
TU_VERIFY_STATIC( sizeof(tusb_desc_endpoint_t) == 7, "size is not correct");
/// USB Other Speed Configuration Descriptor
typedef struct TU_ATTR_PACKED
{
@@ -372,7 +376,7 @@ typedef struct TU_ATTR_PACKED
uint8_t bNumInterfaces ; ///< Number of interfaces supported by this speed configuration
uint8_t bConfigurationValue ; ///< Value to use to select configuration
uint8_t IConfiguration ; ///< Index of string descriptor
uint8_t iConfiguration ; ///< Index of string descriptor
uint8_t bmAttributes ; ///< Same as Configuration descriptor
uint8_t bMaxPower ; ///< Same as Configuration descriptor
} tusb_desc_other_speed_t;
@@ -387,11 +391,14 @@ typedef struct TU_ATTR_PACKED
uint8_t bDeviceClass ; ///< Class Code
uint8_t bDeviceSubClass ; ///< SubClass Code
uint8_t bDeviceProtocol ; ///< Protocol Code
uint8_t bMaxPacketSize0 ; ///< Maximum packet size for other speed
uint8_t bNumConfigurations ; ///< Number of Other-speed Configurations
uint8_t bReserved ; ///< Reserved for future use, must be zero
} tusb_desc_device_qualifier_t;
TU_VERIFY_STATIC( sizeof(tusb_desc_device_qualifier_t) == 10, "size is not correct");
/// USB Interface Association Descriptor (IAD ECN)
typedef struct TU_ATTR_PACKED
{
@@ -506,6 +513,11 @@ static inline uint8_t tu_edpt_addr(uint8_t num, uint8_t dir)
return (uint8_t)(num | (dir ? TUSB_DIR_IN_MASK : 0));
}
static inline uint16_t tu_edpt_packet_size(tusb_desc_endpoint_t const* desc_ep)
{
return tu_le16toh(desc_ep->wMaxPacketSize) & TU_GENMASK(10, 0);
}
//--------------------------------------------------------------------+
// Descriptor helper
//--------------------------------------------------------------------+
+13 -1
View File
@@ -106,7 +106,14 @@ typedef struct TU_ATTR_ALIGNED(4)
void dcd_init (uint8_t rhport);
// Interrupt Handler
#if __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"
#endif
void dcd_int_handler(uint8_t rhport);
#if __GNUC__
#pragma GCC diagnostic pop
#endif
// Enable device interrupt
void dcd_int_enable (uint8_t rhport);
@@ -137,6 +144,11 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re
// Configure endpoint's registers according to descriptor
bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_ep);
// Close all non-control endpoints, cancel all pending transfers if any.
// Invoked when switching from a non-zero Configuration by SET_CONFIGURE therefore
// required for multiple configuration support.
void dcd_edpt_close_all (uint8_t rhport);
// Close an endpoint.
// Since it is weak, caller must TU_ASSERT this function's existence before calling it.
void dcd_edpt_close (uint8_t rhport, uint8_t ep_addr) TU_ATTR_WEAK;
@@ -148,7 +160,7 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer
// This API is optional, may be useful for register-based for transferring data.
bool dcd_edpt_xfer_fifo (uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes) TU_ATTR_WEAK;
// Stall endpoint
// Stall endpoint, any queuing transfer should be removed from endpoint
void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr);
// clear stall, data toggle is also reset to DATA0
+85 -39
View File
@@ -36,121 +36,167 @@
// - PORT_HIGHSPEED: mask to indicate which port support highspeed mode, bit0 for port0 and so on.
//------------- NXP -------------//
#if TU_CHECK_MCU(LPC11UXX) || TU_CHECK_MCU(LPC13XX) || TU_CHECK_MCU(LPC15XX)
#if TU_CHECK_MCU(OPT_MCU_LPC11UXX, OPT_MCU_LPC13XX, OPT_MCU_LPC15XX)
#define DCD_ATTR_ENDPOINT_MAX 5
#elif TU_CHECK_MCU(LPC175X_6X) || TU_CHECK_MCU(LPC177X_8X) || TU_CHECK_MCU(LPC40XX)
#elif TU_CHECK_MCU(OPT_MCU_LPC175X_6X, OPT_MCU_LPC177X_8X, OPT_MCU_LPC40XX)
#define DCD_ATTR_ENDPOINT_MAX 16
#elif TU_CHECK_MCU(LPC18XX) || TU_CHECK_MCU(LPC43XX)
#elif TU_CHECK_MCU(OPT_MCU_LPC18XX, OPT_MCU_LPC43XX)
// TODO USB0 has 6, USB1 has 4
#define DCD_ATTR_CONTROLLER_CHIPIDEA_HS
#define DCD_ATTR_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(LPC51UXX)
#elif TU_CHECK_MCU(OPT_MCU_LPC51UXX)
#define DCD_ATTR_ENDPOINT_MAX 5
#elif TU_CHECK_MCU(LPC54XXX)
#elif TU_CHECK_MCU(OPT_MCU_LPC54XXX)
// TODO USB0 has 5, USB1 has 6
#define DCD_ATTR_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(LPC55XX)
#elif TU_CHECK_MCU(OPT_MCU_LPC55XX)
// TODO USB0 has 5, USB1 has 6
#define DCD_ATTR_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(MIMXRT10XX)
#elif TU_CHECK_MCU(OPT_MCU_MIMXRT10XX)
#define DCD_ATTR_CONTROLLER_CHIPIDEA_HS
#define DCD_ATTR_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(MKL25ZXX) || TU_CHECK_MCU(K32L2BXX)
#elif TU_CHECK_MCU(OPT_MCU_MKL25ZXX, OPT_MCU_K32L2BXX)
#define DCD_ATTR_ENDPOINT_MAX 16
#elif TU_CHECK_MCU(OPT_MCU_MM32F327X)
#define DCD_ATTR_ENDPOINT_MAX 16
//------------- Nordic -------------//
#elif TU_CHECK_MCU(NRF5X)
#elif TU_CHECK_MCU(OPT_MCU_NRF5X)
// 8 CBI + 1 ISO
#define DCD_ATTR_ENDPOINT_MAX 9
//------------- Microchip -------------//
#elif TU_CHECK_MCU(SAMD21) || TU_CHECK_MCU(SAMD51) || TU_CHECK_MCU(SAME5X) || \
TU_CHECK_MCU(SAMD11) || TU_CHECK_MCU(SAML21) || TU_CHECK_MCU(SAML22)
#elif TU_CHECK_MCU(OPT_MCU_SAMD21, OPT_MCU_SAMD51, OPT_MCU_SAME5X) || \
TU_CHECK_MCU(OPT_MCU_SAMD11, OPT_MCU_SAML21, OPT_MCU_SAML22)
#define DCD_ATTR_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(SAMG)
#elif TU_CHECK_MCU(OPT_MCU_SAMG)
#define DCD_ATTR_ENDPOINT_MAX 6
#define DCD_ATTR_ENDPOINT_EXCLUSIVE_NUMBER
#elif TU_CHECK_MCU(SAMX7X)
#elif TU_CHECK_MCU(OPT_MCU_SAMX7X)
#define DCD_ATTR_ENDPOINT_MAX 10
#define DCD_ATTR_ENDPOINT_EXCLUSIVE_NUMBER
//------------- ST -------------//
#elif TU_CHECK_MCU(STM32F0) || TU_CHECK_MCU(STM32F1) || TU_CHECK_MCU(STM32F3) || \
TU_CHECK_MCU(STM32L0) || TU_CHECK_MCU(STM32L1) || TU_CHECK_MCU(STM32L4)
// F1: F102, F103
// L4: L4x2, L4x3
#elif TU_CHECK_MCU(OPT_MCU_STM32F0)
#define DCD_ATTR_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(STM32F2) || TU_CHECK_MCU(STM32F4) || TU_CHECK_MCU(STM32F3)
// F1: F105, F107 only has 4
// L4: L4x5, L4x6 has 6
// For most mcu, FS has 4, HS has 6
#define DCD_ATTR_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(OPT_MCU_STM32F1)
#if defined (STM32F105x8) || defined (STM32F105xB) || defined (STM32F105xC) || \
defined (STM32F107xB) || defined (STM32F107xC)
#define DCD_ATTR_ENDPOINT_MAX 4
#define DCD_ATTR_DWC2_STM32
#else
#define DCD_ATTR_ENDPOINT_MAX 8
#endif
#elif TU_CHECK_MCU(STM32F7)
#elif TU_CHECK_MCU(OPT_MCU_STM32F2)
// FS has 4 ep, HS has 5 ep
#define DCD_ATTR_ENDPOINT_MAX 6
#define DCD_ATTR_DWC2_STM32
#elif TU_CHECK_MCU(OPT_MCU_STM32F3)
#define DCD_ATTR_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_STM32F4)
// For most mcu, FS has 4, HS has 6. TODO 446/469/479 HS has 9
#define DCD_ATTR_ENDPOINT_MAX 6
#define DCD_ATTR_DWC2_STM32
#elif TU_CHECK_MCU(OPT_MCU_STM32F7)
// FS has 6, HS has 9
#define DCD_ATTR_ENDPOINT_MAX 9
#define DCD_ATTR_DWC2_STM32
#elif TU_CHECK_MCU(STM32H7)
#elif TU_CHECK_MCU(OPT_MCU_STM32H7)
#define DCD_ATTR_ENDPOINT_MAX 9
#define DCD_ATTR_DWC2_STM32
#elif TU_CHECK_MCU(OPT_MCU_STM32G4)
#define DCD_ATTR_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_STM32L0, OPT_MCU_STM32L1)
#define DCD_ATTR_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_STM32L4)
#if defined (STM32L475xx) || defined (STM32L476xx) || \
defined (STM32L485xx) || defined (STM32L486xx) || defined (STM32L496xx) || \
defined (STM32L4A6xx) || defined (STM32L4P5xx) || defined (STM32L4Q5xx) || \
defined (STM32L4R5xx) || defined (STM32L4R7xx) || defined (STM32L4R9xx) || \
defined (STM32L4S5xx) || defined (STM32L4S7xx) || defined (STM32L4S9xx)
#define DCD_ATTR_ENDPOINT_MAX 6
#define DCD_ATTR_DWC2_STM32
#else
#define DCD_ATTR_ENDPOINT_MAX 8
#endif
//------------- Sony -------------//
#elif TU_CHECK_MCU(CXD56)
#elif TU_CHECK_MCU(OPT_MCU_CXD56)
#define DCD_ATTR_ENDPOINT_MAX 7
#define DCD_ATTR_ENDPOINT_EXCLUSIVE_NUMBER
//------------- TI -------------//
#elif TU_CHECK_MCU(MSP430x5xx)
#elif TU_CHECK_MCU(OPT_MCU_MSP430x5xx)
#define DCD_ATTR_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_MSP432E4, OPT_MCU_TM4C123, OPT_MCU_TM4C129)
#define DCD_ATTR_ENDPOINT_MAX 8
//------------- ValentyUSB -------------//
#elif TU_CHECK_MCU(VALENTYUSB_EPTRI)
#elif TU_CHECK_MCU(OPT_MCU_VALENTYUSB_EPTRI)
#define DCD_ATTR_ENDPOINT_MAX 16
//------------- Nuvoton -------------//
#elif TU_CHECK_MCU(NUC121) || TU_CHECK_MCU(NUC126)
#elif TU_CHECK_MCU(OPT_MCU_NUC121, OPT_MCU_NUC126)
#define DCD_ATTR_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(NUC120)
#elif TU_CHECK_MCU(OPT_MCU_NUC120)
#define DCD_ATTR_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(NUC505)
#elif TU_CHECK_MCU(OPT_MCU_NUC505)
#define DCD_ATTR_ENDPOINT_MAX 12
//------------- Espressif -------------//
#elif TU_CHECK_MCU(ESP32S2) || TU_CHECK_MCU(ESP32S3)
#elif TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3)
#define DCD_ATTR_ENDPOINT_MAX 6
//------------- Dialog -------------//
#elif TU_CHECK_MCU(DA1469X)
#elif TU_CHECK_MCU(OPT_MCU_DA1469X)
#define DCD_ATTR_ENDPOINT_MAX 4
//------------- Raspberry Pi -------------//
#elif TU_CHECK_MCU(RP2040)
#elif TU_CHECK_MCU(OPT_MCU_RP2040)
#define DCD_ATTR_ENDPOINT_MAX 16
//------------- Silabs -------------//
#elif TU_CHECK_MCU(EFM32GG) || TU_CHECK_MCU(EFM32GG11) || TU_CHECK_MCU(EFM32GG12)
#elif TU_CHECK_MCU(OPT_MCU_EFM32GG)
#define DCD_ATTR_ENDPOINT_MAX 7
//------------- Renesas -------------//
#elif TU_CHECK_MCU(RX63X) || TU_CHECK_MCU(RX65X) || TU_CHECK_MCU(RX72N)
#elif TU_CHECK_MCU(OPT_MCU_RX63X, OPT_MCU_RX65X, OPT_MCU_RX72N)
#define DCD_ATTR_ENDPOINT_MAX 10
//#elif TU_CHECK_MCU(MM32F327X)
// #define DCD_ATTR_ENDPOINT_MAX not known yet
//------------- GigaDevice -------------//
#elif TU_CHECK_MCU(GD32VF103)
#elif TU_CHECK_MCU(OPT_MCU_GD32VF103)
#define DCD_ATTR_ENDPOINT_MAX 4
//------------- Broadcom -------------//
#elif TU_CHECK_MCU(OPT_MCU_BCM2711)
#define DCD_ATTR_ENDPOINT_MAX 8
//------------- Broadcom -------------//
#elif TU_CHECK_MCU(OPT_MCU_XMC4000)
#define DCD_ATTR_ENDPOINT_MAX 8
//------------- BridgeTek -------------//
#elif TU_CHECK_MCU(FT90X)
#define DCD_ATTR_ENDPOINT_MAX 8
+172 -106
View File
@@ -38,7 +38,7 @@
//--------------------------------------------------------------------+
// Debug level of USBD
#define USBD_DBG_LVL 2
#define USBD_DBG 2
#ifndef CFG_TUD_TASK_QUEUE_SZ
#define CFG_TUD_TASK_QUEUE_SZ 16
@@ -143,6 +143,18 @@ static usbd_class_driver_t const _usbd_driver[] =
},
#endif
#if CFG_TUD_VIDEO
{
DRIVER_NAME("VIDEO")
.init = videod_init,
.reset = videod_reset,
.open = videod_open,
.control_xfer_cb = videod_control_xfer_cb,
.xfer_cb = videod_xfer_cb,
.sof = NULL
},
#endif
#if CFG_TUD_MIDI
{
DRIVER_NAME("MIDI")
@@ -203,7 +215,7 @@ static usbd_class_driver_t const _usbd_driver[] =
},
#endif
#if CFG_TUD_NET
#if CFG_TUD_ECM_RNDIS || CFG_TUD_NCM
{
DRIVER_NAME("NET")
.init = netd_init,
@@ -432,19 +444,22 @@ bool tud_init (uint8_t rhport)
return true;
}
static void usbd_reset(uint8_t rhport)
static void configuration_reset(uint8_t rhport)
{
tu_varclr(&_usbd_dev);
memset(_usbd_dev.itf2drv, DRVID_INVALID, sizeof(_usbd_dev.itf2drv)); // invalid mapping
memset(_usbd_dev.ep2drv , DRVID_INVALID, sizeof(_usbd_dev.ep2drv )); // invalid mapping
usbd_control_reset();
for ( uint8_t i = 0; i < TOTAL_DRIVER_COUNT; i++ )
{
get_driver(i)->reset(rhport);
}
tu_varclr(&_usbd_dev);
memset(_usbd_dev.itf2drv, DRVID_INVALID, sizeof(_usbd_dev.itf2drv)); // invalid mapping
memset(_usbd_dev.ep2drv , DRVID_INVALID, sizeof(_usbd_dev.ep2drv )); // invalid mapping
}
static void usbd_reset(uint8_t rhport)
{
configuration_reset(rhport);
usbd_control_reset();
}
bool tud_task_event_ready(void)
@@ -686,9 +701,29 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
{
uint8_t const cfg_num = (uint8_t) p_request->wValue;
if ( !_usbd_dev.cfg_num && cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) );
_usbd_dev.cfg_num = cfg_num;
// Only process if new configure is different
if (_usbd_dev.cfg_num != cfg_num)
{
if ( _usbd_dev.cfg_num )
{
// already configured: need to clear all endpoints and driver first
TU_LOG(USBD_DBG, " Clear current Configuration (%u) before switching\r\n", _usbd_dev.cfg_num);
// close all non-control endpoints, cancel all pending transfers if any
dcd_edpt_close_all(rhport);
// close all drivers and current configured state except bus speed
uint8_t const speed = _usbd_dev.speed;
configuration_reset(rhport);
_usbd_dev.speed = speed; // restore speed
}
// switch to new configuration if not zero
if ( cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) );
}
_usbd_dev.cfg_num = cfg_num;
tud_control_status(rhport, p_request);
}
break;
@@ -701,7 +736,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
// Only support remote wakeup for device feature
TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue);
TU_LOG(USBD_DBG_LVL, " Enable Remote Wakeup\r\n");
TU_LOG(USBD_DBG, " Enable Remote Wakeup\r\n");
// Host may enable remote wake up before suspending especially HID device
_usbd_dev.remote_wakeup_en = true;
@@ -712,7 +747,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
// Only support remote wakeup for device feature
TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue);
TU_LOG(USBD_DBG_LVL, " Disable Remote Wakeup\r\n");
TU_LOG(USBD_DBG, " Disable Remote Wakeup\r\n");
// Host may disable remote wake up after resuming
_usbd_dev.remote_wakeup_en = false;
@@ -751,16 +786,24 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
// driver doesn't use alternate settings or implement this
TU_VERIFY(TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type);
if (TUSB_REQ_GET_INTERFACE == p_request->bRequest)
switch(p_request->bRequest)
{
uint8_t alternate = 0;
tud_control_xfer(rhport, p_request, &alternate, 1);
}else if (TUSB_REQ_SET_INTERFACE == p_request->bRequest)
{
tud_control_status(rhport, p_request);
} else
{
return false;
case TUSB_REQ_GET_INTERFACE:
case TUSB_REQ_SET_INTERFACE:
// Clear complete callback if driver set since it can also stall the request.
usbd_control_set_complete_callback(NULL);
if (TUSB_REQ_GET_INTERFACE == p_request->bRequest)
{
uint8_t alternate = 0;
tud_control_xfer(rhport, p_request, &alternate, 1);
}else
{
tud_control_status(rhport, p_request);
}
break;
default: return false;
}
}
}
@@ -843,12 +886,13 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
// This function parse configuration descriptor & open drivers accordingly
static bool process_set_config(uint8_t rhport, uint8_t cfg_num)
{
tusb_desc_configuration_t const * desc_cfg = (tusb_desc_configuration_t const *) tud_descriptor_configuration_cb(cfg_num-1); // index is cfg_num-1
// index is cfg_num-1
tusb_desc_configuration_t const * desc_cfg = (tusb_desc_configuration_t const *) tud_descriptor_configuration_cb(cfg_num-1);
TU_ASSERT(desc_cfg != NULL && desc_cfg->bDescriptorType == TUSB_DESC_CONFIGURATION);
// Parse configuration descriptor
_usbd_dev.remote_wakeup_support = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP) ? 1 : 0;
_usbd_dev.self_powered = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_SELF_POWERED) ? 1 : 0;
_usbd_dev.self_powered = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_SELF_POWERED ) ? 1 : 0;
// Parse interface descriptor
uint8_t const * p_desc = ((uint8_t const*) desc_cfg) + sizeof(tusb_desc_configuration_t);
@@ -856,66 +900,75 @@ static bool process_set_config(uint8_t rhport, uint8_t cfg_num)
while( p_desc < desc_end )
{
tusb_desc_interface_assoc_t const * desc_iad = NULL;
uint8_t assoc_itf_count = 1;
// Class will always starts with Interface Association (if any) and then Interface descriptor
if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) )
{
desc_iad = (tusb_desc_interface_assoc_t const *) p_desc;
tusb_desc_interface_assoc_t const * desc_iad = (tusb_desc_interface_assoc_t const *) p_desc;
assoc_itf_count = desc_iad->bInterfaceCount;
p_desc = tu_desc_next(p_desc); // next to Interface
// IAD's first interface number and class should match with opened interface
//TU_ASSERT(desc_iad->bFirstInterface == desc_itf->bInterfaceNumber &&
// desc_iad->bFunctionClass == desc_itf->bInterfaceClass);
}
TU_ASSERT( TUSB_DESC_INTERFACE == tu_desc_type(p_desc) );
tusb_desc_interface_t const * desc_itf = (tusb_desc_interface_t const*) p_desc;
uint16_t const remaining_len = desc_end-p_desc;
// Interface number must not be used already
TU_ASSERT(DRVID_INVALID == _usbd_dev.itf2drv[desc_itf->bInterfaceNumber]);
// TODO usbd can calculate the total length used for driver --> driver open() does not need to calculate it
// uint16_t const drv_len = tu_desc_get_interface_total_len(desc_itf, desc_iad ? desc_iad->bInterfaceCount : 1, desc_end-p_desc);
// Find driver for this interface
uint16_t const remaining_len = desc_end-p_desc;
uint8_t drv_id;
for (drv_id = 0; drv_id < TOTAL_DRIVER_COUNT; drv_id++)
{
usbd_class_driver_t const *driver = get_driver(drv_id);
uint16_t const drv_len = driver->open(rhport, desc_itf, remaining_len);
if ( drv_len > 0 )
if ( (sizeof(tusb_desc_interface_t) <= drv_len) && (drv_len <= remaining_len) )
{
// Open successfully, check if length is correct
TU_ASSERT( sizeof(tusb_desc_interface_t) <= drv_len && drv_len <= remaining_len);
// Open successfully
TU_LOG2(" %s opened\r\n", driver->name);
// bind interface to found driver
_usbd_dev.itf2drv[desc_itf->bInterfaceNumber] = drv_id;
// If using IAD, bind all interfaces to the same driver
if (desc_iad)
// Some drivers use 2 or more interfaces but may not have IAD e.g MIDI (always) or
// BTH (even CDC) with class in device descriptor (single interface)
if ( assoc_itf_count == 1)
{
// IAD's first interface number and class should match with opened interface
TU_ASSERT(desc_iad->bFirstInterface == desc_itf->bInterfaceNumber &&
desc_iad->bFunctionClass == desc_itf->bInterfaceClass);
#if CFG_TUD_CDC
if ( driver->open == cdcd_open ) assoc_itf_count = 2;
#endif
for(uint8_t i=1; i<desc_iad->bInterfaceCount; i++)
{
_usbd_dev.itf2drv[desc_itf->bInterfaceNumber+i] = drv_id;
}
#if CFG_TUD_MIDI
if ( driver->open == midid_open ) assoc_itf_count = 2;
#endif
#if CFG_TUD_BTH && CFG_TUD_BTH_ISO_ALT_COUNT
if ( driver->open == btd_open ) assoc_itf_count = 2;
#endif
}
// bind (associated) interfaces to found driver
for(uint8_t i=0; i<assoc_itf_count; i++)
{
uint8_t const itf_num = desc_itf->bInterfaceNumber+i;
// Interface number must not be used already
TU_ASSERT(DRVID_INVALID == _usbd_dev.itf2drv[itf_num]);
_usbd_dev.itf2drv[itf_num] = drv_id;
}
// bind all endpoints to found driver
tu_edpt_bind_driver(_usbd_dev.ep2drv, desc_itf, drv_len, drv_id);
p_desc += drv_len; // next interface
// next Interface
p_desc += drv_len;
break; // exit driver find loop
}
}
// Failed if cannot find supported driver
// Failed if there is no supported drivers
TU_ASSERT(drv_id < TOTAL_DRIVER_COUNT);
}
@@ -937,19 +990,23 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const
{
TU_LOG2(" Device\r\n");
uint16_t len = sizeof(tusb_desc_device_t);
void* desc_device = (void*) (uintptr_t) tud_descriptor_device_cb();
// Only send up to EP0 Packet Size if not addressed
// Only response with exactly 1 Packet if: not addressed and host requested more data than device descriptor has.
// This only happens with the very first get device descriptor and EP0 size = 8 or 16.
if ((CFG_TUD_ENDPOINT0_SIZE < sizeof(tusb_desc_device_t)) && !_usbd_dev.addressed)
if ((CFG_TUD_ENDPOINT0_SIZE < sizeof(tusb_desc_device_t)) && !_usbd_dev.addressed &&
((tusb_control_request_t const*) p_request)->wLength > sizeof(tusb_desc_device_t))
{
len = CFG_TUD_ENDPOINT0_SIZE;
// Hack here: we modify the request length to prevent usbd_control response with zlp
((tusb_control_request_t*) p_request)->wLength = CFG_TUD_ENDPOINT0_SIZE;
}
// since we are responding with 1 packet & less data than wLength.
tusb_control_request_t mod_request = *p_request;
mod_request.wLength = CFG_TUD_ENDPOINT0_SIZE;
return tud_control_xfer(rhport, p_request, (void*) tud_descriptor_device_cb(), len);
return tud_control_xfer(rhport, &mod_request, desc_device, CFG_TUD_ENDPOINT0_SIZE);
}else
{
return tud_control_xfer(rhport, p_request, desc_device, sizeof(tusb_desc_device_t));
}
}
break;
@@ -960,24 +1017,37 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const
// requested by host if USB > 2.0 ( i.e 2.1 or 3.x )
if (!tud_descriptor_bos_cb) return false;
tusb_desc_bos_t const* desc_bos = (tusb_desc_bos_t const*) tud_descriptor_bos_cb();
uintptr_t desc_bos = (uintptr_t) tud_descriptor_bos_cb();
TU_ASSERT(desc_bos);
// Use offsetof to avoid pointer to the odd/misaligned address
uint16_t const total_len = tu_le16toh( tu_unaligned_read16((uint8_t*) desc_bos + offsetof(tusb_desc_bos_t, wTotalLength)) );
uint16_t const total_len = tu_le16toh( tu_unaligned_read16((const void*) (desc_bos + offsetof(tusb_desc_bos_t, wTotalLength))) );
return tud_control_xfer(rhport, p_request, (void*) desc_bos, total_len);
}
break;
case TUSB_DESC_CONFIGURATION:
case TUSB_DESC_OTHER_SPEED_CONFIG:
{
TU_LOG2(" Configuration[%u]\r\n", desc_index);
uintptr_t desc_config;
if ( desc_type == TUSB_DESC_CONFIGURATION )
{
TU_LOG2(" Configuration[%u]\r\n", desc_index);
desc_config = (uintptr_t) tud_descriptor_configuration_cb(desc_index);
}else
{
// Host only request this after getting Device Qualifier descriptor
TU_LOG2(" Other Speed Configuration\r\n");
TU_VERIFY( tud_descriptor_other_speed_configuration_cb );
desc_config = (uintptr_t) tud_descriptor_other_speed_configuration_cb(desc_index);
}
tusb_desc_configuration_t const* desc_config = (tusb_desc_configuration_t const*) tud_descriptor_configuration_cb(desc_index);
TU_ASSERT(desc_config);
// Use offsetof to avoid pointer to the odd/misaligned address
uint16_t const total_len = tu_le16toh( tu_unaligned_read16((uint8_t*) desc_config + offsetof(tusb_desc_configuration_t, wTotalLength)) );
uint16_t const total_len = tu_le16toh( tu_unaligned_read16((const void*) (desc_config + offsetof(tusb_desc_configuration_t, wTotalLength))) );
return tud_control_xfer(rhport, p_request, (void*) desc_config, total_len);
}
@@ -988,38 +1058,26 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const
TU_LOG2(" String[%u]\r\n", desc_index);
// String Descriptor always uses the desc set from user
uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index, p_request->wIndex);
uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index, tu_le16toh(p_request->wIndex));
TU_VERIFY(desc_str);
// first byte of descriptor is its size
return tud_control_xfer(rhport, p_request, (void*) desc_str, desc_str[0]);
return tud_control_xfer(rhport, p_request, (void*) (uintptr_t) desc_str, tu_desc_len(desc_str));
}
break;
case TUSB_DESC_DEVICE_QUALIFIER:
{
TU_LOG2(" Device Qualifier\r\n");
// Host sends this request to ask why our device with USB BCD from 2.0
// but is running at Full/Low Speed. If not highspeed capable stall this request,
// otherwise return the descriptor that could work in highspeed mode
if ( tud_descriptor_device_qualifier_cb )
{
uint8_t const* desc_qualifier = tud_descriptor_device_qualifier_cb();
TU_ASSERT(desc_qualifier);
TU_VERIFY( tud_descriptor_device_qualifier_cb );
// first byte of descriptor is its size
return tud_control_xfer(rhport, p_request, (void*) desc_qualifier, desc_qualifier[0]);
}else
{
return false;
}
break;
uint8_t const* desc_qualifier = tud_descriptor_device_qualifier_cb();
TU_VERIFY(desc_qualifier);
case TUSB_DESC_OTHER_SPEED_CONFIG:
TU_LOG2(" Other Speed Configuration\r\n");
// After Device Qualifier descriptor is received host will ask for this descriptor
return false; // not supported
// first byte of descriptor is its size
return tud_control_xfer(rhport, p_request, (void*) (uintptr_t) desc_qualifier, tu_desc_len(desc_qualifier));
}
break;
default: return false;
@@ -1034,15 +1092,11 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr)
switch (event->event_id)
{
case DCD_EVENT_UNPLUGGED:
// UNPLUGGED event can be bouncing, only processing if we are currently connected
if ( _usbd_dev.connected )
{
_usbd_dev.connected = 0;
_usbd_dev.addressed = 0;
_usbd_dev.cfg_num = 0;
_usbd_dev.suspended = 0;
osal_queue_send(_usbd_q, event, in_isr);
}
_usbd_dev.connected = 0;
_usbd_dev.addressed = 0;
_usbd_dev.cfg_num = 0;
_usbd_dev.suspended = 0;
osal_queue_send(_usbd_q, event, in_isr);
break;
case DCD_EVENT_SUSPEND:
@@ -1301,27 +1355,33 @@ bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr)
void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
TU_LOG(USBD_DBG_LVL, " Stall EP %02X", ep_addr);
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_edpt_stall(rhport, ep_addr);
_usbd_dev.ep_status[epnum][dir].stalled = true;
_usbd_dev.ep_status[epnum][dir].busy = true;
// only stalled if currently cleared
if ( !_usbd_dev.ep_status[epnum][dir].stalled )
{
TU_LOG(USBD_DBG, " Stall EP %02X\r\n", ep_addr);
dcd_edpt_stall(rhport, ep_addr);
_usbd_dev.ep_status[epnum][dir].stalled = true;
_usbd_dev.ep_status[epnum][dir].busy = true;
}
}
void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
TU_LOG(USBD_DBG_LVL, " Clear Stall EP %02X", ep_addr);
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_edpt_clear_stall(rhport, ep_addr);
_usbd_dev.ep_status[epnum][dir].stalled = false;
_usbd_dev.ep_status[epnum][dir].busy = false;
// only clear if currently stalled
if ( _usbd_dev.ep_status[epnum][dir].stalled )
{
TU_LOG(USBD_DBG, " Clear Stall EP %02X\r\n", ep_addr);
dcd_edpt_clear_stall(rhport, ep_addr);
_usbd_dev.ep_status[epnum][dir].stalled = false;
_usbd_dev.ep_status[epnum][dir].busy = false;
}
}
bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr)
@@ -1345,7 +1405,13 @@ void usbd_edpt_close(uint8_t rhport, uint8_t ep_addr)
TU_ASSERT(dcd_edpt_close, /**/);
TU_LOG2(" CLOSING Endpoint: 0x%02X\r\n", ep_addr);
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_edpt_close(rhport, ep_addr);
_usbd_dev.ep_status[epnum][dir].stalled = false;
_usbd_dev.ep_status[epnum][dir].busy = false;
_usbd_dev.ep_status[epnum][dir].claimed = false;
return;
}
+89 -19
View File
@@ -113,9 +113,16 @@ uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid);
TU_ATTR_WEAK uint8_t const * tud_descriptor_bos_cb(void);
// Invoked when received GET DEVICE QUALIFIER DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete.
// device_qualifier descriptor describes information about a high-speed capable device that would
// change if the device were operating at the other speed. If not highspeed capable stall this request.
TU_ATTR_WEAK uint8_t const* tud_descriptor_device_qualifier_cb(void);
// Invoked when received GET OTHER SEED CONFIGURATION DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
// Configuration descriptor in the other speed e.g if high speed then this is for full speed and vice versa
TU_ATTR_WEAK uint8_t const* tud_descriptor_other_speed_configuration_cb(uint8_t index);
// Invoked when device is mounted (configured)
TU_ATTR_WEAK void tud_mount_cb(void);
@@ -171,17 +178,18 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
0x9C, 0xD2, 0x65, 0x9D, 0x9E, 0x64, 0x8A, 0x9F
//--------------------------------------------------------------------+
// Configuration & Interface Descriptor Templates
// Configuration Descriptor Templates
//--------------------------------------------------------------------+
//------------- Configuration -------------//
#define TUD_CONFIG_DESC_LEN (9)
// Config number, interface count, string index, total length, attribute, power in mA
#define TUD_CONFIG_DESCRIPTOR(config_num, _itfcount, _stridx, _total_len, _attribute, _power_ma) \
9, TUSB_DESC_CONFIGURATION, U16_TO_U8S_LE(_total_len), _itfcount, config_num, _stridx, TU_BIT(7) | _attribute, (_power_ma)/2
//------------- CDC -------------//
//--------------------------------------------------------------------+
// CDC Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor: 66 bytes
#define TUD_CDC_DESC_LEN (8+9+5+5+4+5+7+9+7+7)
@@ -210,7 +218,9 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
//------------- MSC -------------//
//--------------------------------------------------------------------+
// MSC Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor: 23 bytes
#define TUD_MSC_DESC_LEN (9 + 7 + 7)
@@ -224,7 +234,10 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
//------------- HID -------------//
//--------------------------------------------------------------------+
// HID Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor: 25 bytes
#define TUD_HID_DESC_LEN (9 + 9 + 7)
@@ -254,8 +267,10 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval
//------------- MIDI -------------//
// MIDI v1.0 is based on Audio v1.0
//--------------------------------------------------------------------+
// MIDI Descriptor Templates
// Note: MIDI v1.0 is based on Audio v1.0
//--------------------------------------------------------------------+
#define TUD_MIDI_DESC_HEAD_LEN (9 + 9 + 9 + 7)
#define TUD_MIDI_DESC_HEAD(_itfnum, _stridx, _numcables) \
@@ -312,7 +327,9 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
TUD_MIDI_DESC_EP(_epin, _epsize, 1),\
TUD_MIDI_JACKID_OUT_EMB(1)
//------------- AUDIO -------------//
//--------------------------------------------------------------------+
// Audio v2.0 Descriptor Templates
//--------------------------------------------------------------------+
/* Standard Interface Association Descriptor (IAD) */
#define TUD_AUDIO_DESC_IAD_LEN 8
@@ -544,7 +561,10 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
((((_maxFrequency + ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 7999 : 999)) / ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 8000 : 1000)) + 1) * _nBytesPerSample * _nChannels)
//------------- TUD_USBTMC/USB488 -------------//
//--------------------------------------------------------------------+
// USBTMC/USB488 Descriptor Templates
//--------------------------------------------------------------------+
#define TUD_USBTMC_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC)
#define TUD_USBTMC_APP_SUBCLASS 0x03u
@@ -574,8 +594,10 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
#define TUD_USBTMC_INT_DESCRIPTOR_LEN (7u)
//--------------------------------------------------------------------+
// Vendor Descriptor Templates
//--------------------------------------------------------------------+
//------------- Vendor -------------//
#define TUD_VENDOR_DESC_LEN (9+7+7)
// Interface number, string index, EP Out & IN address, EP size
@@ -587,7 +609,10 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
//------------- DFU Runtime -------------//
//--------------------------------------------------------------------+
// DFU Runtime Descriptor Templates
//--------------------------------------------------------------------+
#define TUD_DFU_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC)
#define TUD_DFU_APP_SUBCLASS (APP_SUBCLASS_DFU_RUNTIME)
@@ -602,6 +627,10 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
/* Function */ \
9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101)
//--------------------------------------------------------------------+
// DFU Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor: 9 bytes + number of alternatives * 9
#define TUD_DFU_DESC_LEN(_alt_count) (9 + (_alt_count) * 9)
@@ -647,8 +676,9 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx), \
_TUD_DFU_ALT_7(_itfnum, _alt_count+1, _stridx+1)
//------------- CDC-ECM -------------//
//--------------------------------------------------------------------+
// CDC-ECM Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor: 71 bytes
#define TUD_CDC_ECM_DESC_LEN (8+9+5+5+13+7+9+9+7+7)
@@ -677,8 +707,9 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
/* Endpoint Out */\
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
//------------- RNDIS -------------//
//--------------------------------------------------------------------+
// RNDIS Descriptor Templates
//--------------------------------------------------------------------+
#if 0
/* Windows XP */
@@ -719,7 +750,10 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
/* Endpoint Out */\
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
//------------- BT Radio -------------//
//--------------------------------------------------------------------+
// Bluetooth Radio Descriptor Templates
//--------------------------------------------------------------------+
#define TUD_BT_APP_CLASS (TUSB_CLASS_WIRELESS_CONTROLLER)
#define TUD_BT_APP_SUBCLASS 0x01
#define TUD_BT_PROTOCOL_PRIMARY_CONTROLLER 0x01
@@ -729,8 +763,8 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
#define CFG_TUD_BTH_ISO_ALT_COUNT 0
#endif
// Length of template descriptor: 30 bytes + number of ISO alternatives * 23
#define TUD_BTH_DESC_LEN (9 + 7 + 7 + 7 + (CFG_TUD_BTH_ISO_ALT_COUNT) * (9 + 7 + 7))
// Length of template descriptor: 38 bytes + number of ISO alternatives * 23
#define TUD_BTH_DESC_LEN (8 + 9 + 7 + 7 + 7 + (CFG_TUD_BTH_ISO_ALT_COUNT) * (9 + 7 + 7))
/* Primary Interface */
#define TUD_BTH_PRI_ITF(_itfnum, _stridx, _ep_evt, _ep_evt_size, _ep_evt_interval, _ep_in, _ep_out, _ep_size) \
@@ -770,10 +804,46 @@ TU_ATTR_WEAK bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb
// BT Primary controller descriptor
// Interface number, string index, attributes, event endpoint, event endpoint size, interval, data in, data out, data endpoint size, iso endpoint sizes
// TODO BTH should also use IAD like CDC for composite device
#define TUD_BTH_DESCRIPTOR(_itfnum, _stridx, _ep_evt, _ep_evt_size, _ep_evt_interval, _ep_in, _ep_out, _ep_size,...) \
/* Interface Associate */\
8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUD_BT_APP_CLASS, TUD_BT_APP_SUBCLASS, TUD_BT_PROTOCOL_PRIMARY_CONTROLLER, 0,\
TUD_BTH_PRI_ITF(_itfnum, _stridx, _ep_evt, _ep_evt_size, _ep_evt_interval, _ep_in, _ep_out, _ep_size) \
TUD_BTH_ISO_ITFS(_itfnum + 1, _ep_in + 1, _ep_out + 1, __VA_ARGS__)
//--------------------------------------------------------------------+
// CDC-NCM Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor
#define TUD_CDC_NCM_DESC_LEN (8+9+5+5+13+6+7+9+9+7+7)
// CDC-ECM Descriptor Template
// Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size.
#define TUD_CDC_NCM_DESCRIPTOR(_itfnum, _desc_stridx, _mac_stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize, _maxsegmentsize) \
/* Interface Association */\
8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_NETWORK_CONTROL_MODEL, 0, 0,\
/* CDC Control Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_NETWORK_CONTROL_MODEL, 0, _desc_stridx,\
/* CDC-NCM Header */\
5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0110),\
/* CDC-NCM Union */\
5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\
/* CDC-NCM Functional Descriptor */\
13, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ETHERNET_NETWORKING, _mac_stridx, 0, 0, 0, 0, U16_TO_U8S_LE(_maxsegmentsize), U16_TO_U8S_LE(0), 0, \
/* CDC-NCM Functional Descriptor */\
6, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_NCM, U16_TO_U8S_LE(0x0100), 0, \
/* Endpoint Notification */\
7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 50,\
/* CDC Data Interface (default inactive) */\
9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 0, TUSB_CLASS_CDC_DATA, 0, NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK, 0,\
/* CDC Data Interface (alternative active) */\
9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 1, 2, TUSB_CLASS_CDC_DATA, 0, NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK, 0,\
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
/* Endpoint Out */\
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
#ifdef __cplusplus
}
#endif
+2 -1
View File
@@ -81,7 +81,7 @@ bool usbd_edpt_claim(uint8_t rhport, uint8_t ep_addr);
// Release an endpoint without submitting a transfer
bool usbd_edpt_release(uint8_t rhport, uint8_t ep_addr);
// Check if endpoint transferring is complete
// Check if endpoint is busy transferring
bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr);
// Stall endpoint
@@ -93,6 +93,7 @@ void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr);
// Check if endpoint is stalled
bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr);
// Check if endpoint is ready (not busy and not stalled)
TU_ATTR_ALWAYS_INLINE static inline
bool usbd_edpt_ready(uint8_t rhport, uint8_t ep_addr)
{
+23 -23
View File
@@ -34,64 +34,64 @@
// - PORT_HIGHSPEED: mask to indicate which port support highspeed mode, bit0 for port0 and so on.
//------------- NXP -------------//
#if TU_CHECK_MCU(LPC175X_6X) || TU_CHECK_MCU(LPC177X_8X) || TU_CHECK_MCU(LPC40XX)
#if TU_CHECK_MCU(OPT_MCU_LPC175X_6X, OPT_MCU_LPC177X_8X, OPT_MCU_LPC40XX)
#define HCD_ATTR_OHCI
#elif TU_CHECK_MCU(LPC18XX) || TU_CHECK_MCU(LPC43XX)
#elif TU_CHECK_MCU(OPT_MCU_LPC18XX, OPT_MCU_LPC43XX)
#define HCD_ATTR_EHCI_TRANSDIMENSION
#elif TU_CHECK_MCU(LPC54XXX)
#elif TU_CHECK_MCU(OPT_MCU_LPC54XXX)
// #define HCD_ATTR_EHCI_NXP_PTD
#elif TU_CHECK_MCU(LPC55XX)
#elif TU_CHECK_MCU(OPT_MCU_LPC55XX)
// #define HCD_ATTR_EHCI_NXP_PTD
#elif TU_CHECK_MCU(MIMXRT10XX)
#elif TU_CHECK_MCU(OPT_MCU_MIMXRT10XX)
#define HCD_ATTR_EHCI_TRANSDIMENSION
#elif TU_CHECK_MCU(MKL25ZXX)
#elif TU_CHECK_MCU(OPT_MCU_MKL25ZXX)
//------------- Microchip -------------//
#elif TU_CHECK_MCU(SAMD21) || TU_CHECK_MCU(SAMD51) || TU_CHECK_MCU(SAME5X) || \
TU_CHECK_MCU(SAMD11) || TU_CHECK_MCU(SAML21) || TU_CHECK_MCU(SAML22)
#elif TU_CHECK_MCU(OPT_MCU_SAMD21, OPT_MCU_SAMD51, OPT_MCU_SAME5X) || \
TU_CHECK_MCU(OPT_MCU_SAMD11, OPT_MCU_SAML21, OPT_MCU_SAML22)
#elif TU_CHECK_MCU(SAMG)
#elif TU_CHECK_MCU(OPT_MCU_SAMG)
#elif TU_CHECK_MCU(SAMX7X)
#elif TU_CHECK_MCU(OPT_MCU_SAMX7X)
//------------- ST -------------//
#elif TU_CHECK_MCU(STM32F0) || TU_CHECK_MCU(STM32F1) || TU_CHECK_MCU(STM32F3) || \
TU_CHECK_MCU(STM32L0) || TU_CHECK_MCU(STM32L1) || TU_CHECK_MCU(STM32L4)
#elif TU_CHECK_MCU(OPT_MCU_STM32F0, OPT_MCU_STM32F1, OPT_MCU_STM32F3) || \
TU_CHECK_MCU(OPT_MCU_STM32L0, OPT_MCU_STM32L1, OPT_MCU_STM32L4)
#elif TU_CHECK_MCU(STM32F2) || TU_CHECK_MCU(STM32F4) || TU_CHECK_MCU(STM32F3)
#elif TU_CHECK_MCU(OPT_MCU_STM32F2, OPT_MCU_STM32F3, OPT_MCU_STM32F4)
#elif TU_CHECK_MCU(STM32F7)
#elif TU_CHECK_MCU(OPT_MCU_STM32F7)
#elif TU_CHECK_MCU(STM32H7)
#elif TU_CHECK_MCU(OPT_MCU_STM32H7)
//------------- Sony -------------//
#elif TU_CHECK_MCU(CXD56)
#elif TU_CHECK_MCU(OPT_MCU_CXD56)
//------------- Nuvoton -------------//
#elif TU_CHECK_MCU(NUC505)
#elif TU_CHECK_MCU(OPT_MCU_NUC505)
//------------- Espressif -------------//
#elif TU_CHECK_MCU(ESP32S2) || TU_CHECK_MCU(ESP32S3)
#elif TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3)
//------------- Raspberry Pi -------------//
#elif TU_CHECK_MCU(RP2040)
#elif TU_CHECK_MCU(OPT_MCU_RP2040)
//------------- Silabs -------------//
#elif TU_CHECK_MCU(EFM32GG) || TU_CHECK_MCU(EFM32GG11) || TU_CHECK_MCU(EFM32GG12)
#elif TU_CHECK_MCU(OPT_MCU_EFM32GG)
//------------- Renesas -------------//
#elif TU_CHECK_MCU(RX63X) || TU_CHECK_MCU(RX65X) || TU_CHECK_MCU(RX72N)
#elif TU_CHECK_MCU(OPT_MCU_RX63X, OPT_MCU_RX65X, OPT_MCU_RX72N)
//#elif TU_CHECK_MCU(MM32F327X)
//#elif TU_CHECK_MCU(OPT_MCU_MM32F327X)
// #define DCD_ATTR_ENDPOINT_MAX not known yet
//------------- GigaDevice -------------//
#elif TU_CHECK_MCU(GD32VF103)
#elif TU_CHECK_MCU(OPT_MCU_GD32VF103)
#else
// #warning "DCD_ATTR_ENDPOINT_MAX is not defined for this MCU, default to 8"
+64 -48
View File
@@ -53,13 +53,39 @@
// USBH-HCD common data structure
//--------------------------------------------------------------------+
typedef struct {
//------------- port -------------//
// device0 struct must be strictly a subset of normal device struct
typedef struct
{
// port
uint8_t rhport;
uint8_t hub_addr;
uint8_t hub_port;
uint8_t speed;
volatile struct TU_ATTR_PACKED
{
uint8_t connected : 1;
uint8_t addressed : 1;
uint8_t configured : 1;
uint8_t suspended : 1;
};
} usbh_dev0_t;
typedef struct {
// port
uint8_t rhport;
uint8_t hub_addr;
uint8_t hub_port;
uint8_t speed;
volatile struct TU_ATTR_PACKED
{
uint8_t connected : 1;
uint8_t addressed : 1;
uint8_t configured : 1;
uint8_t suspended : 1;
};
//------------- device descriptor -------------//
uint16_t vid;
uint16_t pid;
@@ -73,14 +99,6 @@ typedef struct {
// uint8_t interface_count; // bNumInterfaces alias
//------------- device -------------//
struct TU_ATTR_PACKED
{
uint8_t connected : 1;
uint8_t addressed : 1;
uint8_t configured : 1;
uint8_t suspended : 1;
};
volatile uint8_t state; // device state, value from enum tusbh_device_state_t
uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid)
@@ -103,16 +121,6 @@ typedef struct {
} usbh_device_t;
typedef struct
{
uint8_t rhport;
uint8_t hub_addr;
uint8_t hub_port;
uint8_t speed;
volatile uint8_t connected;
} usbh_dev0_t;
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
@@ -533,10 +541,12 @@ void process_device_unplugged(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port
usbh_class_drivers[drv_id].close(dev_addr);
}
hcd_device_close(rhport, dev_addr);
// release all endpoints associated with the device
memset(dev->itf2drv, DRVID_INVALID, sizeof(dev->itf2drv)); // invalid mapping
memset(dev->ep2drv , DRVID_INVALID, sizeof(dev->ep2drv )); // invalid mapping
hcd_device_close(rhport, dev_addr);
tu_memclr(dev->ep_status, sizeof(dev->ep_status));
dev->state = TUSB_DEVICE_STATE_UNPLUG;
}
@@ -894,11 +904,10 @@ static bool enum_get_9byte_config_desc_complete(uint8_t dev_addr, tusb_control_r
TU_ASSERT(XFER_RESULT_SUCCESS == result);
// TODO not enough buffer to hold configuration descriptor
tusb_desc_configuration_t const * desc_config = (tusb_desc_configuration_t const*) _usbh_ctrl_buf;
uint16_t total_len;
uint8_t const * desc_config = _usbh_ctrl_buf;
// Use offsetof to avoid pointer to the odd/misaligned address
memcpy(&total_len, (uint8_t*) desc_config + offsetof(tusb_desc_configuration_t, wTotalLength), 2);
uint16_t const total_len = tu_le16toh( tu_unaligned_read16(desc_config + offsetof(tusb_desc_configuration_t, wTotalLength)) );
TU_ASSERT(total_len <= CFG_TUH_ENUMERATION_BUFSIZE);
@@ -982,25 +991,38 @@ static bool parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configura
// parse each interfaces
while( p_desc < desc_end )
{
// TODO Do we need to use IAD
tusb_desc_interface_assoc_t const * desc_iad = NULL;
uint8_t assoc_itf_count = 1;
// Class will always starts with Interface Association (if any) and then Interface descriptor
if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) )
{
desc_iad = (tusb_desc_interface_assoc_t const *) p_desc;
p_desc = tu_desc_next(p_desc);
tusb_desc_interface_assoc_t const * desc_iad = (tusb_desc_interface_assoc_t const *) p_desc;
assoc_itf_count = desc_iad->bInterfaceCount;
p_desc = tu_desc_next(p_desc); // next to Interface
// IAD's first interface number and class should match with opened interface
//TU_ASSERT(desc_iad->bFirstInterface == desc_itf->bInterfaceNumber &&
// desc_iad->bFunctionClass == desc_itf->bInterfaceClass);
}
TU_ASSERT( TUSB_DESC_INTERFACE == tu_desc_type(p_desc) );
tusb_desc_interface_t const* desc_itf = (tusb_desc_interface_t const*) p_desc;
// Interface number must not be used already
TU_ASSERT( dev->itf2drv[desc_itf->bInterfaceNumber] == DRVID_INVALID );
#if CFG_TUH_MIDI
// MIDI has 2 interfaces (Audio Control v1 + MIDIStreaming) but does not have IAD
// manually increase the associated count
if (1 == assoc_itf_count &&
TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass &&
AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass &&
AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol)
{
assoc_itf_count = 2;
}
#endif
uint16_t const drv_len = tu_desc_get_interface_total_len(desc_itf, desc_iad ? desc_iad->bInterfaceCount : 1, desc_end-p_desc);
TU_ASSERT(drv_len);
uint16_t const drv_len = tu_desc_get_interface_total_len(desc_itf, assoc_itf_count, desc_end-p_desc);
TU_ASSERT(drv_len >= sizeof(tusb_desc_interface_t));
if (desc_itf->bInterfaceClass == TUSB_CLASS_HUB && dev->hub_addr != 0)
{
@@ -1019,22 +1041,16 @@ static bool parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configura
if ( driver->open(dev->rhport, dev_addr, desc_itf, drv_len) )
{
// open successfully
TU_LOG2(" Opened successfully\r\n");
TU_LOG2(" %s opened\r\n", driver->name);
// bind interface to found driver
dev->itf2drv[desc_itf->bInterfaceNumber] = drv_id;
// If using IAD, bind all interfaces to the same driver
if (desc_iad)
// bind (associated) interfaces to found driver
for(uint8_t i=0; i<assoc_itf_count; i++)
{
// IAD's first interface number and class should match with opened interface
TU_ASSERT(desc_iad->bFirstInterface == desc_itf->bInterfaceNumber &&
desc_iad->bFunctionClass == desc_itf->bInterfaceClass);
uint8_t const itf_num = desc_itf->bInterfaceNumber+i;
for(uint8_t i=1; i<desc_iad->bInterfaceCount; i++)
{
dev->itf2drv[desc_itf->bInterfaceNumber+i] = drv_id;
}
// Interface number must not be used already
TU_ASSERT( DRVID_INVALID == dev->itf2drv[itf_num] );
dev->itf2drv[itf_num] = drv_id;
}
// bind all endpoints to found driver
@@ -1158,7 +1174,7 @@ static bool usbh_edpt_control_open(uint8_t dev_addr, uint8_t max_packet_size)
.bDescriptorType = TUSB_DESC_ENDPOINT,
.bEndpointAddress = 0,
.bmAttributes = { .xfer = TUSB_XFER_CONTROL },
.wMaxPacketSize = { .size = max_packet_size },
.wMaxPacketSize = max_packet_size,
.bInterval = 0
};
+7
View File
@@ -67,6 +67,10 @@ typedef void (*osal_task_func_t)( void * );
// OSAL Porting API
//--------------------------------------------------------------------+
#if __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"
#endif
//------------- Semaphore -------------//
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef);
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr);
@@ -84,6 +88,9 @@ static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef);
static inline bool osal_queue_receive(osal_queue_t qhdl, void* data);
static inline bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr);
static inline bool osal_queue_empty(osal_queue_t qhdl);
#if __GNUC__
#pragma GCC diagnostic pop
#endif
#if 0 // TODO remove subtask related macros later
// Sub Task
+4 -4
View File
@@ -28,10 +28,10 @@
#define _TUSB_OSAL_FREERTOS_H_
// FreeRTOS Headers
#include "FreeRTOS.h"
#include "semphr.h"
#include "queue.h"
#include "task.h"
#include TU_INCLUDE_PATH(CFG_TUSB_OS_INC_PATH,FreeRTOS.h)
#include TU_INCLUDE_PATH(CFG_TUSB_OS_INC_PATH,semphr.h)
#include TU_INCLUDE_PATH(CFG_TUSB_OS_INC_PATH,queue.h)
#include TU_INCLUDE_PATH(CFG_TUSB_OS_INC_PATH,task.h)
#ifdef __cplusplus
extern "C" {
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+50
View File
@@ -0,0 +1,50 @@
/*
* 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 _CI_HS_IMXRT_H_
#define _CI_HS_IMXRT_H_
#include "fsl_device_registers.h"
static const ci_hs_controller_t _ci_controller[] =
{
// RT1010 and RT1020 only has 1 USB controller
#if FSL_FEATURE_SOC_USBHS_COUNT == 1
{ .reg_base = USB_BASE , .irqnum = USB_OTG1_IRQn, .ep_count = 8 }
#else
{ .reg_base = USB1_BASE, .irqnum = USB_OTG1_IRQn, .ep_count = 8 },
{ .reg_base = USB2_BASE, .irqnum = USB_OTG2_IRQn, .ep_count = 8 }
#endif
};
#define CI_DCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum)
#define CI_DCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum)
#define CI_HCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum)
#define CI_HCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum)
#endif
@@ -0,0 +1,45 @@
/*
* 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 _CI_HS_LPC18_43_H_
#define _CI_HS_LPC18_43_H_
// LPCOpen for 18xx & 43xx
#include "chip.h"
static const ci_hs_controller_t _ci_controller[] =
{
{ .reg_base = LPC_USB0_BASE, .irqnum = USB0_IRQn, .ep_count = 6 },
{ .reg_base = LPC_USB1_BASE, .irqnum = USB1_IRQn, .ep_count = 4 }
};
#define CI_DCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum)
#define CI_DCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum)
#define CI_HCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum)
#define CI_HCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum)
#endif
+144
View File
@@ -0,0 +1,144 @@
/*
* 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 CI_HS_TYPE_H_
#define CI_HS_TYPE_H_
#ifdef __cplusplus
extern "C" {
#endif
// USBCMD
enum {
USBCMD_RUN_STOP = TU_BIT(0),
USBCMD_RESET = TU_BIT(1),
USBCMD_SETUP_TRIPWIRE = TU_BIT(13),
USBCMD_ADD_QTD_TRIPWIRE = TU_BIT(14) ///< This bit is used as a semaphore to ensure the to proper addition of a new dTD to an active (primed) endpoints linked list. This bit is set and cleared by software during the process of adding a new dTD
// Interrupt Threshold bit 23:16
};
// PORTSC1
#define PORTSC1_PORT_SPEED_POS 26
enum {
PORTSC1_CURRENT_CONNECT_STATUS = TU_BIT(0),
PORTSC1_FORCE_PORT_RESUME = TU_BIT(6),
PORTSC1_SUSPEND = TU_BIT(7),
PORTSC1_FORCE_FULL_SPEED = TU_BIT(24),
PORTSC1_PORT_SPEED = TU_BIT(26) | TU_BIT(27)
};
// OTGSC
enum {
OTGSC_VBUS_DISCHARGE = TU_BIT(0),
OTGSC_VBUS_CHARGE = TU_BIT(1),
// OTGSC_HWASSIST_AUTORESET = TU_BIT(2),
OTGSC_OTG_TERMINATION = TU_BIT(3), ///< Must set to 1 when OTG go to device mode
OTGSC_DATA_PULSING = TU_BIT(4),
OTGSC_ID_PULLUP = TU_BIT(5),
// OTGSC_HWASSIT_DATA_PULSE = TU_BIT(6),
// OTGSC_HWASSIT_BDIS_ACONN = TU_BIT(7),
OTGSC_ID = TU_BIT(8), ///< 0 = A device, 1 = B Device
OTGSC_A_VBUS_VALID = TU_BIT(9),
OTGSC_A_SESSION_VALID = TU_BIT(10),
OTGSC_B_SESSION_VALID = TU_BIT(11),
OTGSC_B_SESSION_END = TU_BIT(12),
OTGSC_1MS_TOGGLE = TU_BIT(13),
OTGSC_DATA_BUS_PULSING_STATUS = TU_BIT(14),
};
// USBMode
enum {
USBMODE_CM_DEVICE = 2,
USBMODE_CM_HOST = 3,
USBMODE_SLOM = TU_BIT(3),
USBMODE_SDIS = TU_BIT(4),
USBMODE_VBUS_POWER_SELECT = TU_BIT(5), // Need to be enabled for LPC18XX/43XX in host mode
};
// Device Registers
typedef struct
{
//------------- ID + HW Parameter Registers-------------//
volatile uint32_t TU_RESERVED[64]; ///< For iMX RT10xx, but not used by LPC18XX/LPC43XX
//------------- Capability Registers-------------//
volatile uint8_t CAPLENGTH; ///< Capability Registers Length
volatile uint8_t TU_RESERVED[1];
volatile uint16_t HCIVERSION; ///< Host Controller Interface Version
volatile uint32_t HCSPARAMS; ///< Host Controller Structural Parameters
volatile uint32_t HCCPARAMS; ///< Host Controller Capability Parameters
volatile uint32_t TU_RESERVED[5];
volatile uint16_t DCIVERSION; ///< Device Controller Interface Version
volatile uint8_t TU_RESERVED[2];
volatile uint32_t DCCPARAMS; ///< Device Controller Capability Parameters
volatile uint32_t TU_RESERVED[6];
//------------- Operational Registers -------------//
volatile uint32_t USBCMD; ///< USB Command Register
volatile uint32_t USBSTS; ///< USB Status Register
volatile uint32_t USBINTR; ///< Interrupt Enable Register
volatile uint32_t FRINDEX; ///< USB Frame Index
volatile uint32_t TU_RESERVED;
volatile uint32_t DEVICEADDR; ///< Device Address
volatile uint32_t ENDPTLISTADDR; ///< Endpoint List Address
volatile uint32_t TU_RESERVED;
volatile uint32_t BURSTSIZE; ///< Programmable Burst Size
volatile uint32_t TXFILLTUNING; ///< TX FIFO Fill Tuning
uint32_t TU_RESERVED[4];
volatile uint32_t ENDPTNAK; ///< Endpoint NAK
volatile uint32_t ENDPTNAKEN; ///< Endpoint NAK Enable
volatile uint32_t TU_RESERVED;
volatile uint32_t PORTSC1; ///< Port Status & Control
volatile uint32_t TU_RESERVED[7];
volatile uint32_t OTGSC; ///< On-The-Go Status & control
volatile uint32_t USBMODE; ///< USB Device Mode
volatile uint32_t ENDPTSETUPSTAT; ///< Endpoint Setup Status
volatile uint32_t ENDPTPRIME; ///< Endpoint Prime
volatile uint32_t ENDPTFLUSH; ///< Endpoint Flush
volatile uint32_t ENDPTSTAT; ///< Endpoint Status
volatile uint32_t ENDPTCOMPLETE; ///< Endpoint Complete
volatile uint32_t ENDPTCTRL[8]; ///< Endpoint Control 0 - 7
} ci_hs_regs_t;
typedef struct
{
uint32_t reg_base;
uint32_t irqnum;
uint8_t ep_count; // Max bi-directional Endpoints
}ci_hs_controller_t;
#ifdef __cplusplus
}
#endif
#endif /* CI_HS_TYPE_H_ */
+637
View File
@@ -0,0 +1,637 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 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.
*/
#include "tusb_option.h"
#include "device/dcd_attr.h"
#if TUSB_OPT_DEVICE_ENABLED && defined(DCD_ATTR_CONTROLLER_CHIPIDEA_HS)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "device/dcd.h"
#include "ci_hs_type.h"
#if CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX
#include "ci_hs_imxrt.h"
#elif TU_CHECK_MCU(OPT_MCU_LPC18XX, OPT_MCU_LPC43XX)
#include "ci_hs_lpc18_43.h"
#else
#error "Unsupported MCUs"
#endif
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
#define CI_HS_REG(_port) ((ci_hs_regs_t*) _ci_controller[_port].reg_base)
#if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1
#define CleanInvalidateDCache_by_Addr SCB_CleanInvalidateDCache_by_Addr
#else
#define CleanInvalidateDCache_by_Addr(_addr, _dsize)
#endif
// ENDPTCTRL
enum {
ENDPTCTRL_STALL = TU_BIT(0),
ENDPTCTRL_TOGGLE_INHIBIT = TU_BIT(5), // used for test only
ENDPTCTRL_TOGGLE_RESET = TU_BIT(6),
ENDPTCTRL_ENABLE = TU_BIT(7)
};
enum {
ENDPTCTRL_TYPE_POS = 2, // Endpoint type is 2-bit field
};
// USBSTS, USBINTR
enum {
INTR_USB = TU_BIT(0),
INTR_ERROR = TU_BIT(1),
INTR_PORT_CHANGE = TU_BIT(2),
INTR_RESET = TU_BIT(6),
INTR_SOF = TU_BIT(7),
INTR_SUSPEND = TU_BIT(8),
INTR_NAK = TU_BIT(16)
};
// Queue Transfer Descriptor
typedef struct
{
// Word 0: Next QTD Pointer
uint32_t next; ///< Next link pointer This field contains the physical memory address of the next dTD to be processed
// Word 1: qTQ Token
uint32_t : 3 ;
volatile uint32_t xact_err : 1 ;
uint32_t : 1 ;
volatile uint32_t buffer_err : 1 ;
volatile uint32_t halted : 1 ;
volatile uint32_t active : 1 ;
uint32_t : 2 ;
uint32_t iso_mult_override : 2 ; ///< This field can be used for transmit ISOs to override the MULT field in the dQH. This field must be zero for all packet types that are not transmit-ISO.
uint32_t : 3 ;
uint32_t int_on_complete : 1 ;
volatile uint32_t total_bytes : 15 ;
uint32_t : 1 ;
// Word 2-6: Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page
uint32_t buffer[5]; ///< buffer1 has frame_n for TODO Isochronous
//--------------------------------------------------------------------+
// TD is 32 bytes aligned but occupies only 28 bytes
// Therefore there are 4 bytes padding that we can use.
//--------------------------------------------------------------------+
uint16_t expected_bytes;
uint8_t reserved[2];
} dcd_qtd_t;
TU_VERIFY_STATIC( sizeof(dcd_qtd_t) == 32, "size is not correct");
// Queue Head
typedef struct
{
// Word 0: Capabilities and Characteristics
uint32_t : 15 ; ///< Number of packets executed per transaction descriptor 00 - Execute N transactions as demonstrated by the USB variable length protocol where N is computed using Max_packet_length and the Total_bytes field in the dTD. 01 - Execute one transaction 10 - Execute two transactions 11 - Execute three transactions Remark: Non-isochronous endpoints must set MULT = 00. Remark: Isochronous endpoints must set MULT = 01, 10, or 11 as needed.
uint32_t int_on_setup : 1 ; ///< Interrupt on setup This bit is used on control type endpoints to indicate if USBINT is set in response to a setup being received.
uint32_t max_packet_size : 11 ; ///< Endpoint's wMaxPacketSize
uint32_t : 2 ;
uint32_t zero_length_termination : 1 ; ///< This bit is used for non-isochronous endpoints to indicate when a zero-length packet is received to terminate transfers in case the total transfer length is “multiple”. 0 - Enable zero-length packet to terminate transfers equal to a multiple of Max_packet_length (default). 1 - Disable zero-length packet on transfers that are equal in length to a multiple Max_packet_length.
uint32_t iso_mult : 2 ; ///<
// Word 1: Current qTD Pointer
volatile uint32_t qtd_addr;
// Word 2-9: Transfer Overlay
volatile dcd_qtd_t qtd_overlay;
// Word 10-11: Setup request (control OUT only)
volatile tusb_control_request_t setup_request;
//--------------------------------------------------------------------+
// QHD is 64 bytes aligned but occupies only 48 bytes
// Therefore there are 16 bytes padding that we can use.
//--------------------------------------------------------------------+
tu_fifo_t * ff;
uint8_t reserved[12];
} dcd_qhd_t;
TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct");
//--------------------------------------------------------------------+
// Variables
//--------------------------------------------------------------------+
#define QTD_NEXT_INVALID 0x01
typedef struct {
// Must be at 2K alignment
// Each endpoint with direction (IN/OUT) occupies a queue head
// for portability, TinyUSB only queue 1 TD for each Qhd
dcd_qhd_t qhd[DCD_ATTR_ENDPOINT_MAX][2] TU_ATTR_ALIGNED(64);
dcd_qtd_t qtd[DCD_ATTR_ENDPOINT_MAX][2] TU_ATTR_ALIGNED(32);
}dcd_data_t;
CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048)
static dcd_data_t _dcd_data;
//--------------------------------------------------------------------+
// Controller API
//--------------------------------------------------------------------+
/// follows LPC43xx User Manual 23.10.3
static void bus_reset(uint8_t rhport)
{
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
// The reset value for all endpoint types is the control endpoint. If one endpoint
// direction is enabled and the paired endpoint of opposite direction is disabled, then the
// endpoint type of the unused direction must be changed from the control type to any other
// type (e.g. bulk). Leaving an un-configured endpoint control will cause undefined behavior
// for the data PID tracking on the active endpoint.
for( uint8_t i=1; i < _ci_controller[rhport].ep_count; i++)
{
dcd_reg->ENDPTCTRL[i] = (TUSB_XFER_BULK << ENDPTCTRL_TYPE_POS) | (TUSB_XFER_BULK << (16+ENDPTCTRL_TYPE_POS));
}
//------------- Clear All Registers -------------//
dcd_reg->ENDPTNAK = dcd_reg->ENDPTNAK;
dcd_reg->ENDPTNAKEN = 0;
dcd_reg->USBSTS = dcd_reg->USBSTS;
dcd_reg->ENDPTSETUPSTAT = dcd_reg->ENDPTSETUPSTAT;
dcd_reg->ENDPTCOMPLETE = dcd_reg->ENDPTCOMPLETE;
while (dcd_reg->ENDPTPRIME) {}
dcd_reg->ENDPTFLUSH = 0xFFFFFFFF;
while (dcd_reg->ENDPTFLUSH) {}
// read reset bit in portsc
//------------- Queue Head & Queue TD -------------//
tu_memclr(&_dcd_data, sizeof(dcd_data_t));
//------------- Set up Control Endpoints (0 OUT, 1 IN) -------------//
_dcd_data.qhd[0][0].zero_length_termination = _dcd_data.qhd[0][1].zero_length_termination = 1;
_dcd_data.qhd[0][0].max_packet_size = _dcd_data.qhd[0][1].max_packet_size = CFG_TUD_ENDPOINT0_SIZE;
_dcd_data.qhd[0][0].qtd_overlay.next = _dcd_data.qhd[0][1].qtd_overlay.next = QTD_NEXT_INVALID;
_dcd_data.qhd[0][0].int_on_setup = 1; // OUT only
}
void dcd_init(uint8_t rhport)
{
tu_memclr(&_dcd_data, sizeof(dcd_data_t));
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
// Reset controller
dcd_reg->USBCMD |= USBCMD_RESET;
while( dcd_reg->USBCMD & USBCMD_RESET ) {}
// Set mode to device, must be set immediately after reset
dcd_reg->USBMODE = USBMODE_CM_DEVICE;
dcd_reg->OTGSC = OTGSC_VBUS_DISCHARGE | OTGSC_OTG_TERMINATION;
#if !TUD_OPT_HIGH_SPEED
dcd_reg->PORTSC1 = PORTSC1_FORCE_FULL_SPEED;
#endif
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
dcd_reg->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment
dcd_reg->USBSTS = dcd_reg->USBSTS;
dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_SUSPEND;
dcd_reg->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0
dcd_reg->USBCMD |= USBCMD_RUN_STOP; // Connect
}
void dcd_int_enable(uint8_t rhport)
{
CI_DCD_INT_ENABLE(rhport);
}
void dcd_int_disable(uint8_t rhport)
{
CI_DCD_INT_DISABLE(rhport);
}
void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
{
// Response with status first before changing device address
dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0);
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
dcd_reg->DEVICEADDR = (dev_addr << 25) | TU_BIT(24);
}
void dcd_remote_wakeup(uint8_t rhport)
{
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
dcd_reg->PORTSC1 |= PORTSC1_FORCE_PORT_RESUME;
}
void dcd_connect(uint8_t rhport)
{
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
dcd_reg->USBCMD |= USBCMD_RUN_STOP;
}
void dcd_disconnect(uint8_t rhport)
{
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
dcd_reg->USBCMD &= ~USBCMD_RUN_STOP;
}
//--------------------------------------------------------------------+
// HELPER
//--------------------------------------------------------------------+
static void qtd_init(dcd_qtd_t* p_qtd, void * data_ptr, uint16_t total_bytes)
{
// Force the CPU to flush the buffer. We increase the size by 31 because the call aligns the
// address to 32-byte boundaries. Buffer must be word aligned
CleanInvalidateDCache_by_Addr((uint32_t*) tu_align((uint32_t) data_ptr, 4), total_bytes + 31);
tu_memclr(p_qtd, sizeof(dcd_qtd_t));
p_qtd->next = QTD_NEXT_INVALID;
p_qtd->active = 1;
p_qtd->total_bytes = p_qtd->expected_bytes = total_bytes;
p_qtd->int_on_complete = true;
if (data_ptr != NULL)
{
p_qtd->buffer[0] = (uint32_t) data_ptr;
uint32_t const bufend = p_qtd->buffer[0] + total_bytes;
for(uint8_t i=1; i<5; i++)
{
uint32_t const next_page = tu_align4k( p_qtd->buffer[i-1] ) + 4096;
if ( bufend <= next_page ) break;
p_qtd->buffer[i] = next_page;
// TODO page[1] FRAME_N for ISO transfer
}
}
}
//--------------------------------------------------------------------+
// DCD Endpoint Port
//--------------------------------------------------------------------+
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
dcd_reg->ENDPTCTRL[epnum] |= ENDPTCTRL_STALL << (dir ? 16 : 0);
// flush to abort any primed buffer
dcd_reg->ENDPTFLUSH = TU_BIT(epnum + (dir ? 16 : 0));
}
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
// data toggle also need to be reset
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
dcd_reg->ENDPTCTRL[epnum] |= ENDPTCTRL_TOGGLE_RESET << ( dir ? 16 : 0 );
dcd_reg->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_STALL << ( dir ? 16 : 0));
}
bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
{
uint8_t const epnum = tu_edpt_number(p_endpoint_desc->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
// Must not exceed max endpoint number
TU_ASSERT( epnum < _ci_controller[rhport].ep_count );
//------------- Prepare Queue Head -------------//
dcd_qhd_t * p_qhd = &_dcd_data.qhd[epnum][dir];
tu_memclr(p_qhd, sizeof(dcd_qhd_t));
p_qhd->zero_length_termination = 1;
p_qhd->max_packet_size = tu_edpt_packet_size(p_endpoint_desc);
if (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS)
{
p_qhd->iso_mult = 1;
}
p_qhd->qtd_overlay.next = QTD_NEXT_INVALID;
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
// Enable EP Control
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
uint32_t const epctrl = (p_endpoint_desc->bmAttributes.xfer << ENDPTCTRL_TYPE_POS) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET;
if ( dir == TUSB_DIR_OUT )
{
dcd_reg->ENDPTCTRL[epnum] = (dcd_reg->ENDPTCTRL[epnum] & 0xFFFF0000u) | epctrl;
}else
{
dcd_reg->ENDPTCTRL[epnum] = (dcd_reg->ENDPTCTRL[epnum] & 0x0000FFFFu) | (epctrl << 16);
}
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
// Disable all non-control endpoints
for( uint8_t epnum=1; epnum < _ci_controller[rhport].ep_count; epnum++)
{
_dcd_data.qhd[epnum][TUSB_DIR_OUT].qtd_overlay.halted = 1;
_dcd_data.qhd[epnum][TUSB_DIR_IN ].qtd_overlay.halted = 1;
dcd_reg->ENDPTFLUSH = TU_BIT(epnum) | TU_BIT(epnum+16);
dcd_reg->ENDPTCTRL[epnum] = (TUSB_XFER_BULK << ENDPTCTRL_TYPE_POS) | (TUSB_XFER_BULK << (16+ENDPTCTRL_TYPE_POS));
}
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
_dcd_data.qhd[epnum][dir].qtd_overlay.halted = 1;
// Flush EP
uint32_t const flush_mask = TU_BIT(epnum + (dir ? 16 : 0));
dcd_reg->ENDPTFLUSH = flush_mask;
while(dcd_reg->ENDPTFLUSH & flush_mask);
// Clear EP enable
dcd_reg->ENDPTCTRL[epnum] &=~(ENDPTCTRL_ENABLE << (dir ? 16 : 0));
}
static void qhd_start_xfer(uint8_t rhport, uint8_t epnum, uint8_t dir)
{
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
dcd_qhd_t* p_qhd = &_dcd_data.qhd[epnum][dir];
dcd_qtd_t* p_qtd = &_dcd_data.qtd[epnum][dir];
p_qhd->qtd_overlay.halted = false; // clear any previous error
p_qhd->qtd_overlay.next = (uint32_t) p_qtd; // link qtd to qhd
// flush cache
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
if ( epnum == 0 )
{
// follows UM 24.10.8.1.1 Setup packet handling using setup lockout mechanism
// wait until ENDPTSETUPSTAT before priming data/status in response TODO add time out
while(dcd_reg->ENDPTSETUPSTAT & TU_BIT(0)) {}
}
// start transfer
dcd_reg->ENDPTPRIME = TU_BIT(epnum + (dir ? 16 : 0));
}
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);
dcd_qhd_t* p_qhd = &_dcd_data.qhd[epnum][dir];
dcd_qtd_t* p_qtd = &_dcd_data.qtd[epnum][dir];
// Prepare qtd
qtd_init(p_qtd, buffer, total_bytes);
// Start qhd transfer
p_qhd->ff = NULL;
qhd_start_xfer(rhport, epnum, dir);
return true;
}
// fifo has to be aligned to 4k boundary
bool dcd_edpt_xfer_fifo (uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_qhd_t * p_qhd = &_dcd_data.qhd[epnum][dir];
dcd_qtd_t * p_qtd = &_dcd_data.qtd[epnum][dir];
tu_fifo_buffer_info_t fifo_info;
if (dir)
{
tu_fifo_get_read_info(ff, &fifo_info);
} else
{
tu_fifo_get_write_info(ff, &fifo_info);
}
if ( fifo_info.len_lin >= total_bytes )
{
// Linear length is enough for this transfer
qtd_init(p_qtd, fifo_info.ptr_lin, total_bytes);
}
else
{
// linear part is not enough
// prepare TD up to linear length
qtd_init(p_qtd, fifo_info.ptr_lin, fifo_info.len_lin);
if ( !tu_offset4k((uint32_t) fifo_info.ptr_wrap) && !tu_offset4k(tu_fifo_depth(ff)) )
{
// If buffer is aligned to 4K & buffer size is multiple of 4K
// We can make use of buffer page array to also combine the linear + wrapped length
p_qtd->total_bytes = p_qtd->expected_bytes = total_bytes;
for(uint8_t i = 1, page = 0; i < 5; i++)
{
// pick up buffer array where linear ends
if (p_qtd->buffer[i] == 0)
{
p_qtd->buffer[i] = (uint32_t) fifo_info.ptr_wrap + 4096 * page;
page++;
}
}
CleanInvalidateDCache_by_Addr((uint32_t*) tu_align((uint32_t) fifo_info.ptr_wrap, 4), total_bytes - fifo_info.len_wrap + 31);
}
else
{
// TODO we may need to carry the wrapped length after the linear part complete
// for now only transfer up to linear part
}
}
// Start qhd transfer
p_qhd->ff = ff;
qhd_start_xfer(rhport, epnum, dir);
return true;
}
//--------------------------------------------------------------------+
// ISR
//--------------------------------------------------------------------+
static void process_edpt_complete_isr(uint8_t rhport, uint8_t epnum, uint8_t dir)
{
dcd_qhd_t * p_qhd = &_dcd_data.qhd[epnum][dir];
dcd_qtd_t * p_qtd = &_dcd_data.qtd[epnum][dir];
uint8_t result = p_qtd->halted ? XFER_RESULT_STALLED :
( p_qtd->xact_err || p_qtd->buffer_err ) ? XFER_RESULT_FAILED : XFER_RESULT_SUCCESS;
if ( result != XFER_RESULT_SUCCESS )
{
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
// flush to abort error buffer
dcd_reg->ENDPTFLUSH = TU_BIT(epnum + (dir ? 16 : 0));
}
uint16_t const xferred_bytes = p_qtd->expected_bytes - p_qtd->total_bytes;
if (p_qhd->ff)
{
if (dir == TUSB_DIR_IN)
{
tu_fifo_advance_read_pointer(p_qhd->ff, xferred_bytes);
} else
{
tu_fifo_advance_write_pointer(p_qhd->ff, xferred_bytes);
}
}
// only number of bytes in the IOC qtd
dcd_event_xfer_complete(rhport, tu_edpt_addr(epnum, dir), xferred_bytes, result, true);
}
void dcd_int_handler(uint8_t rhport)
{
ci_hs_regs_t* dcd_reg = CI_HS_REG(rhport);
uint32_t const int_enable = dcd_reg->USBINTR;
uint32_t const int_status = dcd_reg->USBSTS & int_enable;
dcd_reg->USBSTS = int_status; // Acknowledge handled interrupt
// disabled interrupt sources
if (int_status == 0) return;
// Set if the port controller enters the full or high-speed operational state.
// either from Bus Reset or Suspended state
if (int_status & INTR_PORT_CHANGE)
{
// TU_LOG2("PortChange %08lx\r\n", dcd_reg->PORTSC1);
// Reset interrupt is not enabled, we manually check if Port Change is due
// to connection / disconnection
if ( dcd_reg->USBSTS & INTR_RESET )
{
dcd_reg->USBSTS = INTR_RESET;
if (dcd_reg->PORTSC1 & PORTSC1_CURRENT_CONNECT_STATUS)
{
uint32_t const speed = (dcd_reg->PORTSC1 & PORTSC1_PORT_SPEED) >> PORTSC1_PORT_SPEED_POS;
bus_reset(rhport);
dcd_event_bus_reset(rhport, (tusb_speed_t) speed, true);
}else
{
dcd_event_bus_signal(rhport, DCD_EVENT_UNPLUGGED, true);
}
}
else
{
// Triggered by resuming from suspended state
if ( !(dcd_reg->PORTSC1 & PORTSC1_SUSPEND) )
{
dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true);
}
}
}
if (int_status & INTR_SUSPEND)
{
// TU_LOG2("Suspend %08lx\r\n", dcd_reg->PORTSC1);
if (dcd_reg->PORTSC1 & PORTSC1_SUSPEND)
{
// Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration.
// Skip suspend event if we are not addressed
if ((dcd_reg->DEVICEADDR >> 25) & 0x0f)
{
dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true);
}
}
}
if (int_status & INTR_USB)
{
// Make sure we read the latest version of _dcd_data.
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
uint32_t const edpt_complete = dcd_reg->ENDPTCOMPLETE;
dcd_reg->ENDPTCOMPLETE = edpt_complete; // acknowledge
if (dcd_reg->ENDPTSETUPSTAT)
{
//------------- Set up Received -------------//
// 23.10.10.2 Operational model for setup transfers
dcd_reg->ENDPTSETUPSTAT = dcd_reg->ENDPTSETUPSTAT;
dcd_event_setup_received(rhport, (uint8_t*)(uintptr_t) &_dcd_data.qhd[0][0].setup_request, true);
}
// 23.10.12.3 Failed QTD also get ENDPTCOMPLETE set
// nothing to do, we will submit xfer as error to usbd
// if (int_status & INTR_ERROR) { }
if ( edpt_complete )
{
for(uint8_t epnum = 0; epnum < DCD_ATTR_ENDPOINT_MAX; epnum++)
{
if ( tu_bit_test(edpt_complete, epnum) ) process_edpt_complete_isr(rhport, epnum, TUSB_DIR_OUT);
if ( tu_bit_test(edpt_complete, epnum+16) ) process_edpt_complete_isr(rhport, epnum, TUSB_DIR_IN);
}
}
}
if (int_status & INTR_SOF)
{
dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true);
}
}
#endif
+93
View File
@@ -0,0 +1,93 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 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.
*/
#include "tusb_option.h"
// Chipidea Highspeed USB IP implement EHCI for host functionality
#if TUSB_OPT_HOST_ENABLED && \
(CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "common/tusb_common.h"
#include "portable/ehci/ehci_api.h"
#include "ci_hs_type.h"
#if CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX
#include "ci_hs_imxrt.h"
#elif TU_CHECK_MCU(OPT_MCU_LPC18XX, OPT_MCU_LPC43XX)
#include "ci_hs_lpc18_43.h"
#else
#error "Unsupported MCUs"
#endif
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
#define CI_HS_REG(_port) ((ci_hs_regs_t*) _ci_controller[_port].reg_base)
//--------------------------------------------------------------------+
// Controller API
//--------------------------------------------------------------------+
bool hcd_init(uint8_t rhport)
{
ci_hs_regs_t* hcd_reg = CI_HS_REG(rhport);
// Reset controller
hcd_reg->USBCMD |= USBCMD_RESET;
while( hcd_reg->USBCMD & USBCMD_RESET ) {}
// Set mode to device, must be set immediately after reset
#if CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX
// LPC18XX/43XX need to set VBUS Power Select to HIGH
// RHPORT1 is fullspeed only (need external PHY for Highspeed)
hcd_reg->USBMODE = USBMODE_CM_HOST | USBMODE_VBUS_POWER_SELECT;
if (rhport == 1) hcd_reg->PORTSC1 |= PORTSC1_FORCE_FULL_SPEED;
#else
hcd_reg->USBMODE = USBMODE_CM_HOST;
#endif
// FIXME force full speed, still have issue with Highspeed enumeration
hcd_reg->PORTSC1 |= PORTSC1_FORCE_FULL_SPEED;
return ehci_init(rhport, (uint32_t) &hcd_reg->CAPLENGTH, (uint32_t) &hcd_reg->USBCMD);
}
void hcd_int_enable(uint8_t rhport)
{
CI_HCD_INT_ENABLE(rhport);
}
void hcd_int_disable(uint8_t rhport)
{
CI_HCD_INT_DISABLE(rhport);
}
#endif
+229 -93
View File
@@ -60,10 +60,17 @@
#define EP_MAX 4
// Node functional states
#define NFSR_NODE_RESET 0
#define NFSR_NODE_RESUME 1
#define NFSR_NODE_OPERATIONAL 2
#define NFSR_NODE_SUSPEND 3
// Those two following states are added to allow going out of sleep mode
// using frame interrupt. On remove wakeup RESUME state must be kept for
// at least 1ms. It is accomplished by using FRAME interrupt that goes
// through those two fake states before entering OPERATIONAL state.
#define NFSR_NODE_WAKING (0x10 | (NFSR_NODE_RESUME))
#define NFSR_NODE_WAKING2 (0x20 | (NFSR_NODE_RESUME))
static TU_ATTR_ALIGNED(4) uint8_t _setup_packet[8];
@@ -133,7 +140,7 @@ typedef struct
__IOM uint32_t USB_RXC2_REG; /*!< (@ 0x000000DC) Receive Command Register 2 */
__IOM uint32_t USB_RXC3_REG; /*!< (@ 0x000000FC) Receive Command Register 3 */
};
} EPx_REGS;
} volatile EPx_REGS;
#define EP_REGS(first_ep_reg) (EPx_REGS*)(&USB->first_ep_reg)
@@ -193,8 +200,14 @@ typedef struct
#define REG_CLR_BIT(reg, field) USB->reg &= ~USB_ ## reg ## _ ## field ## _Msk
#define REG_SET_VAL(reg, field, val) USB->reg = (USB->reg & ~USB_ ## reg ## _ ## field ## _Msk) | (val << USB_ ## reg ## _ ## field ## _Pos)
static EPx_REGS * const ep_regs[EP_MAX] = {
EP_REGS(USB_EPC0_REG),
EP_REGS(USB_EPC1_REG),
EP_REGS(USB_EPC3_REG),
EP_REGS(USB_EPC5_REG),
};
typedef struct {
EPx_REGS * regs;
uint8_t * buffer;
// Total length of current transfer
uint16_t total_len;
@@ -217,22 +230,24 @@ typedef struct {
static struct
{
bool vbus_present;
bool in_reset;
bool init_called;
uint8_t nfsr;
xfer_ctl_t xfer_status[EP_MAX][2];
// Endpoints that use DMA, one for each direction
uint8_t dma_ep[2];
} _dcd =
{
.vbus_present = false,
.xfer_status =
{
{ { .regs = EP_REGS(USB_EPC0_REG) }, { .regs = EP_REGS(USB_EPC0_REG) } },
{ { .regs = EP_REGS(USB_EPC1_REG) }, { .regs = EP_REGS(USB_EPC1_REG) } },
{ { .regs = EP_REGS(USB_EPC3_REG) }, { .regs = EP_REGS(USB_EPC3_REG) } },
{ { .regs = EP_REGS(USB_EPC5_REG) }, { .regs = EP_REGS(USB_EPC5_REG) } },
}
.init_called = false,
};
// Converts xfer pointer to epnum (0,1,2,3) regardless of xfer direction
#define XFER_EPNUM(xfer) ((xfer - &_dcd.xfer_status[0][0]) >> 1)
// Converts xfer pinter to EPx_REGS pointer (returns same pointer for IN and OUT with same endpoint number)
#define XFER_REGS(xfer) ep_regs[XFER_EPNUM(xfer)]
// Converts epnum (0,1,2,3) to EPx_REGS pointer
#define EPNUM_REGS(epnum) ep_regs[epnum]
// Two endpoint 0 descriptor definition for unified dcd_edpt_open()
static const tusb_desc_endpoint_t ep0OUT_desc =
{
@@ -241,7 +256,7 @@ static const tusb_desc_endpoint_t ep0OUT_desc =
.bEndpointAddress = 0x00,
.bmAttributes = { .xfer = TUSB_XFER_CONTROL },
.wMaxPacketSize = { .size = CFG_TUD_ENDPOINT0_SIZE },
.wMaxPacketSize = CFG_TUD_ENDPOINT0_SIZE,
.bInterval = 0
};
@@ -252,18 +267,27 @@ static const tusb_desc_endpoint_t ep0IN_desc =
.bEndpointAddress = 0x80,
.bmAttributes = { .xfer = TUSB_XFER_CONTROL },
.wMaxPacketSize = { .size = CFG_TUD_ENDPOINT0_SIZE },
.wMaxPacketSize = CFG_TUD_ENDPOINT0_SIZE,
.bInterval = 0
};
#define XFER_CTL_BASE(_ep, _dir) &_dcd.xfer_status[_ep][_dir]
static void set_nfsr(uint8_t val)
{
_dcd.nfsr = val;
// Write only lower 2 bits to register, higher bits are used
// to count down till OPERATIONAL state can be entered when
// remote wakeup activated.
USB->USB_NFSR_REG = val & 3;
}
static void fill_tx_fifo(xfer_ctl_t * xfer)
{
int left_to_send;
uint8_t const *src;
EPx_REGS *regs = xfer->regs;
uint8_t const epnum = tu_edpt_number(xfer->ep_addr);
EPx_REGS *regs = EPNUM_REGS(epnum);
src = &xfer->buffer[xfer->transferred];
left_to_send = xfer->total_len - xfer->transferred;
@@ -291,7 +315,7 @@ static void fill_tx_fifo(xfer_ctl_t * xfer)
}
else
{
xfer->regs->txc &= ~USB_USB_TXC1_REG_USB_TFWL_Msk;
regs->txc &= ~USB_USB_TXC1_REG_USB_TFWL_Msk;
USB->USB_FWMSK_REG &= ~(1 << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_TXWARN31_Pos));
// Whole packet already in fifo, no need to refill it later. Mark last.
regs->txc |= USB_USB_TXC1_REG_USB_LAST_Msk;
@@ -332,30 +356,31 @@ static void start_rx_packet(xfer_ctl_t *xfer)
uint8_t const epnum = tu_edpt_number(xfer->ep_addr);
uint16_t remaining = xfer->total_len - xfer->transferred;
uint16_t size = tu_min16(remaining, xfer->max_packet_size);
EPx_REGS *regs = XFER_REGS(xfer);
xfer->last_packet_size = 0;
if (xfer->max_packet_size > FIFO_SIZE && remaining > FIFO_SIZE)
{
if (try_allocate_dma(epnum, TUSB_DIR_OUT))
{
start_rx_dma(&xfer->regs->rxd, xfer->buffer + xfer->transferred, size);
start_rx_dma(&regs->rxd, xfer->buffer + xfer->transferred, size);
}
else
{
// Other endpoint is using DMA in that direction, fall back to interrupts.
// For endpoint size greater then FIFO size enable FIFO level warning interrupt
// when FIFO has less then 17 bytes free.
xfer->regs->rxc |= USB_USB_RXC1_REG_USB_RFWL_Msk;
// For endpoint size greater than FIFO size enable FIFO level warning interrupt
// when FIFO has less than 17 bytes free.
regs->rxc |= USB_USB_RXC1_REG_USB_RFWL_Msk;
USB->USB_FWMSK_REG |= 1 << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_RXWARN31_Pos);
}
}
else if (epnum != 0)
{
// If max_packet_size would fit in FIFO no need for FIFO level warning interrupt.
xfer->regs->rxc &= ~USB_USB_RXC1_REG_USB_RFWL_Msk;
regs->rxc &= ~USB_USB_RXC1_REG_USB_RFWL_Msk;
USB->USB_FWMSK_REG &= ~(1 << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_RXWARN31_Pos));
}
xfer->regs->rxc |= USB_USB_RXC1_REG_USB_RX_EN_Msk;
regs->rxc |= USB_USB_RXC1_REG_USB_RX_EN_Msk;
}
static void start_tx_dma(void *src, volatile void *dst, uint16_t size)
@@ -374,13 +399,13 @@ static void start_tx_packet(xfer_ctl_t *xfer)
uint8_t const epnum = tu_edpt_number(xfer->ep_addr);
uint16_t remaining = xfer->total_len - xfer->transferred;
uint16_t size = tu_min16(remaining, xfer->max_packet_size);
EPx_REGS *regs = xfer->regs;
EPx_REGS *regs = EPNUM_REGS(epnum);
xfer->last_packet_size = 0;
regs->txc = USB_USB_TXC1_REG_USB_FLUSH_Msk;
regs->txc = USB_USB_TXC1_REG_USB_IGN_ISOMSK_Msk;
if (xfer->data1) xfer->regs->txc |= USB_USB_TXC1_REG_USB_TOGGLE_TX_Msk;
if (xfer->data1) regs->txc |= USB_USB_TXC1_REG_USB_TOGGLE_TX_Msk;
if (xfer->max_packet_size > FIFO_SIZE && remaining > FIFO_SIZE && try_allocate_dma(epnum, TUSB_DIR_IN))
{
@@ -395,9 +420,9 @@ static void start_tx_packet(xfer_ctl_t *xfer)
regs->txc |= USB_USB_TXC1_REG_USB_TX_EN_Msk;
}
static void read_rx_fifo(xfer_ctl_t *xfer, uint16_t bytes_in_fifo)
static uint16_t read_rx_fifo(xfer_ctl_t *xfer, uint16_t bytes_in_fifo)
{
EPx_REGS *regs = xfer->regs;
EPx_REGS *regs = XFER_REGS(xfer);
uint16_t remaining = xfer->total_len - xfer->transferred - xfer->last_packet_size;
uint16_t receive_this_time = bytes_in_fifo;
@@ -408,6 +433,8 @@ static void read_rx_fifo(xfer_ctl_t *xfer, uint16_t bytes_in_fifo)
for (int i = 0; i < receive_this_time; ++i) buf[i] = regs->rxd;
xfer->last_packet_size += receive_this_time;
return bytes_in_fifo - receive_this_time;
}
static void handle_ep0_rx(void)
@@ -467,7 +494,7 @@ static void handle_ep0_tx(void)
{
uint32_t txs0;
xfer_ctl_t *xfer = XFER_CTL_BASE(0, TUSB_DIR_IN);
EPx_REGS *regs = xfer->regs;
EPx_REGS *regs = XFER_REGS(xfer);
txs0 = regs->USB_TXS0_REG;
@@ -501,7 +528,7 @@ static void handle_epx_rx_ev(uint8_t ep)
int fifo_bytes;
xfer_ctl_t *xfer = XFER_CTL_BASE(ep, TUSB_DIR_OUT);
EPx_REGS *regs = xfer->regs;
EPx_REGS *regs = EPNUM_REGS(ep);
do
{
@@ -537,7 +564,7 @@ static void handle_epx_rx_ev(uint8_t ep)
// FIFO maybe empty if DMA read it before or it's final iteration and function already read all that was to read.
if (fifo_bytes > 0)
{
read_rx_fifo(xfer, fifo_bytes);
fifo_bytes = read_rx_fifo(xfer, fifo_bytes);
}
if (GET_BIT(rxs, USB_USB_RXS1_REG_USB_RX_LAST))
{
@@ -552,6 +579,13 @@ static void handle_epx_rx_ev(uint8_t ep)
xfer->transferred += xfer->last_packet_size;
if (xfer->total_len == xfer->transferred || xfer->last_packet_size < xfer->max_packet_size || xfer->iso)
{
if (fifo_bytes)
{
// There are extra bytes in the FIFO just flush them
regs->rxc |= USB_USB_RXC1_REG_USB_FLUSH_Msk;
fifo_bytes = 0;
}
dcd_event_xfer_complete(0, xfer->ep_addr, xfer->transferred, XFER_RESULT_SUCCESS, true);
}
else
@@ -580,7 +614,7 @@ static void handle_epx_tx_ev(xfer_ctl_t *xfer)
{
uint8_t const epnum = tu_edpt_number(xfer->ep_addr);
uint32_t txs;
EPx_REGS *regs = xfer->regs;
EPx_REGS *regs = EPNUM_REGS(epnum);
txs = regs->txs;
@@ -607,6 +641,13 @@ static void handle_epx_tx_ev(xfer_ctl_t *xfer)
return;
}
}
else if (regs->epc_in & USB_USB_EPC1_REG_USB_STALL_Msk)
{
// TX_DONE also indicates that STALL packet was just sent, there is
// no point to put anything into transmit FIFO. It could result in
// empty packet being scheduled.
return;
}
}
if (txs & USB_USB_TXS1_REG_USB_TX_URUN_Msk)
{
@@ -626,60 +667,81 @@ static void handle_tx_ev(void)
handle_epx_tx_ev(XFER_CTL_BASE(3, TUSB_DIR_IN));
}
static uint32_t check_reset_end(uint32_t alt_ev)
{
if (_dcd.nfsr == NFSR_NODE_RESET)
{
if (GET_BIT(alt_ev, USB_USB_ALTEV_REG_USB_RESET))
{
// Could be still in reset, but since USB_M_RESET is disabled it can
// be also old reset state that was not cleared yet.
// If (after reading USB_ALTEV_REG register again) bit is cleared
// reset state just ended.
// Keep non-reset bits combined from two previous ALTEV read and
// one from the next line.
alt_ev = (alt_ev & ~USB_USB_ALTEV_REG_USB_RESET_Msk) | USB->USB_ALTEV_REG;
}
if (GET_BIT(alt_ev, USB_USB_ALTEV_REG_USB_RESET) == 0)
{
USB->USB_ALTMSK_REG = USB_USB_ALTMSK_REG_USB_M_RESET_Msk |
USB_USB_ALTEV_REG_USB_SD3_Msk;
set_nfsr(NFSR_NODE_OPERATIONAL);
dcd_edpt_open(0, &ep0OUT_desc);
dcd_edpt_open(0, &ep0IN_desc);
}
}
return alt_ev;
}
static void handle_bus_reset(void)
{
uint32_t alt_ev;
USB->USB_NFSR_REG = 0;
USB->USB_FAR_REG = 0x80;
USB->USB_ALTMSK_REG = 0;
USB->USB_NFSR_REG = NFSR_NODE_RESET;
USB->USB_TXMSK_REG = 0;
USB->USB_RXMSK_REG = 0;
(void)USB->USB_ALTEV_REG;
_dcd.in_reset = true;
set_nfsr(NFSR_NODE_RESET);
dcd_event_bus_reset(0, TUSB_SPEED_FULL, true);
USB->USB_DMA_CTRL_REG = 0;
USB->USB_MAMSK_REG = USB_USB_MAMSK_REG_USB_M_INTR_Msk |
#if USE_SOF
USB_USB_MAMSK_REG_USB_M_FRAME_Msk |
#endif
USB_USB_MAMSK_REG_USB_M_WARN_Msk |
USB_USB_MAMSK_REG_USB_M_ALT_Msk;
USB->USB_NFSR_REG = NFSR_NODE_OPERATIONAL;
USB->USB_ALTMSK_REG = USB_USB_ALTMSK_REG_USB_M_SD3_Msk |
USB_USB_ALTMSK_REG_USB_M_RESUME_Msk;
// There is no information about end of reset state
// USB_FRAME event will be used to enable reset detection again
REG_SET_BIT(USB_MAEV_REG, USB_FRAME);
dcd_edpt_open (0, &ep0OUT_desc);
dcd_edpt_open (0, &ep0IN_desc);
USB->USB_ALTMSK_REG = USB_USB_ALTMSK_REG_USB_M_RESUME_Msk;
alt_ev = USB->USB_ALTEV_REG;
check_reset_end(alt_ev);
}
static void handle_alt_ev(void)
{
uint32_t alt_ev = USB->USB_ALTEV_REG;
if (GET_BIT(alt_ev, USB_USB_ALTEV_REG_USB_RESET))
alt_ev = check_reset_end(alt_ev);
if (GET_BIT(alt_ev, USB_USB_ALTEV_REG_USB_RESET) && _dcd.nfsr != NFSR_NODE_RESET)
{
handle_bus_reset();
}
else
else if (GET_BIT(alt_ev, USB_USB_ALTEV_REG_USB_RESUME))
{
if (GET_BIT(alt_ev, USB_USB_ALTEV_REG_USB_RESUME))
if (USB->USB_NFSR_REG == NFSR_NODE_SUSPEND)
{
USB->USB_NFSR_REG = NFSR_NODE_OPERATIONAL;
USB->USB_ALTMSK_REG &= ~USB_USB_ALTMSK_REG_USB_M_RESUME_Msk;
USB->USB_ALTMSK_REG |= USB_USB_ALTMSK_REG_USB_M_SD3_Msk;
set_nfsr(NFSR_NODE_OPERATIONAL);
USB->USB_ALTMSK_REG = USB_USB_ALTMSK_REG_USB_M_RESET_Msk |
USB_USB_ALTMSK_REG_USB_M_SD3_Msk;
dcd_event_bus_signal(0, DCD_EVENT_RESUME, true);
}
if (GET_BIT(alt_ev, USB_USB_ALTEV_REG_USB_SD3))
{
USB->USB_NFSR_REG = NFSR_NODE_SUSPEND;
USB->USB_ALTMSK_REG |= USB_USB_ALTMSK_REG_USB_M_RESUME_Msk;
USB->USB_ALTMSK_REG &= ~USB_USB_ALTMSK_REG_USB_M_SD3_Msk | USB_USB_ALTMSK_REG_USB_M_SD5_Msk;
dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true);
}
}
else if (GET_BIT(alt_ev, USB_USB_ALTEV_REG_USB_SD3))
{
set_nfsr(NFSR_NODE_SUSPEND);
USB->USB_ALTMSK_REG = USB_USB_ALTMSK_REG_USB_M_RESET_Msk |
USB_USB_ALTMSK_REG_USB_M_RESUME_Msk;
dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true);
}
}
@@ -735,19 +797,13 @@ static void handle_ep0_nak(void)
*------------------------------------------------------------------*/
void dcd_init(uint8_t rhport)
{
USB->USB_MCTRL_REG = USB_USB_MCTRL_REG_USBEN_Msk;
USB->USB_NFSR_REG = 0;
USB->USB_FAR_REG = 0x80;
USB->USB_NFSR_REG = NFSR_NODE_RESET;
USB->USB_TXMSK_REG = 0;
USB->USB_RXMSK_REG = 0;
(void) rhport;
USB->USB_MAMSK_REG = USB_USB_MAMSK_REG_USB_M_INTR_Msk |
USB_USB_MAMSK_REG_USB_M_ALT_Msk |
USB_USB_MAMSK_REG_USB_M_WARN_Msk;
USB->USB_ALTMSK_REG = USB_USB_ALTMSK_REG_USB_M_RESET_Msk;
dcd_connect(rhport);
_dcd.init_called = true;
if (_dcd.vbus_present)
{
dcd_connect(rhport);
}
}
void dcd_int_enable(uint8_t rhport)
@@ -777,16 +833,37 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
void dcd_remote_wakeup(uint8_t rhport)
{
(void)rhport;
if (_dcd.nfsr == NFSR_NODE_SUSPEND)
{
// Enter fake state that will use FRAME interrupt to wait before going operational.
set_nfsr(NFSR_NODE_WAKING);
USB->USB_MAMSK_REG |= USB_USB_MAMSK_REG_USB_M_FRAME_Msk;
}
}
void dcd_connect(uint8_t rhport)
{
(void)rhport;
REG_SET_BIT(USB_MCTRL_REG, USB_NAT);
if (GET_BIT(USB->USB_MCTRL_REG, USB_USB_MCTRL_REG_USB_NAT) == 0)
{
USB->USB_MCTRL_REG = USB_USB_MCTRL_REG_USBEN_Msk;
USB->USB_NFSR_REG = 0;
USB->USB_FAR_REG = 0x80;
USB->USB_TXMSK_REG = 0;
USB->USB_RXMSK_REG = 0;
// Select chosen DMA to be triggered by USB.
DMA->DMA_REQ_MUX_REG = (DMA->DMA_REQ_MUX_REG & ~DA146XX_DMA_USB_MUX_MASK) | DA146XX_DMA_USB_MUX;
USB->USB_MAMSK_REG = USB_USB_MAMSK_REG_USB_M_INTR_Msk |
USB_USB_MAMSK_REG_USB_M_ALT_Msk |
USB_USB_MAMSK_REG_USB_M_WARN_Msk;
USB->USB_ALTMSK_REG = USB_USB_ALTMSK_REG_USB_M_RESET_Msk |
USB_USB_ALTEV_REG_USB_SD3_Msk;
USB->USB_MCTRL_REG = USB_USB_MCTRL_REG_USBEN_Msk | USB_USB_MCTRL_REG_USB_NAT_Msk;
// Select chosen DMA to be triggered by USB.
DMA->DMA_REQ_MUX_REG = (DMA->DMA_REQ_MUX_REG & ~DA146XX_DMA_USB_MUX_MASK) | DA146XX_DMA_USB_MUX;
}
}
void dcd_disconnect(uint8_t rhport)
@@ -796,6 +873,30 @@ void dcd_disconnect(uint8_t rhport)
REG_CLR_BIT(USB_MCTRL_REG, USB_NAT);
}
TU_ATTR_ALWAYS_INLINE static inline bool is_in_isr(void)
{
return (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0;
}
void tusb_vbus_changed(bool present)
{
if (present && !_dcd.vbus_present)
{
_dcd.vbus_present = true;
// If power event happened before USB started, delay dcd_connect
// until dcd_init is called.
if (_dcd.init_called)
{
dcd_connect(0);
}
}
else if (!present && _dcd.vbus_present)
{
_dcd.vbus_present = false;
USB->USB_MCTRL_REG = 0;
dcd_event_bus_signal(0, DCD_EVENT_UNPLUGGED, is_in_isr());
}
}
/*------------------------------------------------------------------*/
/* DCD Endpoint port
@@ -808,11 +909,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
uint8_t const epnum = tu_edpt_number(desc_edpt->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(desc_edpt->bEndpointAddress);
xfer_ctl_t * xfer = XFER_CTL_BASE(epnum, dir);
EPx_REGS *regs = EPNUM_REGS(epnum);
uint8_t iso_mask = 0;
TU_ASSERT(epnum < EP_MAX);
xfer->max_packet_size = desc_edpt->wMaxPacketSize.size;
xfer->max_packet_size = tu_edpt_packet_size(desc_edpt);
xfer->ep_addr = desc_edpt->bEndpointAddress;
xfer->data1 = 0;
xfer->iso = 0;
@@ -832,13 +934,13 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
{
if (dir == TUSB_DIR_OUT)
{
xfer->regs->epc_out = epnum | USB_USB_EPC1_REG_USB_EP_EN_Msk | iso_mask;
regs->epc_out = epnum | USB_USB_EPC1_REG_USB_EP_EN_Msk | iso_mask;
USB->USB_RXMSK_REG |= 0x101 << (epnum - 1);
REG_SET_BIT(USB_MAMSK_REG, USB_M_RX_EV);
}
else
{
xfer->regs->epc_in = epnum | USB_USB_EPC1_REG_USB_EP_EN_Msk | iso_mask;
regs->epc_in = epnum | USB_USB_EPC1_REG_USB_EP_EN_Msk | iso_mask;
USB->USB_TXMSK_REG |= 0x101 << (epnum - 1);
REG_SET_BIT(USB_MAMSK_REG, USB_M_TX_EV);
}
@@ -847,10 +949,22 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
for (int epnum = 1; epnum < EP_MAX; ++epnum)
{
dcd_edpt_close(0, epnum | TUSB_DIR_OUT);
dcd_edpt_close(0, epnum | TUSB_DIR_IN);
}
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
EPx_REGS *regs = EPNUM_REGS(epnum);
xfer_ctl_t * xfer = XFER_CTL_BASE(epnum, dir);
(void)rhport;
@@ -866,8 +980,8 @@ void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
if (dir == TUSB_DIR_OUT)
{
xfer->regs->rxc = USB_USB_RXC1_REG_USB_FLUSH_Msk;
xfer->regs->epc_out = 0;
regs->rxc = USB_USB_RXC1_REG_USB_FLUSH_Msk;
regs->epc_out = 0;
USB->USB_RXMSK_REG &= ~(0x101 << (epnum - 1));
// Release DMA if needed
if (_dcd.dma_ep[TUSB_DIR_OUT] == epnum)
@@ -878,8 +992,8 @@ void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
}
else
{
xfer->regs->txc = USB_USB_TXC1_REG_USB_FLUSH_Msk;
xfer->regs->epc_in = 0;
regs->txc = USB_USB_TXC1_REG_USB_FLUSH_Msk;
regs->epc_in = 0;
USB->USB_TXMSK_REG &= ~(0x101 << (epnum - 1));
// Release DMA if needed
if (_dcd.dma_ep[TUSB_DIR_IN] == epnum)
@@ -889,6 +1003,7 @@ void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
}
}
}
tu_memclr(xfer, sizeof(*xfer));
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
@@ -924,6 +1039,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
(void)rhport;
xfer_ctl_t * xfer = XFER_CTL_BASE(epnum, dir);
EPx_REGS *regs = EPNUM_REGS(epnum);
xfer->stall = 1;
if (epnum == 0)
@@ -932,11 +1048,11 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
REG_SET_BIT(USB_EPC0_REG, USB_STALL);
if (dir == TUSB_DIR_OUT)
{
xfer->regs->USB_RXC0_REG = USB_USB_RXC0_REG_USB_RX_EN_Msk;
regs->USB_RXC0_REG = USB_USB_RXC0_REG_USB_RX_EN_Msk;
}
else
{
if (xfer->regs->USB_RXC0_REG & USB_USB_RXC0_REG_USB_RX_EN_Msk)
if (regs->USB_RXC0_REG & USB_USB_RXC0_REG_USB_RX_EN_Msk)
{
// If RX is also enabled TX will not be stalled since RX has
// higher priority. Enable NAK interrupt to handle stall.
@@ -944,7 +1060,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
}
else
{
xfer->regs->USB_TXC0_REG |= USB_USB_TXC0_REG_USB_TX_EN_Msk;
regs->USB_TXC0_REG |= USB_USB_TXC0_REG_USB_TX_EN_Msk;
}
}
}
@@ -952,13 +1068,13 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
if (dir == TUSB_DIR_OUT)
{
xfer->regs->epc_out |= USB_USB_EPC1_REG_USB_STALL_Msk;
xfer->regs->rxc |= USB_USB_RXC1_REG_USB_RX_EN_Msk;
regs->epc_out |= USB_USB_EPC1_REG_USB_STALL_Msk;
regs->rxc |= USB_USB_RXC1_REG_USB_RX_EN_Msk;
}
else
{
xfer->regs->epc_in |= USB_USB_EPC1_REG_USB_STALL_Msk;
xfer->regs->txc |= USB_USB_TXC1_REG_USB_TX_EN_Msk | USB_USB_TXC1_REG_USB_LAST_Msk;
regs->epc_in |= USB_USB_EPC1_REG_USB_STALL_Msk;
regs->txc |= USB_USB_TXC1_REG_USB_TX_EN_Msk | USB_USB_TXC1_REG_USB_LAST_Msk;
}
}
}
@@ -971,6 +1087,7 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
(void)rhport;
xfer_ctl_t * xfer = XFER_CTL_BASE(epnum, dir);
EPx_REGS *regs = EPNUM_REGS(epnum);
// Clear stall is called in response to Clear Feature ENDPOINT_HALT, reset toggle
xfer->data1 = 0;
@@ -978,11 +1095,11 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
if (dir == TUSB_DIR_OUT)
{
xfer->regs->epc_out &= ~USB_USB_EPC1_REG_USB_STALL_Msk;
regs->epc_out &= ~USB_USB_EPC1_REG_USB_STALL_Msk;
}
else
{
xfer->regs->epc_in &= ~USB_USB_EPC1_REG_USB_STALL_Msk;
regs->epc_in &= ~USB_USB_EPC1_REG_USB_STALL_Msk;
}
if (epnum == 0)
{
@@ -996,7 +1113,7 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
void dcd_int_handler(uint8_t rhport)
{
uint32_t int_status = USB->USB_MAEV_REG;
uint32_t int_status = USB->USB_MAEV_REG & USB->USB_MAMSK_REG;
(void)rhport;
@@ -1038,19 +1155,38 @@ void dcd_int_handler(uint8_t rhport)
if (GET_BIT(int_status, USB_USB_MAEV_REG_USB_FRAME))
{
if (_dcd.in_reset)
if (_dcd.nfsr == NFSR_NODE_RESET)
{
// Enable reset detection
_dcd.in_reset = false;
(void)USB->USB_ALTEV_REG;
// During reset FRAME interrupt is enabled to periodically
// check when reset state ends.
// FRAME interrupt is generated every 1ms without host sending
// actual SOF.
check_reset_end(USB_USB_ALTEV_REG_USB_RESET_Msk);
}
else if (_dcd.nfsr == NFSR_NODE_WAKING)
{
// No need to call set_nfsr, just set state
_dcd.nfsr = NFSR_NODE_WAKING2;
}
else if (_dcd.nfsr == NFSR_NODE_WAKING2)
{
// No need to call set_nfsr, just set state
_dcd.nfsr = NFSR_NODE_RESUME;
}
else if (_dcd.nfsr == NFSR_NODE_RESUME)
{
set_nfsr(NFSR_NODE_OPERATIONAL);
}
else
{
#if USE_SOF
dcd_event_bus_signal(0, DCD_EVENT_SOF, true);
dcd_event_bus_signal(0, DCD_EVENT_SOF, true);
#else
// SOF was used to re-enable reset detection
// No need to keep it enabled
USB->USB_MAMSK_REG &= ~USB_USB_MAMSK_REG_USB_M_FRAME_Msk;
// FRAME interrupt was used to re-enable reset detection or remote
// wakeup no need to keep it enabled when USE_SOF is off.
USB->USB_MAMSK_REG &= ~USB_USB_MAMSK_REG_USB_M_FRAME_Msk;
#endif
}
}
if (GET_BIT(int_status, USB_USB_MAEV_REG_USB_TX_EV))
+4 -4
View File
@@ -128,7 +128,7 @@ static inline ehci_qtd_t* qtd_find_free (void);
static inline ehci_qtd_t* qtd_next (ehci_qtd_t const * p_qtd);
static inline void qtd_insert_to_qhd (ehci_qhd_t *p_qhd, ehci_qtd_t *p_qtd_new);
static inline void qtd_remove_1st_from_qhd (ehci_qhd_t *p_qhd);
static void qtd_init (ehci_qtd_t* p_qtd, void* buffer, uint16_t total_bytes);
static void qtd_init (ehci_qtd_t* p_qtd, void const* buffer, uint16_t total_bytes);
static inline void list_insert (ehci_link_t *current, ehci_link_t *new, uint8_t new_type);
static inline ehci_link_t* list_next (ehci_link_t *p_link_pointer);
@@ -392,7 +392,7 @@ bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet
ehci_qhd_t* qhd = &ehci_data.control[dev_addr].qhd;
ehci_qtd_t* td = &ehci_data.control[dev_addr].qtd;
qtd_init(td, (void*) setup_packet, 8);
qtd_init(td, setup_packet, 8);
td->pid = EHCI_PID_SETUP;
td->int_on_complete = 1;
td->next.terminate = 1;
@@ -802,7 +802,7 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t c
p_qhd->ep_speed = devtree_info.speed;
p_qhd->data_toggle_control= (xfer_type == TUSB_XFER_CONTROL) ? 1 : 0;
p_qhd->head_list_flag = (dev_addr == 0) ? 1 : 0; // addr0's endpoint is the static asyn list head
p_qhd->max_packet_size = ep_desc->wMaxPacketSize.size;
p_qhd->max_packet_size = tu_edpt_packet_size(ep_desc);
p_qhd->fl_ctrl_ep_flag = ((xfer_type == TUSB_XFER_CONTROL) && (p_qhd->ep_speed != TUSB_SPEED_HIGH)) ? 1 : 0;
p_qhd->nak_reload = 0;
@@ -857,7 +857,7 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t c
}
}
static void qtd_init(ehci_qtd_t* p_qtd, void* buffer, uint16_t total_bytes)
static void qtd_init(ehci_qtd_t* p_qtd, void const* buffer, uint16_t total_bytes)
{
tu_memclr(p_qtd, sizeof(ehci_qtd_t));
+55 -68
View File
@@ -31,7 +31,6 @@
#if (((CFG_TUSB_MCU == OPT_MCU_ESP32S2) || (CFG_TUSB_MCU == OPT_MCU_ESP32S3)) && TUSB_OPT_DEVICE_ENABLED)
// Espressif
#include "driver/periph_ctrl.h"
#include "freertos/xtensa_api.h"
#include "esp_intr_alloc.h"
#include "esp_log.h"
@@ -39,13 +38,10 @@
#include "soc/dport_reg.h"
#include "soc/gpio_sig_map.h"
#include "soc/usb_periph.h"
#include "soc/periph_defs.h" // for interrupt source
#include "device/dcd.h"
// Since TinyUSB doesn't use SOF for now, and this interrupt too often (1ms interval)
// We disable SOF for now until needed later on
#define USE_SOF 0
// Max number of bi-directional endpoints including EP0
// Note: ESP32S2 specs say there are only up to 5 IN active endpoints include EP0
// We should probably prohibit enabling Endpoint IN > 4 (not done yet)
@@ -92,11 +88,12 @@ static void bus_reset(void)
USB0.out_ep_reg[ep_num].doepctl |= USB_DO_SNAK0_M; // DOEPCTL0_SNAK
}
USB0.dcfg &= ~USB_DEVADDR_M; // reset address
// clear device address
USB0.dcfg &= ~USB_DEVADDR_M;
USB0.daintmsk |= USB_OUTEPMSK0_M | USB_INEPMSK0_M;
USB0.doepmsk |= USB_SETUPMSK_M | USB_XFERCOMPLMSK;
USB0.diepmsk |= USB_TIMEOUTMSK_M | USB_DI_XFERCOMPLMSK_M /*| USB_INTKNTXFEMPMSK_M*/;
USB0.daintmsk = USB_OUTEPMSK0_M | USB_INEPMSK0_M;
USB0.doepmsk = USB_SETUPMSK_M | USB_XFERCOMPLMSK;
USB0.diepmsk = USB_TIMEOUTMSK_M | USB_DI_XFERCOMPLMSK_M /*| USB_INTKNTXFEMPMSK_M*/;
// "USB Data FIFOs" section in reference manual
// Peripheral FIFO architecture
@@ -193,9 +190,6 @@ void dcd_init(uint8_t rhport)
USB0.gintsts = ~0U; //clear pending ints
USB0.gintmsk = USB_OTGINTMSK_M |
USB_MODEMISMSK_M |
#if USE_SOF
USB_SOFMSK_M |
#endif
USB_RXFLVIMSK_M |
USB_ERLYSUSPMSK_M |
USB_USBSUSPMSK_M |
@@ -220,8 +214,17 @@ void dcd_remote_wakeup(uint8_t rhport)
{
(void)rhport;
// TODO must manually clear this bit after 1-15 ms
// USB0.DCTL |= USB_RMTWKUPSIG_M;
// set remote wakeup
USB0.dctl |= USB_RMTWKUPSIG_M;
// enable SOF to detect bus resume
USB0.gintsts = USB_SOF_M;
USB0.gintmsk |= USB_SOFMSK_M;
// Per specs: remote wakeup signal bit must be clear within 1-15ms
vTaskDelay(pdMS_TO_TICKS(1));
USB0.dctl &= ~USB_RMTWKUPSIG_M;
}
// connect by enabling internal pull-up resistor on D+/D-
@@ -253,16 +256,16 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const *desc_edpt)
uint8_t const epnum = tu_edpt_number(desc_edpt->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(desc_edpt->bEndpointAddress);
TU_ASSERT(desc_edpt->wMaxPacketSize.size <= 64);
TU_ASSERT(epnum < EP_MAX);
xfer_ctl_t *xfer = XFER_CTL_BASE(epnum, dir);
xfer->max_size = desc_edpt->wMaxPacketSize.size;
xfer->max_size = tu_edpt_packet_size(desc_edpt);
if (dir == TUSB_DIR_OUT) {
out_ep[epnum].doepctl |= USB_USBACTEP0_M |
desc_edpt->bmAttributes.xfer << USB_EPTYPE0_S |
desc_edpt->wMaxPacketSize.size << USB_MPS0_S;
out_ep[epnum].doepctl |= USB_USBACTEP1_M |
desc_edpt->bmAttributes.xfer << USB_EPTYPE1_S |
(desc_edpt->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS ? USB_DO_SETD0PID1_M : 0) |
xfer->max_size << USB_MPS1_S;
USB0.daintmsk |= (1 << (16 + epnum));
} else {
// "USB Data FIFOs" section in reference manual
@@ -296,7 +299,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const *desc_edpt)
fifo_num << USB_D_TXFNUM1_S |
desc_edpt->bmAttributes.xfer << USB_D_EPTYPE1_S |
(desc_edpt->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS ? (1 << USB_DI_SETD0PID1_S) : 0) |
desc_edpt->wMaxPacketSize.size << 0;
xfer->max_size << 0;
USB0.daintmsk |= (1 << (0 + epnum));
@@ -312,6 +315,30 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const *desc_edpt)
return true;
}
void dcd_edpt_close_all(uint8_t rhport)
{
(void) rhport;
usb_out_endpoint_t *out_ep = &(USB0.out_ep_reg[0]);
usb_in_endpoint_t *in_ep = &(USB0.in_ep_reg[0]);
// Disable non-control interrupt
USB0.daintmsk = USB_OUTEPMSK0_M | USB_INEPMSK0_M;
for(uint8_t n = 1; n < EP_MAX; n++)
{
// disable OUT endpoint
out_ep[n].doepctl = 0;
xfer_status[n][TUSB_DIR_OUT].max_size = 0;
// disable IN endpoint
in_ep[n].diepctl = 0;
xfer_status[n][TUSB_DIR_IN].max_size = 0;
}
_allocated_fifos = 1;
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
{
(void)rhport;
@@ -361,49 +388,6 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t to
bool dcd_edpt_xfer_fifo (uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes)
{
(void)rhport;
// 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;
xfer->queued_len = 0;
xfer->short_packet = false;
uint16_t num_packets = (total_bytes / xfer->max_size);
uint8_t short_packet_size = total_bytes % xfer->max_size;
// Zero-size packet is special case.
if (short_packet_size > 0 || (total_bytes == 0)) {
num_packets++;
}
ESP_LOGV(TAG, "Transfer <-> EP%i, %s, pkgs: %i, bytes: %i",
epnum, ((dir == TUSB_DIR_IN) ? "USB0.HOST (in)" : "HOST->DEV (out)"),
num_packets, total_bytes);
// IN and OUT endpoint xfers are interrupt-driven, we just schedule them
// here.
if (dir == TUSB_DIR_IN) {
// A full IN transfer (multiple packets, possibly) triggers XFRC.
USB0.in_ep_reg[epnum].dieptsiz = (num_packets << USB_D_PKTCNT0_S) | total_bytes;
USB0.in_ep_reg[epnum].diepctl |= USB_D_EPENA1_M | USB_D_CNAK1_M; // Enable | CNAK
// Enable fifo empty interrupt only if there are something to put in the fifo.
if(total_bytes != 0) {
USB0.dtknqr4_fifoemptymsk |= (1 << epnum);
}
} else {
// Each complete packet for OUT xfers triggers XFRC.
USB0.out_ep_reg[epnum].doeptsiz |= USB_PKTCNT0_M | ((xfer->max_size & USB_XFERSIZE0_V) << USB_XFERSIZE0_S);
USB0.out_ep_reg[epnum].doepctl |= USB_EPENA0_M | USB_CNAK0_M;
}
return true;
}
#endif
@@ -748,8 +732,8 @@ static void _dcd_int_handler(void* arg)
(void) arg;
uint8_t const rhport = 0;
const uint32_t int_status = USB0.gintsts;
//const uint32_t int_msk = USB0.gintmsk;
const uint32_t int_msk = USB0.gintmsk;
const uint32_t int_status = USB0.gintsts & int_msk;
if (int_status & USB_USBRST_M) {
// start of reset
@@ -802,12 +786,15 @@ static void _dcd_int_handler(void* arg)
USB0.gotgint = otg_int;
}
#if USE_SOF
if (int_status & USB_SOF_M) {
USB0.gintsts = USB_SOF_M;
dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); // do nothing actually
// Disable SOF interrupt since currently only used for remote wakeup detection
USB0.gintmsk &= ~USB_SOFMSK_M;
dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true);
}
#endif
if (int_status & USB_RXFLVI_M) {
// RXFLVL bit is read-only
+900
View File
@@ -0,0 +1,900 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Koji KITAYAMA
*
* 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 && \
TU_CHECK_MCU(OPT_MCU_MSP432E4, OPT_MCU_TM4C123, OPT_MCU_TM4C129)
#if __GNUC__ > 8 && defined(__ARM_FEATURE_UNALIGNED)
/* GCC warns that an address may be unaligned, even though
* the target CPU has the capability for unaligned memory access. */
_Pragma("GCC diagnostic ignored \"-Waddress-of-packed-member\"");
#endif
#include "device/dcd.h"
#if TU_CHECK_MCU(OPT_MCU_MSP432E4)
#include "musb_msp432e.h"
#elif TU_CHECK_MCU(OPT_MCU_TM4C123, OPT_MCU_TM4C129)
#include "musb_tm4c.h"
// HACK generalize later
#include "musb_type.h"
#define FIFO0_WORD FIFO0
#define FIFO1_WORD FIFO1
#else
#error "Unsupported MCUs"
#endif
/*------------------------------------------------------------------
* MACRO TYPEDEF CONSTANT ENUM DECLARATION
*------------------------------------------------------------------*/
#define REQUEST_TYPE_INVALID (0xFFu)
typedef struct {
uint_fast16_t beg; /* offset of including first element */
uint_fast16_t end; /* offset of excluding the last element */
} free_block_t;
typedef struct TU_ATTR_PACKED {
uint16_t TXMAXP;
uint8_t TXCSRL;
uint8_t TXCSRH;
uint16_t RXMAXP;
uint8_t RXCSRL;
uint8_t RXCSRH;
uint16_t RXCOUNT;
uint16_t RESERVED[3];
} hw_endpoint_t;
typedef union {
uint8_t u8;
uint16_t u16;
uint32_t u32;
} hw_fifo_t;
typedef struct TU_ATTR_PACKED
{
void *buf; /* the start address of a transfer data buffer */
uint16_t length; /* the number of bytes in the buffer */
uint16_t remaining; /* the number of bytes remaining in the buffer */
} pipe_state_t;
typedef struct
{
tusb_control_request_t setup_packet;
uint16_t remaining_ctrl; /* The number of bytes remaining in data stage of control transfer. */
int8_t status_out;
pipe_state_t pipe0;
pipe_state_t pipe[2][7]; /* pipe[direction][endpoint number - 1] */
uint16_t pipe_buf_is_fifo[2]; /* Bitmap. Each bit means whether 1:TU_FIFO or 0:POD. */
} dcd_data_t;
/*------------------------------------------------------------------
* INTERNAL OBJECT & FUNCTION DECLARATION
*------------------------------------------------------------------*/
static dcd_data_t _dcd;
static inline free_block_t *find_containing_block(free_block_t *beg, free_block_t *end, uint_fast16_t addr)
{
free_block_t *cur = beg;
for (; cur < end && ((addr < cur->beg) || (cur->end <= addr)); ++cur) ;
return cur;
}
static inline int update_free_block_list(free_block_t *blks, unsigned num, uint_fast16_t addr, uint_fast16_t size)
{
free_block_t *p = find_containing_block(blks, blks + num, addr);
TU_ASSERT(p != blks + num, -2);
if (p->beg == addr) {
/* Shrink block */
p->beg = addr + size;
if (p->beg != p->end) return 0;
/* remove block */
free_block_t *end = blks + num;
while (p + 1 < end) {
*p = *(p + 1);
++p;
}
return -1;
} else {
/* Split into 2 blocks */
free_block_t tmp = {
.beg = addr + size,
.end = p->end
};
p->end = addr;
if (p->beg == p->end) {
if (tmp.beg != tmp.end) {
*p = tmp;
return 0;
}
/* remove block */
free_block_t *end = blks + num;
while (p + 1 < end) {
*p = *(p + 1);
++p;
}
return -1;
}
if (tmp.beg == tmp.end) return 0;
blks[num] = tmp;
return 1;
}
}
static inline unsigned free_block_size(free_block_t const *blk)
{
return blk->end - blk->beg;
}
#if 0
static inline void print_block_list(free_block_t const *blk, unsigned num)
{
TU_LOG1("*************\n");
for (unsigned i = 0; i < num; ++i) {
TU_LOG1(" Blk%u %u %u\n", i, blk->beg, blk->end);
++blk;
}
}
#else
#define print_block_list(a,b)
#endif
static unsigned find_free_memory(uint_fast16_t size_in_log2_minus3)
{
free_block_t free_blocks[2 * (DCD_ATTR_ENDPOINT_MAX - 1)];
unsigned num_blocks = 1;
/* Initialize free memory block list */
free_blocks[0].beg = 64 / 8;
free_blocks[0].end = (4 << 10) / 8; /* 4KiB / 8 bytes */
for (int i = 1; i < DCD_ATTR_ENDPOINT_MAX; ++i) {
uint_fast16_t addr;
int num;
USB0->EPIDX = i;
addr = USB0->TXFIFOADD;
if (addr) {
unsigned sz = USB0->TXFIFOSZ;
unsigned sft = (sz & USB_TXFIFOSZ_SIZE_M) + ((sz & USB_TXFIFOSZ_DPB) ? 1: 0);
num = update_free_block_list(free_blocks, num_blocks, addr, 1 << sft);
TU_ASSERT(-2 < num, 0);
num_blocks += num;
print_block_list(free_blocks, num_blocks);
}
addr = USB0->RXFIFOADD;
if (addr) {
unsigned sz = USB0->RXFIFOSZ;
unsigned sft = (sz & USB_RXFIFOSZ_SIZE_M) + ((sz & USB_RXFIFOSZ_DPB) ? 1: 0);
num = update_free_block_list(free_blocks, num_blocks, addr, 1 << sft);
TU_ASSERT(-2 < num, 0);
num_blocks += num;
print_block_list(free_blocks, num_blocks);
}
}
print_block_list(free_blocks, num_blocks);
/* Find the best fit memory block */
uint_fast16_t size_in_8byte_unit = 1 << size_in_log2_minus3;
free_block_t const *min = NULL;
uint_fast16_t min_sz = 0xFFFFu;
free_block_t const *end = &free_blocks[num_blocks];
for (free_block_t const *cur = &free_blocks[0]; cur < end; ++cur) {
uint_fast16_t sz = free_block_size(cur);
if (sz < size_in_8byte_unit) continue;
if (size_in_8byte_unit == sz) return cur->beg;
if (sz < min_sz) min = cur;
}
TU_ASSERT(min, 0);
return min->beg;
}
static inline volatile hw_endpoint_t* edpt_regs(unsigned epnum_minus1)
{
volatile hw_endpoint_t *regs = (volatile hw_endpoint_t*)((uintptr_t)&USB0->TXMAXP1);
return regs + epnum_minus1;
}
static void pipe_write_packet(void *buf, volatile void *fifo, unsigned len)
{
volatile hw_fifo_t *reg = (volatile hw_fifo_t*)fifo;
uintptr_t addr = (uintptr_t)buf;
while (len >= 4) {
reg->u32 = *(uint32_t const *)addr;
addr += 4;
len -= 4;
}
if (len >= 2) {
reg->u16 = *(uint16_t const *)addr;
addr += 2;
len -= 2;
}
if (len) {
reg->u8 = *(uint8_t const *)addr;
}
}
static void pipe_read_packet(void *buf, volatile void *fifo, unsigned len)
{
volatile hw_fifo_t *reg = (volatile hw_fifo_t*)fifo;
uintptr_t addr = (uintptr_t)buf;
while (len >= 4) {
*(uint32_t *)addr = reg->u32;
addr += 4;
len -= 4;
}
if (len >= 2) {
*(uint16_t *)addr = reg->u16;
addr += 2;
len -= 2;
}
if (len) {
*(uint8_t *)addr = reg->u8;
}
}
static void pipe_read_write_packet_ff(tu_fifo_t *f, volatile void *fifo, unsigned len, unsigned dir)
{
static const struct {
void (*tu_fifo_get_info)(tu_fifo_t *f, tu_fifo_buffer_info_t *info);
void (*tu_fifo_advance)(tu_fifo_t *f, uint16_t n);
void (*pipe_read_write)(void *buf, volatile void *fifo, unsigned len);
} ops[] = {
/* OUT */ {tu_fifo_get_write_info,tu_fifo_advance_write_pointer,pipe_read_packet},
/* IN */ {tu_fifo_get_read_info, tu_fifo_advance_read_pointer, pipe_write_packet},
};
tu_fifo_buffer_info_t info;
ops[dir].tu_fifo_get_info(f, &info);
unsigned total_len = len;
len = TU_MIN(total_len, info.len_lin);
ops[dir].pipe_read_write(info.ptr_lin, fifo, len);
unsigned rem = total_len - len;
if (rem) {
len = TU_MIN(rem, info.len_wrap);
ops[dir].pipe_read_write(info.ptr_wrap, fifo, len);
rem -= len;
}
ops[dir].tu_fifo_advance(f, total_len - rem);
}
static void process_setup_packet(uint8_t rhport)
{
uint32_t *p = (void*)&_dcd.setup_packet;
p[0] = USB0->FIFO0_WORD;
p[1] = USB0->FIFO0_WORD;
_dcd.pipe0.buf = NULL;
_dcd.pipe0.length = 0;
_dcd.pipe0.remaining = 0;
dcd_event_setup_received(rhport, (const uint8_t*)(uintptr_t)&_dcd.setup_packet, true);
const unsigned len = _dcd.setup_packet.wLength;
_dcd.remaining_ctrl = len;
const unsigned dir_in = tu_edpt_dir(_dcd.setup_packet.bmRequestType);
/* Clear RX FIFO and reverse the transaction direction */
if (len && dir_in) USB0->CSRL0 = USB_CSRL0_RXRDYC;
}
static bool handle_xfer_in(uint_fast8_t ep_addr)
{
unsigned epnum_minus1 = tu_edpt_number(ep_addr) - 1;
pipe_state_t *pipe = &_dcd.pipe[tu_edpt_dir(ep_addr)][epnum_minus1];
const unsigned rem = pipe->remaining;
if (!rem) {
pipe->buf = NULL;
return true;
}
volatile hw_endpoint_t *regs = edpt_regs(epnum_minus1);
const unsigned mps = regs->TXMAXP;
const unsigned len = TU_MIN(mps, rem);
void *buf = pipe->buf;
// TU_LOG1(" %p mps %d len %d rem %d\n", buf, mps, len, rem);
if (len) {
if (_dcd.pipe_buf_is_fifo[TUSB_DIR_IN] & TU_BIT(epnum_minus1)) {
pipe_read_write_packet_ff(buf, &USB0->FIFO1_WORD + epnum_minus1, len, TUSB_DIR_IN);
} else {
pipe_write_packet(buf, &USB0->FIFO1_WORD + epnum_minus1, len);
pipe->buf = buf + len;
}
pipe->remaining = rem - len;
}
regs->TXCSRL = USB_TXCSRL1_TXRDY;
// TU_LOG1(" TXCSRL%d = %x %d\n", epnum_minus1 + 1, regs->TXCSRL, rem - len);
return false;
}
static bool handle_xfer_out(uint_fast8_t ep_addr)
{
unsigned epnum_minus1 = tu_edpt_number(ep_addr) - 1;
pipe_state_t *pipe = &_dcd.pipe[tu_edpt_dir(ep_addr)][epnum_minus1];
volatile hw_endpoint_t *regs = edpt_regs(epnum_minus1);
// TU_LOG1(" RXCSRL%d = %x\n", epnum_minus1 + 1, regs->RXCSRL);
TU_ASSERT(regs->RXCSRL & USB_RXCSRL1_RXRDY);
const unsigned mps = regs->RXMAXP;
const unsigned rem = pipe->remaining;
const unsigned vld = regs->RXCOUNT;
const unsigned len = TU_MIN(TU_MIN(rem, mps), vld);
void *buf = pipe->buf;
if (len) {
if (_dcd.pipe_buf_is_fifo[TUSB_DIR_OUT] & TU_BIT(epnum_minus1)) {
pipe_read_write_packet_ff(buf, &USB0->FIFO1_WORD + epnum_minus1, len, TUSB_DIR_OUT);
} else {
pipe_read_packet(buf, &USB0->FIFO1_WORD + epnum_minus1, len);
pipe->buf = buf + len;
}
pipe->remaining = rem - len;
}
if ((len < mps) || (rem == len)) {
pipe->buf = NULL;
return NULL != buf;
}
regs->RXCSRL = 0; /* Clear RXRDY bit */
return false;
}
static bool edpt_n_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
{
(void)rhport;
unsigned epnum_minus1 = tu_edpt_number(ep_addr) - 1;
unsigned dir_in = tu_edpt_dir(ep_addr);
pipe_state_t *pipe = &_dcd.pipe[dir_in][epnum_minus1];
pipe->buf = buffer;
pipe->length = total_bytes;
pipe->remaining = total_bytes;
if (dir_in) {
handle_xfer_in(ep_addr);
} else {
volatile hw_endpoint_t *regs = edpt_regs(epnum_minus1);
if (regs->RXCSRL & USB_RXCSRL1_RXRDY) regs->RXCSRL = 0;
}
return true;
}
static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
{
(void)rhport;
TU_ASSERT(total_bytes <= 64); /* Current implementation supports for only up to 64 bytes. */
const unsigned req = _dcd.setup_packet.bmRequestType;
TU_ASSERT(req != REQUEST_TYPE_INVALID || total_bytes == 0);
if (req == REQUEST_TYPE_INVALID || _dcd.status_out) {
/* STATUS OUT stage.
* MUSB controller automatically handles STATUS OUT packets without
* software helps. We do not have to do anything. And STATUS stage
* may have already finished and received the next setup packet
* without calling this function, so we have no choice but to
* invoke the callback function of status packet here. */
// TU_LOG1(" STATUS OUT USB0->CSRL0 = %x\n", USB0->CSRL0);
_dcd.status_out = 0;
if (req == REQUEST_TYPE_INVALID) {
dcd_event_xfer_complete(rhport, ep_addr, total_bytes, XFER_RESULT_SUCCESS, false);
} else {
/* The next setup packet has already been received, it aborts
* invoking callback function to avoid confusing TUSB stack. */
TU_LOG1("Drop CONTROL_STAGE_ACK\n");
}
return true;
}
const unsigned dir_in = tu_edpt_dir(ep_addr);
if (tu_edpt_dir(req) == dir_in) { /* DATA stage */
TU_ASSERT(total_bytes <= _dcd.remaining_ctrl);
const unsigned rem = _dcd.remaining_ctrl;
const unsigned len = TU_MIN(TU_MIN(rem, 64), total_bytes);
if (dir_in) {
pipe_write_packet(buffer, &USB0->FIFO0_WORD, len);
_dcd.pipe0.buf = buffer + len;
_dcd.pipe0.length = len;
_dcd.pipe0.remaining = 0;
_dcd.remaining_ctrl = rem - len;
if ((len < 64) || (rem == len)) {
_dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID; /* Change to STATUS/SETUP stage */
_dcd.status_out = 1;
/* Flush TX FIFO and reverse the transaction direction. */
USB0->CSRL0 = USB_CSRL0_TXRDY | USB_CSRL0_DATAEND;
} else {
USB0->CSRL0 = USB_CSRL0_TXRDY; /* Flush TX FIFO to return ACK. */
}
// TU_LOG1(" IN USB0->CSRL0 = %x\n", USB0->CSRL0);
} else {
// TU_LOG1(" OUT USB0->CSRL0 = %x\n", USB0->CSRL0);
_dcd.pipe0.buf = buffer;
_dcd.pipe0.length = len;
_dcd.pipe0.remaining = len;
USB0->CSRL0 = USB_CSRL0_RXRDYC; /* Clear RX FIFO to return ACK. */
}
} else if (dir_in) {
// TU_LOG1(" STATUS IN USB0->CSRL0 = %x\n", USB0->CSRL0);
_dcd.pipe0.buf = NULL;
_dcd.pipe0.length = 0;
_dcd.pipe0.remaining = 0;
/* Clear RX FIFO and reverse the transaction direction */
USB0->CSRL0 = USB_CSRL0_RXRDYC | USB_CSRL0_DATAEND;
}
return true;
}
static void process_ep0(uint8_t rhport)
{
uint_fast8_t csrl = USB0->CSRL0;
// TU_LOG1(" EP0 USB0->CSRL0 = %x\n", csrl);
if (csrl & USB_CSRL0_STALLED) {
/* Returned STALL packet to HOST. */
USB0->CSRL0 = 0; /* Clear STALL */
return;
}
unsigned req = _dcd.setup_packet.bmRequestType;
if (csrl & USB_CSRL0_SETEND) {
TU_LOG1(" ABORT by the next packets\n");
USB0->CSRL0 = USB_CSRL0_SETENDC;
if (req != REQUEST_TYPE_INVALID && _dcd.pipe0.buf) {
/* DATA stage was aborted by receiving STATUS or SETUP packet. */
_dcd.pipe0.buf = NULL;
_dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID;
dcd_event_xfer_complete(rhport,
req & TUSB_DIR_IN_MASK,
_dcd.pipe0.length - _dcd.pipe0.remaining,
XFER_RESULT_SUCCESS, true);
}
req = REQUEST_TYPE_INVALID;
if (!(csrl & USB_CSRL0_RXRDY)) return; /* Received SETUP packet */
}
if (csrl & USB_CSRL0_RXRDY) {
/* Received SETUP or DATA OUT packet */
if (req == REQUEST_TYPE_INVALID) {
/* SETUP */
TU_ASSERT(sizeof(tusb_control_request_t) == USB0->COUNT0,);
process_setup_packet(rhport);
return;
}
if (_dcd.pipe0.buf) {
/* DATA OUT */
const unsigned vld = USB0->COUNT0;
const unsigned rem = _dcd.pipe0.remaining;
const unsigned len = TU_MIN(TU_MIN(rem, 64), vld);
pipe_read_packet(_dcd.pipe0.buf, &USB0->FIFO0_WORD, len);
_dcd.pipe0.remaining = rem - len;
_dcd.remaining_ctrl -= len;
_dcd.pipe0.buf = NULL;
dcd_event_xfer_complete(rhport,
tu_edpt_addr(0, TUSB_DIR_OUT),
_dcd.pipe0.length - _dcd.pipe0.remaining,
XFER_RESULT_SUCCESS, true);
}
return;
}
/* When CSRL0 is zero, it means that completion of sending a any length packet
* or receiving a zero length packet. */
if (req != REQUEST_TYPE_INVALID && !tu_edpt_dir(req)) {
/* STATUS IN */
if (*(const uint16_t*)(uintptr_t)&_dcd.setup_packet == 0x0500) {
/* The address must be changed on completion of the control transfer. */
USB0->FADDR = (uint8_t)_dcd.setup_packet.wValue;
}
_dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID;
dcd_event_xfer_complete(rhport,
tu_edpt_addr(0, TUSB_DIR_IN),
_dcd.pipe0.length - _dcd.pipe0.remaining,
XFER_RESULT_SUCCESS, true);
return;
}
if (_dcd.pipe0.buf) {
/* DATA IN */
_dcd.pipe0.buf = NULL;
dcd_event_xfer_complete(rhport,
tu_edpt_addr(0, TUSB_DIR_IN),
_dcd.pipe0.length - _dcd.pipe0.remaining,
XFER_RESULT_SUCCESS, true);
}
}
static void process_edpt_n(uint8_t rhport, uint_fast8_t ep_addr)
{
bool completed;
const unsigned dir_in = tu_edpt_dir(ep_addr);
const unsigned epn_minus1 = tu_edpt_number(ep_addr) - 1;
volatile hw_endpoint_t *regs = edpt_regs(epn_minus1);
if (dir_in) {
// TU_LOG1(" TXCSRL%d = %x\n", epn_minus1 + 1, regs->TXCSRL);
if (regs->TXCSRL & USB_TXCSRL1_STALLED) {
regs->TXCSRL &= ~(USB_TXCSRL1_STALLED | USB_TXCSRL1_UNDRN);
return;
}
completed = handle_xfer_in(ep_addr);
} else {
// TU_LOG1(" RXCSRL%d = %x\n", epn_minus1 + 1, regs->RXCSRL);
if (regs->RXCSRL & USB_RXCSRL1_STALLED) {
regs->RXCSRL &= ~(USB_RXCSRL1_STALLED | USB_RXCSRL1_OVER);
return;
}
completed = handle_xfer_out(ep_addr);
}
if (completed) {
pipe_state_t *pipe = &_dcd.pipe[dir_in][tu_edpt_number(ep_addr) - 1];
dcd_event_xfer_complete(rhport, ep_addr,
pipe->length - pipe->remaining,
XFER_RESULT_SUCCESS, true);
}
}
static void process_bus_reset(uint8_t rhport)
{
/* When bmRequestType is REQUEST_TYPE_INVALID(0xFF),
* a control transfer state is SETUP or STATUS stage. */
_dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID;
_dcd.status_out = 0;
/* When pipe0.buf has not NULL, DATA stage works in progress. */
_dcd.pipe0.buf = NULL;
USB0->TXIE = 1; /* Enable only EP0 */
USB0->RXIE = 0;
/* Clear FIFO settings */
for (unsigned i = 1; i < DCD_ATTR_ENDPOINT_MAX; ++i) {
USB0->EPIDX = i;
USB0->TXFIFOSZ = 0;
USB0->TXFIFOADD = 0;
USB0->RXFIFOSZ = 0;
USB0->RXFIFOADD = 0;
}
dcd_event_bus_reset(rhport, TUSB_SPEED_FULL, true);
}
/*------------------------------------------------------------------
* Device API
*------------------------------------------------------------------*/
void dcd_init(uint8_t rhport)
{
(void)rhport;
USB0->IE |= USB_IE_SUSPND;
NVIC_ClearPendingIRQ(USB0_IRQn);
dcd_connect(rhport);
}
void dcd_int_enable(uint8_t rhport)
{
(void)rhport;
NVIC_EnableIRQ(USB0_IRQn);
}
void dcd_int_disable(uint8_t rhport)
{
(void)rhport;
NVIC_DisableIRQ(USB0_IRQn);
}
// Receive Set Address request, mcu port must also include status IN response
void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
{
(void)rhport;
(void)dev_addr;
_dcd.pipe0.buf = NULL;
_dcd.pipe0.length = 0;
_dcd.pipe0.remaining = 0;
/* Clear RX FIFO to return ACK. */
USB0->CSRL0 = USB_CSRL0_RXRDYC | USB_CSRL0_DATAEND;
}
// Wake up host
void dcd_remote_wakeup(uint8_t rhport)
{
(void)rhport;
USB0->POWER |= USB_POWER_RESUME;
unsigned cnt = SystemCoreClock / 1000;
while (cnt--) __NOP();
USB0->POWER &= ~USB_POWER_RESUME;
}
// Connect by enabling internal pull-up resistor on D+/D-
void dcd_connect(uint8_t rhport)
{
(void)rhport;
USB0->POWER |= USB_POWER_SOFTCONN;
}
// Disconnect by disabling internal pull-up resistor on D+/D-
void dcd_disconnect(uint8_t rhport)
{
(void)rhport;
USB0->POWER &= ~USB_POWER_SOFTCONN;
}
//--------------------------------------------------------------------+
// Endpoint API
//--------------------------------------------------------------------+
// Configure endpoint's registers according to descriptor
bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
{
(void) rhport;
const unsigned ep_addr = ep_desc->bEndpointAddress;
const unsigned epn = tu_edpt_number(ep_addr);
const unsigned dir_in = tu_edpt_dir(ep_addr);
const unsigned xfer = ep_desc->bmAttributes.xfer;
const unsigned mps = tu_edpt_packet_size(ep_desc);
TU_ASSERT(epn < DCD_ATTR_ENDPOINT_MAX);
pipe_state_t *pipe = &_dcd.pipe[dir_in][epn - 1];
pipe->buf = NULL;
pipe->length = 0;
pipe->remaining = 0;
volatile hw_endpoint_t *regs = edpt_regs(epn - 1);
if (dir_in) {
regs->TXMAXP = mps;
regs->TXCSRH = (xfer == TUSB_XFER_ISOCHRONOUS) ? USB_TXCSRH1_ISO : 0;
if (regs->TXCSRL & USB_TXCSRL1_TXRDY)
regs->TXCSRL = USB_TXCSRL1_CLRDT | USB_TXCSRL1_FLUSH;
else
regs->TXCSRL = USB_TXCSRL1_CLRDT;
USB0->TXIE |= TU_BIT(epn);
} else {
regs->RXMAXP = mps;
regs->RXCSRH = (xfer == TUSB_XFER_ISOCHRONOUS) ? USB_RXCSRH1_ISO : 0;
if (regs->RXCSRL & USB_RXCSRL1_RXRDY)
regs->RXCSRL = USB_RXCSRL1_CLRDT | USB_RXCSRL1_FLUSH;
else
regs->RXCSRL = USB_RXCSRL1_CLRDT;
USB0->RXIE |= TU_BIT(epn);
}
/* Setup FIFO */
int size_in_log2_minus3 = 28 - TU_MIN(28, __CLZ((uint32_t)mps));
if ((8u << size_in_log2_minus3) < mps) ++size_in_log2_minus3;
unsigned addr = find_free_memory(size_in_log2_minus3);
TU_ASSERT(addr);
USB0->EPIDX = epn;
if (dir_in) {
USB0->TXFIFOADD = addr;
USB0->TXFIFOSZ = size_in_log2_minus3;
} else {
USB0->RXFIFOADD = addr;
USB0->RXFIFOSZ = size_in_log2_minus3;
}
return true;
}
void dcd_edpt_close_all(uint8_t rhport)
{
(void) rhport;
volatile hw_endpoint_t *regs = (volatile hw_endpoint_t *)(uintptr_t)&USB0->TXMAXP1;
unsigned const ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
USB0->TXIE = 1; /* Enable only EP0 */
USB0->RXIE = 0;
for (unsigned i = 1; i < DCD_ATTR_ENDPOINT_MAX; ++i) {
regs->TXMAXP = 0;
regs->TXCSRH = 0;
if (regs->TXCSRL & USB_TXCSRL1_TXRDY)
regs->TXCSRL = USB_TXCSRL1_CLRDT | USB_TXCSRL1_FLUSH;
else
regs->TXCSRL = USB_TXCSRL1_CLRDT;
regs->RXMAXP = 0;
regs->RXCSRH = 0;
if (regs->RXCSRL & USB_RXCSRL1_RXRDY)
regs->RXCSRL = USB_RXCSRL1_CLRDT | USB_RXCSRL1_FLUSH;
else
regs->RXCSRL = USB_RXCSRL1_CLRDT;
USB0->EPIDX = i;
USB0->TXFIFOSZ = 0;
USB0->TXFIFOADD = 0;
USB0->RXFIFOSZ = 0;
USB0->RXFIFOADD = 0;
}
if (ie) NVIC_EnableIRQ(USB0_IRQn);
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
(void)rhport;
unsigned const epn = tu_edpt_number(ep_addr);
unsigned const dir_in = tu_edpt_dir(ep_addr);
hw_endpoint_t volatile *regs = edpt_regs(epn - 1);
unsigned const ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
if (dir_in) {
USB0->TXIE &= ~TU_BIT(epn);
regs->TXMAXP = 0;
regs->TXCSRH = 0;
if (regs->TXCSRL & USB_TXCSRL1_TXRDY)
regs->TXCSRL = USB_TXCSRL1_CLRDT | USB_TXCSRL1_FLUSH;
else
regs->TXCSRL = USB_TXCSRL1_CLRDT;
USB0->EPIDX = epn;
USB0->TXFIFOSZ = 0;
USB0->TXFIFOADD = 0;
} else {
USB0->RXIE &= ~TU_BIT(epn);
regs->RXMAXP = 0;
regs->RXCSRH = 0;
if (regs->RXCSRL & USB_RXCSRL1_RXRDY)
regs->RXCSRL = USB_RXCSRL1_CLRDT | USB_RXCSRL1_FLUSH;
else
regs->RXCSRL = USB_RXCSRL1_CLRDT;
USB0->EPIDX = epn;
USB0->RXFIFOSZ = 0;
USB0->RXFIFOADD = 0;
}
if (ie) NVIC_EnableIRQ(USB0_IRQn);
}
// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
{
(void)rhport;
bool ret;
// TU_LOG1("X %x %d\n", ep_addr, total_bytes);
unsigned const epnum = tu_edpt_number(ep_addr);
unsigned const ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
if (epnum) {
_dcd.pipe_buf_is_fifo[tu_edpt_dir(ep_addr)] &= ~TU_BIT(epnum - 1);
ret = edpt_n_xfer(rhport, ep_addr, buffer, total_bytes);
} else
ret = edpt0_xfer(rhport, ep_addr, buffer, total_bytes);
if (ie) NVIC_EnableIRQ(USB0_IRQn);
return ret;
}
// Submit a transfer where is managed by FIFO, When complete dcd_event_xfer_complete() is invoked to notify the stack - optional, however, must be listed in usbd.c
bool dcd_edpt_xfer_fifo(uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes)
{
(void)rhport;
bool ret;
// TU_LOG1("X %x %d\n", ep_addr, total_bytes);
unsigned const epnum = tu_edpt_number(ep_addr);
TU_ASSERT(epnum);
unsigned const ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
_dcd.pipe_buf_is_fifo[tu_edpt_dir(ep_addr)] |= TU_BIT(epnum - 1);
ret = edpt_n_xfer(rhport, ep_addr, (uint8_t*)ff, total_bytes);
if (ie) NVIC_EnableIRQ(USB0_IRQn);
return ret;
}
// Stall endpoint
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
(void)rhport;
unsigned const epn = tu_edpt_number(ep_addr);
unsigned const ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
if (0 == epn) {
if (!ep_addr) { /* Ignore EP80 */
_dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID;
_dcd.pipe0.buf = NULL;
USB0->CSRL0 = USB_CSRL0_STALL;
}
} else {
volatile hw_endpoint_t *regs = edpt_regs(epn - 1);
if (tu_edpt_dir(ep_addr)) { /* IN */
regs->TXCSRL = USB_TXCSRL1_STALL;
} else { /* OUT */
TU_ASSERT(!(regs->RXCSRL & USB_RXCSRL1_RXRDY),);
regs->RXCSRL = USB_RXCSRL1_STALL;
}
}
if (ie) NVIC_EnableIRQ(USB0_IRQn);
}
// clear stall, data toggle is also reset to DATA0
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
(void)rhport;
unsigned const epn = tu_edpt_number(ep_addr);
hw_endpoint_t volatile *regs = edpt_regs(epn - 1);
unsigned const ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
if (tu_edpt_dir(ep_addr)) { /* IN */
regs->TXCSRL = USB_TXCSRL1_CLRDT;
} else { /* OUT */
regs->RXCSRL = USB_RXCSRL1_CLRDT;
}
if (ie) NVIC_EnableIRQ(USB0_IRQn);
}
/*-------------------------------------------------------------------
* ISR
*-------------------------------------------------------------------*/
void dcd_int_handler(uint8_t rhport)
{
uint_fast8_t is, txis, rxis;
is = USB0->IS; /* read and clear interrupt status */
txis = USB0->TXIS; /* read and clear interrupt status */
rxis = USB0->RXIS; /* read and clear interrupt status */
// TU_LOG1("D%2x T%2x R%2x\n", is, txis, rxis);
is &= USB0->IE; /* Clear disabled interrupts */
if (is & USB_IS_DISCON) {
}
if (is & USB_IS_SOF) {
dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true);
}
if (is & USB_IS_RESET) {
process_bus_reset(rhport);
}
if (is & USB_IS_RESUME) {
dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true);
}
if (is & USB_IS_SUSPEND) {
dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true);
}
txis &= USB0->TXIE; /* Clear disabled interrupts */
if (txis & USB_TXIE_EP0) {
process_ep0(rhport);
txis &= ~TU_BIT(0);
}
while (txis) {
unsigned const num = __builtin_ctz(txis);
process_edpt_n(rhport, tu_edpt_addr(num, TUSB_DIR_IN));
txis &= ~TU_BIT(num);
}
rxis &= USB0->RXIE; /* Clear disabled interrupts */
while (rxis) {
unsigned const num = __builtin_ctz(rxis);
process_edpt_n(rhport, tu_edpt_addr(num, TUSB_DIR_OUT));
rxis &= ~TU_BIT(num);
}
}
#endif
+876
View File
@@ -0,0 +1,876 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Koji KITAYAMA
*
* 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 && \
TU_CHECK_MCU(OPT_MCU_MSP432E4, OPT_MCU_TM4C123, OPT_MCU_TM4C129)
#if __GNUC__ > 8 && defined(__ARM_FEATURE_UNALIGNED)
/* GCC warns that an address may be unaligned, even though
* the target CPU has the capability for unaligned memory access. */
_Pragma("GCC diagnostic ignored \"-Waddress-of-packed-member\"");
#endif
#include "host/hcd.h"
#if TU_CHECK_MCU(OPT_MCU_MSP432E4)
#include "musb_msp432e.h"
#elif TU_CHECK_MCU(OPT_MCU_TM4C123, OPT_MCU_TM4C129)
#include "musb_tm4c.h"
// HACK generalize later
#include "musb_type.h"
#define FIFO0_WORD FIFO0
#else
#error "Unsupported MCUs"
#endif
#ifndef HCD_ATTR_ENDPOINT_MAX
# define HCD_ATTR_ENDPOINT_MAX 8
#endif
/*------------------------------------------------------------------
* MACRO TYPEDEF CONSTANT ENUM DECLARATION
*------------------------------------------------------------------*/
#define REQUEST_TYPE_INVALID (0xFFu)
typedef struct {
uint_fast16_t beg; /* offset of including first element */
uint_fast16_t end; /* offset of excluding the last element */
} free_block_t;
typedef struct TU_ATTR_PACKED {
uint8_t TXFUNCADDR;
uint8_t RESERVED0;
uint8_t TXHUBADDR;
uint8_t TXHUBPORT;
uint8_t RXFUNCADDR;
uint8_t RESERVED1;
uint8_t RXHUBADDR;
uint8_t RXHUBPORT;
} hw_addr_t;
typedef struct TU_ATTR_PACKED {
uint16_t TXMAXP;
uint8_t TXCSRL;
uint8_t TXCSRH;
uint16_t RXMAXP;
uint8_t RXCSRL;
uint8_t RXCSRH;
uint16_t RXCOUNT;
uint8_t TXTYPE;
uint8_t TXINTERVAL;
uint8_t RXTYPE;
uint8_t RXINTERVAL;
uint16_t RESERVED;
} hw_endpoint_t;
typedef union {
uint8_t u8;
uint16_t u16;
uint32_t u32;
} hw_fifo_t;
typedef struct TU_ATTR_PACKED
{
void *buf; /* the start address of a transfer data buffer */
uint16_t length; /* the number of bytes in the buffer */
uint16_t remaining; /* the number of bytes remaining in the buffer */
} pipe_state_t;
typedef struct TU_ATTR_PACKED
{
uint8_t dev;
uint8_t ep;
} pipe_addr_t;
typedef struct
{
bool need_reset; /* The device has not been reset after connection. */
uint8_t bmRequestType;
uint8_t ctl_mps[7]; /* EP0 max packet size for each device */
pipe_state_t pipe0;
pipe_state_t pipe[7][2]; /* pipe[pipe number - 1][direction 0:RX 1:TX] */
pipe_addr_t addr[7][2]; /* addr[pipe number - 1][direction 0:RX 1:TX] */
} hcd_data_t;
/*------------------------------------------------------------------
* INTERNAL OBJECT & FUNCTION DECLARATION
*------------------------------------------------------------------*/
static hcd_data_t _hcd;
static inline free_block_t *find_containing_block(free_block_t *beg, free_block_t *end, uint_fast16_t addr)
{
free_block_t *cur = beg;
for (; cur < end && ((addr < cur->beg) || (cur->end <= addr)); ++cur) ;
return cur;
}
static inline int update_free_block_list(free_block_t *blks, unsigned num, uint_fast16_t addr, uint_fast16_t size)
{
free_block_t *p = find_containing_block(blks, blks + num, addr);
TU_ASSERT(p != blks + num, -2);
if (p->beg == addr) {
/* Shrink block */
p->beg = addr + size;
if (p->beg != p->end) return 0;
/* remove block */
free_block_t *end = blks + num;
while (p + 1 < end) {
*p = *(p + 1);
++p;
}
return -1;
} else {
/* Split into 2 blocks */
free_block_t tmp = {
.beg = addr + size,
.end = p->end
};
p->end = addr;
if (p->beg == p->end) {
if (tmp.beg != tmp.end) {
*p = tmp;
return 0;
}
/* remove block */
free_block_t *end = blks + num;
while (p + 1 < end) {
*p = *(p + 1);
++p;
}
return -1;
}
if (tmp.beg == tmp.end) return 0;
blks[num] = tmp;
return 1;
}
}
static inline unsigned free_block_size(free_block_t const *blk)
{
return blk->end - blk->beg;
}
static unsigned find_free_memory(uint_fast16_t size_in_log2_minus3)
{
free_block_t free_blocks[2 * (HCD_ATTR_ENDPOINT_MAX - 1)];
unsigned num_blocks = 1;
/* Initialize free memory block list */
free_blocks[0].beg = 64 / 8;
free_blocks[0].end = (4 << 10) / 8; /* 4KiB / 8 bytes */
for (int i = 1; i < HCD_ATTR_ENDPOINT_MAX; ++i) {
uint_fast16_t addr;
int num;
USB0->EPIDX = i;
addr = USB0->TXFIFOADD;
if (addr) {
unsigned sz = USB0->TXFIFOSZ;
unsigned sft = (sz & USB_TXFIFOSZ_SIZE_M) + ((sz & USB_TXFIFOSZ_DPB) ? 1: 0);
num = update_free_block_list(free_blocks, num_blocks, addr, 1 << sft);
TU_ASSERT(-2 < num, 0);
num_blocks += num;
}
addr = USB0->RXFIFOADD;
if (addr) {
unsigned sz = USB0->RXFIFOSZ;
unsigned sft = (sz & USB_RXFIFOSZ_SIZE_M) + ((sz & USB_RXFIFOSZ_DPB) ? 1: 0);
num = update_free_block_list(free_blocks, num_blocks, addr, 1 << sft);
TU_ASSERT(-2 < num, 0);
num_blocks += num;
}
}
/* Find the best fit memory block */
uint_fast16_t size_in_8byte_unit = 1 << size_in_log2_minus3;
free_block_t const *min = NULL;
uint_fast16_t min_sz = 0xFFFFu;
free_block_t const *end = &free_blocks[num_blocks];
for (free_block_t const *cur = &free_blocks[0]; cur < end; ++cur) {
uint_fast16_t sz = free_block_size(cur);
if (sz < size_in_8byte_unit) continue;
if (size_in_8byte_unit == sz) return cur->beg;
if (sz < min_sz) min = cur;
}
TU_ASSERT(min, 0);
return min->beg;
}
static inline volatile hw_endpoint_t* edpt_regs(unsigned epnum_minus1)
{
volatile hw_endpoint_t *regs = (volatile hw_endpoint_t*)((uintptr_t)&USB0->TXMAXP1);
return regs + epnum_minus1;
}
static unsigned find_pipe(uint_fast8_t dev_addr, uint_fast8_t ep_addr)
{
unsigned const dir_tx = tu_edpt_dir(ep_addr) ? 0: 1;
pipe_addr_t const *p = &_hcd.addr[0][dir_tx];
for (unsigned i = 0; i < sizeof(_hcd.addr)/sizeof(_hcd.addr[0]); ++i, p += 2) {
if ((dev_addr == p->dev) && (ep_addr == p->ep))
return i + 1;
}
return 0;
}
static void pipe_write_packet(void *buf, volatile void *fifo, unsigned len)
{
volatile hw_fifo_t *reg = (volatile hw_fifo_t*)fifo;
uintptr_t addr = (uintptr_t)buf;
while (len >= 4) {
reg->u32 = *(uint32_t const *)addr;
addr += 4;
len -= 4;
}
if (len >= 2) {
reg->u16 = *(uint16_t const *)addr;
addr += 2;
len -= 2;
}
if (len) {
reg->u8 = *(uint8_t const *)addr;
}
}
static void pipe_read_packet(void *buf, volatile void *fifo, unsigned len)
{
volatile hw_fifo_t *reg = (volatile hw_fifo_t*)fifo;
uintptr_t addr = (uintptr_t)buf;
while (len >= 4) {
*(uint32_t *)addr = reg->u32;
addr += 4;
len -= 4;
}
if (len >= 2) {
*(uint16_t *)addr = reg->u16;
addr += 2;
len -= 2;
}
if (len) {
*(uint8_t *)addr = reg->u8;
}
}
static bool edpt0_xfer_out(void)
{
pipe_state_t *pipe = &_hcd.pipe0;
unsigned const rem = pipe->remaining;
if (!rem) {
pipe->buf = NULL;
return true;
}
unsigned const dev_addr = USB0->TXFUNCADDR0;
unsigned const mps = _hcd.ctl_mps[dev_addr];
unsigned const len = TU_MIN(rem, mps);
void *buf = pipe->buf;
if (len) {
pipe_write_packet(buf, &USB0->FIFO0_WORD, len);
pipe->buf = (uint8_t*)buf + len;
}
pipe->remaining = rem - len;
USB0->CSRL0 = USB_CSRL0_TXRDY;
return false;
}
static bool edpt0_xfer_in(void)
{
pipe_state_t *pipe = &_hcd.pipe0;
unsigned const rem = pipe->remaining;
unsigned const dev_addr = USB0->TXFUNCADDR0;
unsigned const mps = _hcd.ctl_mps[dev_addr];
unsigned const vld = USB0->COUNT0;
unsigned const len = TU_MIN(TU_MIN(rem, mps), vld);
void *buf = pipe->buf;
if (len) {
pipe_read_packet(buf, &USB0->FIFO0_WORD, len);
pipe->buf = (uint8_t*)buf + len;
}
pipe->remaining = rem - len;
if ((len < mps) || (rem == len)) {
pipe->buf = NULL;
return true;
}
USB0->CSRL0 = USB_CSRL0_REQPKT;
return false;
}
static bool edpt0_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *buffer, uint16_t buflen)
{
(void)rhport;
unsigned const req = _hcd.bmRequestType;
TU_ASSERT(req != REQUEST_TYPE_INVALID);
TU_ASSERT(dev_addr < sizeof(_hcd.ctl_mps));
USB0->TXFUNCADDR0 = dev_addr;
const unsigned dir_in = tu_edpt_dir(ep_addr);
if (tu_edpt_dir(req) == dir_in) { /* DATA stage */
TU_ASSERT(buffer);
_hcd.pipe0.buf = buffer;
_hcd.pipe0.length = buflen;
_hcd.pipe0.remaining = buflen;
if (dir_in)
USB0->CSRL0 = USB_CSRL0_REQPKT;
else
edpt0_xfer_out();
} else { /* STATUS stage */
_hcd.pipe0.buf = NULL;
_hcd.pipe0.length = 0;
_hcd.pipe0.remaining = 0;
USB0->CSRL0 = USB_CSRL0_STATUS | (dir_in ? USB_CSRL0_REQPKT: USB_CSRL0_TXRDY);
}
return true;
}
static bool pipe_xfer_out(uint_fast8_t pipenum)
{
pipe_state_t *pipe = &_hcd.pipe[pipenum - 1][1];
unsigned const rem = pipe->remaining;
if (!rem) {
pipe->buf = NULL;
return true;
}
hw_endpoint_t volatile *regs = edpt_regs(pipenum - 1);
unsigned const mps = regs->TXMAXP;
unsigned const len = TU_MIN(rem, mps);
void *buf = pipe->buf;
if (len) {
pipe_write_packet(buf, &USB0->FIFO0_WORD + pipenum, len);
pipe->buf = (uint8_t*)buf + len;
}
pipe->remaining = rem - len;
regs->TXCSRL = USB_TXCSRL1_TXRDY;
return false;
}
static bool pipe_xfer_in(uint_fast8_t pipenum)
{
pipe_state_t *pipe = &_hcd.pipe[pipenum - 1][0];
volatile hw_endpoint_t *regs = edpt_regs(pipenum - 1);
TU_ASSERT(regs->RXCSRL & USB_RXCSRL1_RXRDY);
const unsigned mps = regs->RXMAXP;
const unsigned rem = pipe->remaining;
const unsigned vld = regs->RXCOUNT;
const unsigned len = TU_MIN(TU_MIN(rem, mps), vld);
void *buf = pipe->buf;
if (len) {
pipe_read_packet(buf, &USB0->FIFO0_WORD + pipenum, len);
pipe->buf = buf + len;
pipe->remaining = rem - len;
}
if ((len < mps) || (rem == len)) {
pipe->buf = NULL;
return NULL != buf;
}
regs->RXCSRL = USB_RXCSRL1_REQPKT;
return false;
}
static bool edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *buffer, uint16_t buflen)
{
(void)rhport;
unsigned const pipenum = find_pipe(dev_addr, ep_addr);
unsigned const dir_tx = tu_edpt_dir(ep_addr) ? 0: 1;
pipe_state_t *pipe = &_hcd.pipe[pipenum - 1][dir_tx];
pipe->buf = buffer;
pipe->length = buflen;
pipe->remaining = buflen;
if (dir_tx) {
pipe_xfer_out(pipenum);
} else {
volatile hw_endpoint_t *regs = edpt_regs(pipenum - 1);
regs->RXCSRL = USB_RXCSRL1_REQPKT;
}
return true;
}
static void process_ep0(uint8_t rhport)
{
(void)rhport;
uint_fast8_t csrl = USB0->CSRL0;
// TU_LOG1(" EP0 CSRL = %x\n", csrl);
unsigned const dev_addr = USB0->TXFUNCADDR0;
unsigned const req = _hcd.bmRequestType;
if (csrl & (USB_CSRL0_ERROR | USB_CSRL0_NAKTO | USB_CSRL0_STALLED)) {
/* No response / NAK timed out / Stall received */
if (csrl & (USB_CSRL0_RXRDY | USB_CSRL0_TXRDY))
USB0->CSRH0 = USB_CSRH0_FLUSH;
USB0->CSRL0 = 0;
_hcd.bmRequestType = REQUEST_TYPE_INVALID;
uint8_t result = (csrl & USB_CSRL0_STALLED) ? XFER_RESULT_STALLED: XFER_RESULT_FAILED;
if (REQUEST_TYPE_INVALID == req) { /* SETUP */
uint8_t const ep_addr = tu_edpt_addr(0, TUSB_DIR_OUT);
hcd_event_xfer_complete(dev_addr, ep_addr,
_hcd.pipe0.length - _hcd.pipe0.remaining,
result, true);
} else if (csrl & USB_CSRL0_STATUS) { /* STATUS */
uint8_t const ep_addr = tu_edpt_dir(req) ?
tu_edpt_addr(0, TUSB_DIR_OUT): tu_edpt_addr(0, TUSB_DIR_IN);
hcd_event_xfer_complete(dev_addr, ep_addr,
_hcd.pipe0.length - _hcd.pipe0.remaining,
result, true);
} else { /* DATA */
uint8_t const ep_addr = tu_edpt_dir(req) ?
tu_edpt_addr(0, TUSB_DIR_IN): tu_edpt_addr(0, TUSB_DIR_OUT);
hcd_event_xfer_complete(dev_addr, ep_addr,
_hcd.pipe0.length - _hcd.pipe0.remaining,
result, true);
}
return;
}
if (csrl & USB_CSRL0_STATUS) {
/* STATUS IN */
TU_ASSERT(USB_CSRL0_RXRDY == (csrl & USB_CSRL0_RXRDY),);
TU_ASSERT(0 == USB0->COUNT0,);
USB0->CSRH0 = USB_CSRH0_FLUSH;
USB0->CSRL0 = 0;
_hcd.bmRequestType = REQUEST_TYPE_INVALID;
hcd_event_xfer_complete(dev_addr, tu_edpt_addr(0, TUSB_DIR_IN),
0, XFER_RESULT_SUCCESS, true);
return;
}
if (csrl & USB_CSRL0_RXRDY) {
/* DATA IN */
TU_ASSERT(REQUEST_TYPE_INVALID != req,);
TU_ASSERT(_hcd.pipe0.buf,);
if (edpt0_xfer_in()) {
hcd_event_xfer_complete(dev_addr, tu_edpt_addr(0, TUSB_DIR_IN),
_hcd.pipe0.length - _hcd.pipe0.remaining,
XFER_RESULT_SUCCESS, true);
}
return;
}
/* When CSRL0 is zero, it means that completion of sending a any length packet. */
if (!_hcd.pipe0.buf) {
/* STATUS OUT */
TU_ASSERT(REQUEST_TYPE_INVALID != req,);
_hcd.bmRequestType = REQUEST_TYPE_INVALID;
/* EP address is the reverse direction of DATA stage */
uint8_t const ep_addr = tu_edpt_dir(req) ?
tu_edpt_addr(0, TUSB_DIR_OUT): tu_edpt_addr(0, TUSB_DIR_IN);
hcd_event_xfer_complete(dev_addr, ep_addr, 0, XFER_RESULT_SUCCESS, true);
return;
}
if (REQUEST_TYPE_INVALID == req) {
/* SETUP */
_hcd.bmRequestType = *(uint8_t*)_hcd.pipe0.buf;
_hcd.pipe0.buf = NULL;
hcd_event_xfer_complete(dev_addr, tu_edpt_addr(0, TUSB_DIR_OUT),
8, XFER_RESULT_SUCCESS, true);
return;
}
/* DATA OUT */
if (edpt0_xfer_out()) {
hcd_event_xfer_complete(dev_addr, tu_edpt_addr(0, TUSB_DIR_OUT),
_hcd.pipe0.length - _hcd.pipe0.remaining,
XFER_RESULT_SUCCESS, true);
}
}
static void process_pipe_tx(uint8_t rhport, uint_fast8_t pipenum)
{
(void)rhport;
bool completed;
uint8_t result;
volatile hw_endpoint_t *regs = edpt_regs(pipenum - 1);
unsigned const csrl = regs->TXCSRL;
// TU_LOG1(" TXCSRL%d = %x\n", pipenum, csrl);
if (csrl & (USB_TXCSRL1_STALLED | USB_TXCSRL1_ERROR)) {
if (csrl & USB_TXCSRL1_TXRDY)
regs->TXCSRL = (csrl & ~(USB_TXCSRL1_STALLED | USB_TXCSRL1_ERROR)) | USB_TXCSRL1_FLUSH;
else
regs->TXCSRL = csrl & ~(USB_TXCSRL1_STALLED | USB_TXCSRL1_ERROR);
completed = true;
result = (csrl & USB_TXCSRL1_STALLED) ? XFER_RESULT_STALLED: XFER_RESULT_FAILED;
} else {
completed = pipe_xfer_out(pipenum);
result = XFER_RESULT_SUCCESS;
}
if (completed) {
pipe_addr_t *addr = &_hcd.addr[pipenum - 1][1];
pipe_state_t *pipe = &_hcd.pipe[pipenum - 1][1];
hcd_event_xfer_complete(addr->dev, addr->ep,
pipe->length - pipe->remaining,
result, true);
}
}
static void process_pipe_rx(uint8_t rhport, uint_fast8_t pipenum)
{
(void)rhport;
bool completed;
uint8_t result;
volatile hw_endpoint_t *regs = edpt_regs(pipenum - 1);
unsigned const csrl = regs->RXCSRL;
// TU_LOG1(" RXCSRL%d = %x\n", pipenum, csrl);
if (csrl & (USB_RXCSRL1_STALLED | USB_RXCSRL1_ERROR)) {
if (csrl & USB_RXCSRL1_RXRDY)
regs->RXCSRL = (csrl & ~(USB_RXCSRL1_STALLED | USB_RXCSRL1_ERROR)) | USB_RXCSRL1_FLUSH;
else
regs->RXCSRL = csrl & ~(USB_RXCSRL1_STALLED | USB_RXCSRL1_ERROR);
completed = true;
result = (csrl & USB_RXCSRL1_STALLED) ? XFER_RESULT_STALLED: XFER_RESULT_FAILED;
} else {
completed = pipe_xfer_in(pipenum);
result = XFER_RESULT_SUCCESS;
}
if (completed) {
pipe_addr_t *addr = &_hcd.addr[pipenum - 1][0];
pipe_state_t *pipe = &_hcd.pipe[pipenum - 1][0];
hcd_event_xfer_complete(addr->dev, addr->ep,
pipe->length - pipe->remaining,
result, true);
}
}
/*------------------------------------------------------------------
* Host API
*------------------------------------------------------------------*/
bool hcd_init(uint8_t rhport)
{
(void)rhport;
NVIC_ClearPendingIRQ(USB0_IRQn);
_hcd.bmRequestType = REQUEST_TYPE_INVALID;
USB0->DEVCTL |= USB_DEVCTL_SESSION;
USB0->IE = USB_IE_DISCON | USB_IE_CONN | USB_IE_BABBLE | USB_IE_RESUME;
return true;
}
void hcd_int_enable(uint8_t rhport)
{
(void)rhport;
NVIC_EnableIRQ(USB0_IRQn);
}
void hcd_int_disable(uint8_t rhport)
{
(void)rhport;
NVIC_DisableIRQ(USB0_IRQn);
}
uint32_t hcd_frame_number(uint8_t rhport)
{
(void)rhport;
/* The device must be reset at least once after connection
* in order to start the frame counter. */
if (_hcd.need_reset) hcd_port_reset(rhport);
return USB0->FRAME;
}
//--------------------------------------------------------------------+
// Port API
//--------------------------------------------------------------------+
bool hcd_port_connect_status(uint8_t rhport)
{
(void)rhport;
unsigned devctl = USB0->DEVCTL;
if (!(devctl & USB_DEVCTL_HOST)) return false;
if (devctl & (USB_DEVCTL_LSDEV | USB_DEVCTL_FSDEV)) return true;
return false;
}
void hcd_port_reset(uint8_t rhport)
{
(void)rhport;
USB0->POWER |= USB_POWER_HSENAB | USB_POWER_RESET;
unsigned cnt = SystemCoreClock / 1000 * 20;
while (cnt--) __NOP();
USB0->POWER &= ~USB_POWER_RESET;
_hcd.need_reset = false;
}
tusb_speed_t hcd_port_speed_get(uint8_t rhport)
{
(void)rhport;
unsigned devctl = USB0->DEVCTL;
if (devctl & USB_DEVCTL_LSDEV) return TUSB_SPEED_LOW;
if (!(devctl & USB_DEVCTL_FSDEV)) return TUSB_SPEED_INVALID;
if (USB0->POWER & USB_POWER_HSMODE) return TUSB_SPEED_HIGH;
return TUSB_SPEED_FULL;
}
void hcd_device_close(uint8_t rhport, uint8_t dev_addr)
{
(void)rhport;
if (sizeof(_hcd.ctl_mps) <= dev_addr) return;
unsigned const ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
_hcd.ctl_mps[dev_addr] = 0;
if (!dev_addr) return;
pipe_addr_t *p = &_hcd.addr[0][0];
for (unsigned i = 0; i < sizeof(_hcd.addr)/sizeof(_hcd.addr[0]); ++i) {
for (unsigned j = 0; j < 2; ++j, ++p) {
if (dev_addr != p->dev) continue;
hw_addr_t volatile *fadr = (hw_addr_t volatile*)&USB0->TXFUNCADDR0 + i + 1;
hw_endpoint_t volatile *regs = edpt_regs(i);
USB0->EPIDX = i + 1;
if (j) {
USB0->TXIE &= ~TU_BIT(i + 1);
if (regs->TXCSRL & USB_TXCSRL1_TXRDY)
regs->TXCSRL = USB_TXCSRL1_CLRDT | USB_TXCSRL1_FLUSH;
else
regs->TXCSRL = USB_TXCSRL1_CLRDT;
regs->TXMAXP = 0;
regs->TXTYPE = 0;
regs->TXINTERVAL = 0;
fadr->TXFUNCADDR = 0;
fadr->TXHUBADDR = 0;
fadr->TXHUBPORT = 0;
USB0->TXFIFOADD = 0;
USB0->TXFIFOSZ = 0;
} else {
USB0->RXIE &= ~TU_BIT(i + 1);
if (regs->RXCSRL & USB_RXCSRL1_RXRDY)
regs->RXCSRL = USB_RXCSRL1_CLRDT | USB_RXCSRL1_FLUSH;
else
regs->RXCSRL = USB_RXCSRL1_CLRDT;
regs->RXMAXP = 0;
regs->RXTYPE = 0;
regs->RXINTERVAL = 0;
fadr->RXFUNCADDR = 0;
fadr->RXHUBADDR = 0;
fadr->RXHUBPORT = 0;
USB0->RXFIFOADD = 0;
USB0->RXFIFOSZ = 0;
}
p->dev = 0;
p->ep = 0;
pipe_state_t *pipe = &_hcd.pipe[i][j];
pipe->buf = NULL;
pipe->length = 0;
pipe->remaining = 0;
}
}
if (ie) NVIC_EnableIRQ(USB0_IRQn);
}
//--------------------------------------------------------------------+
// Endpoints API
//--------------------------------------------------------------------+
bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8])
{
(void)rhport;
pipe_write_packet((void*)(uintptr_t)setup_packet, &USB0->FIFO0_WORD, 8);
_hcd.pipe0.buf = (void*)(uintptr_t)setup_packet;
_hcd.pipe0.length = 8;
_hcd.pipe0.remaining = 0;
hcd_devtree_info_t devtree;
hcd_devtree_get_info(dev_addr, &devtree);
switch (devtree.speed) {
default: return false;
case TUSB_SPEED_LOW: USB0->TYPE0 = USB_TYPE0_SPEED_LOW; break;
case TUSB_SPEED_FULL: USB0->TYPE0 = USB_TYPE0_SPEED_FULL; break;
case TUSB_SPEED_HIGH: USB0->TYPE0 = USB_TYPE0_SPEED_HIGH; break;
}
USB0->TXHUBADDR0 = devtree.hub_addr;
USB0->TXHUBPORT0 = devtree.hub_port;
USB0->TXFUNCADDR0 = dev_addr;
USB0->CSRL0 = USB_CSRL0_TXRDY | USB_CSRL0_SETUP;
return true;
}
bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc)
{
(void)rhport;
if (sizeof(_hcd.ctl_mps) <= dev_addr) return false;
unsigned const ep_addr = ep_desc->bEndpointAddress;
unsigned const epn = tu_edpt_number(ep_addr);
if (0 == epn) {
_hcd.ctl_mps[dev_addr] = ep_desc->wMaxPacketSize;
return true;
}
unsigned const dir_tx = tu_edpt_dir(ep_addr) ? 0: 1;
/* Find a free pipe */
unsigned pipenum = 0;
pipe_addr_t *p = &_hcd.addr[0][dir_tx];
for (unsigned i = 0; i < sizeof(_hcd.addr)/sizeof(_hcd.addr[0]); ++i, p += 2) {
if (0 == p->ep) {
p->dev = dev_addr;
p->ep = ep_addr;
pipenum = i + 1;
break;
}
}
if (!pipenum) return false;
unsigned const xfer = ep_desc->bmAttributes.xfer;
unsigned const mps = tu_edpt_packet_size(ep_desc);
pipe_state_t *pipe = &_hcd.pipe[pipenum - 1][dir_tx];
pipe->buf = NULL;
pipe->length = 0;
pipe->remaining = 0;
uint8_t pipe_type = 0;
hcd_devtree_info_t devtree;
hcd_devtree_get_info(dev_addr, &devtree);
switch (devtree.speed) {
default: return false;
case TUSB_SPEED_LOW: pipe_type |= USB_TXTYPE1_SPEED_LOW; break;
case TUSB_SPEED_FULL: pipe_type |= USB_TXTYPE1_SPEED_FULL; break;
case TUSB_SPEED_HIGH: pipe_type |= USB_TXTYPE1_SPEED_HIGH; break;
}
switch (xfer) {
default: return false;
case TUSB_XFER_BULK: pipe_type |= USB_TXTYPE1_PROTO_BULK; break;
case TUSB_XFER_INTERRUPT: pipe_type |= USB_TXTYPE1_PROTO_INT; break;
case TUSB_XFER_ISOCHRONOUS: pipe_type |= USB_TXTYPE1_PROTO_ISOC; break;
}
hw_addr_t volatile *fadr = (hw_addr_t volatile*)&USB0->TXFUNCADDR0 + pipenum;
hw_endpoint_t volatile *regs = edpt_regs(pipenum - 1);
if (dir_tx) {
fadr->TXFUNCADDR = dev_addr;
fadr->TXHUBADDR = devtree.hub_addr;
fadr->TXHUBPORT = devtree.hub_port;
regs->TXMAXP = mps;
regs->TXTYPE = pipe_type | epn;
regs->TXINTERVAL = ep_desc->bInterval;
if (regs->TXCSRL & USB_TXCSRL1_TXRDY)
regs->TXCSRL = USB_TXCSRL1_CLRDT | USB_TXCSRL1_FLUSH;
else
regs->TXCSRL = USB_TXCSRL1_CLRDT;
USB0->TXIE |= TU_BIT(pipenum);
} else {
fadr->RXFUNCADDR = dev_addr;
fadr->RXHUBADDR = devtree.hub_addr;
fadr->RXHUBPORT = devtree.hub_port;
regs->RXMAXP = mps;
regs->RXTYPE = pipe_type | epn;
regs->RXINTERVAL = ep_desc->bInterval;
if (regs->RXCSRL & USB_RXCSRL1_RXRDY)
regs->RXCSRL = USB_RXCSRL1_CLRDT | USB_RXCSRL1_FLUSH;
else
regs->RXCSRL = USB_RXCSRL1_CLRDT;
USB0->RXIE |= TU_BIT(pipenum);
}
/* Setup FIFO */
int size_in_log2_minus3 = 28 - TU_MIN(28, __CLZ((uint32_t)mps));
if ((8u << size_in_log2_minus3) < mps) ++size_in_log2_minus3;
unsigned addr = find_free_memory(size_in_log2_minus3);
TU_ASSERT(addr);
USB0->EPIDX = pipenum;
if (dir_tx) {
USB0->TXFIFOADD = addr;
USB0->TXFIFOSZ = size_in_log2_minus3;
} else {
USB0->RXFIFOADD = addr;
USB0->RXFIFOSZ = size_in_log2_minus3;
}
return true;
}
bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *buffer, uint16_t buflen)
{
(void)rhport;
bool ret = false;
if (0 == tu_edpt_number(ep_addr)) {
ret = edpt0_xfer(rhport, dev_addr, ep_addr, buffer, buflen);
} else {
ret = edpt_xfer(rhport, dev_addr, ep_addr, buffer, buflen);
}
return ret;
}
// clear stall, data toggle is also reset to DATA0
bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr)
{
unsigned const pipenum = find_pipe(dev_addr, ep_addr);
if (!pipenum) return false;
hw_endpoint_t volatile *regs = edpt_regs(pipenum - 1);
unsigned const dir_tx = tu_edpt_dir(ep_addr) ? 0: 1;
if (dir_tx)
regs->TXCSRL = USB_TXCSRL1_CLRDT;
else
regs->RXCSRL = USB_RXCSRL1_CLRDT;
return true;
}
/*-------------------------------------------------------------------
* ISR
*-------------------------------------------------------------------*/
void hcd_int_handler(uint8_t rhport)
{
uint_fast8_t is, txis, rxis;
is = USB0->IS; /* read and clear interrupt status */
txis = USB0->TXIS; /* read and clear interrupt status */
rxis = USB0->RXIS; /* read and clear interrupt status */
// TU_LOG1("D%2x T%2x R%2x\n", is, txis, rxis);
is &= USB0->IE; /* Clear disabled interrupts */
if (is & USB_IS_RESUME) {
}
if (is & USB_IS_CONN) {
_hcd.need_reset = true;
hcd_event_device_attach(rhport, true);
}
if (is & USB_IS_DISCON) {
hcd_event_device_remove(rhport, true);
}
if (is & USB_IS_BABBLE) {
}
txis &= USB0->TXIE; /* Clear disabled interrupts */
if (txis & USB_TXIE_EP0) {
process_ep0(rhport);
txis &= ~TU_BIT(0);
}
while (txis) {
unsigned const num = __builtin_ctz(txis);
process_pipe_tx(rhport, num);
txis &= ~TU_BIT(num);
}
rxis &= USB0->RXIE; /* Clear disabled interrupts */
while (rxis) {
unsigned const num = __builtin_ctz(rxis);
process_pipe_rx(rhport, num);
rxis &= ~TU_BIT(num);
}
}
#endif
+40
View File
@@ -0,0 +1,40 @@
/*
* 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_MUSB_MSP432E_H_
#define _TUSB_MUSB_MSP432E_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "msp.h"
#ifdef __cplusplus
}
#endif
#endif
+45
View File
@@ -0,0 +1,45 @@
/*
* 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_MUSB_TM4C_H_
#define _TUSB_MUSB_TM4C_H_
#ifdef __cplusplus
extern "C" {
#endif
#if CFG_TUSB_MCU == OPT_MCU_TM4C123
#include "TM4C123.h"
//#elif CFG_TUSB_MCU == OPT_MCU_TM4C129
#else
#error "Unsupported MCUs"
#endif
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large Load Diff
+10 -2
View File
@@ -214,14 +214,14 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
UsbDeviceDescBank* bank = &sram_registers[epnum][dir];
uint32_t size_value = 0;
while (size_value < 7) {
if (1 << (size_value + 3) == desc_edpt->wMaxPacketSize.size) {
if (1 << (size_value + 3) == tu_edpt_packet_size(desc_edpt)) {
break;
}
size_value++;
}
// unsupported endpoint size
if ( size_value == 7 && desc_edpt->wMaxPacketSize.size != 1023 ) return false;
if ( size_value == 7 && tu_edpt_packet_size(desc_edpt) != 1023 ) return false;
bank->PCKSIZE.bit.SIZE = size_value;
@@ -230,16 +230,24 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
if ( dir == TUSB_DIR_OUT )
{
ep->EPCFG.bit.EPTYPE0 = desc_edpt->bmAttributes.xfer + 1;
ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ0 | USB_DEVICE_EPSTATUSCLR_DTGLOUT; // clear stall & dtoggle
ep->EPINTENSET.bit.TRCPT0 = true;
}else
{
ep->EPCFG.bit.EPTYPE1 = desc_edpt->bmAttributes.xfer + 1;
ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ1 | USB_DEVICE_EPSTATUSCLR_DTGLIN; // clear stall & dtoggle
ep->EPINTENSET.bit.TRCPT1 = true;
}
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
{
(void) rhport;
+7 -1
View File
@@ -258,7 +258,7 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
// Must not already enabled
TU_ASSERT((UDP->UDP_CSR[epnum] & UDP_CSR_EPEDS_Msk) == 0);
xfer_epsize_set(&_dcd_xfer[epnum], ep_desc->wMaxPacketSize.size);
xfer_epsize_set(&_dcd_xfer[epnum], tu_edpt_packet_size(ep_desc));
// Configure type and enable EP
csr_write(epnum, UDP_CSR_EPEDS_Msk | UDP_CSR_EPTYPE(ep_desc->bmAttributes.xfer + 4*dir));
@@ -269,6 +269,12 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack
bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
{
+8 -2
View File
@@ -84,7 +84,7 @@ static xfer_ctl_t xfer_status[EP_MAX];
static const tusb_desc_endpoint_t ep0_desc =
{
.bEndpointAddress = 0x00,
.wMaxPacketSize = { .size = CFG_TUD_ENDPOINT0_SIZE },
.wMaxPacketSize = CFG_TUD_ENDPOINT0_SIZE,
};
TU_ATTR_ALWAYS_INLINE static inline void CleanInValidateCache(uint32_t *addr, int32_t size)
@@ -460,7 +460,7 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_desc->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(ep_desc->bEndpointAddress);
uint16_t const epMaxPktSize = ep_desc->wMaxPacketSize.size;
uint16_t const epMaxPktSize = tu_edpt_packet_size(ep_desc);
tusb_xfer_type_t const eptype = (tusb_xfer_type_t)ep_desc->bmAttributes.xfer;
uint8_t fifoSize = 0; // FIFO size
uint16_t defaultEndpointSize = 8; // Default size of Endpoint
@@ -544,6 +544,12 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
}
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
@@ -283,7 +283,7 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
/* Response with status first before changing device address */
dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0);
}
extern u32 SystemCoreClock ;
extern u32 SystemCoreClock;
void dcd_remote_wakeup(uint8_t rhport)
{
(void) rhport;
@@ -323,7 +323,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
/* No support for control transfer */
TU_ASSERT(epn && (xfer != TUSB_XFER_CONTROL));
ep->max_packet_size = ep_desc->wMaxPacketSize.size;
ep->max_packet_size = tu_edpt_packet_size(ep_desc);
unsigned val = USB_ENDPT_EPCTLDIS_MASK;
val |= (xfer != TUSB_XFER_ISOCHRONOUS) ? USB_ENDPT_EPHSHK_MASK: 0;
val |= dir ? USB_ENDPT_EPTXEN_MASK : USB_ENDPT_EPRXEN_MASK;
@@ -339,6 +339,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
+130 -80
View File
@@ -63,7 +63,7 @@ typedef struct
uint8_t* buffer;
uint16_t total_len;
volatile uint16_t actual_len;
uint16_t mps; // max packet size
uint16_t mps; // max packet size
// nRF will auto accept OUT packet after DMA is done
// indicate packet is already ACK
@@ -82,11 +82,8 @@ static struct
// +1 for ISO endpoints
xfer_td_t xfer[EP_CBI_COUNT + 1][2];
// Number of pending DMA that is started but not handled yet by dcd_int_handler().
// Since nRF can only carry one DMA can run at a time, this value is normally be either 0 or 1.
// However, in critical section with interrupt disabled, the DMA can be finished and added up
// until handled by dcd_int_handler() when exiting critical section.
volatile uint8_t dma_pending;
// nRF can only carry one DMA at a time, this is used to guard the access to EasyDMA
volatile bool dma_running;
}_dcd;
/*------------------------------------------------------------------*/
@@ -115,67 +112,68 @@ TU_ATTR_ALWAYS_INLINE static inline bool is_in_isr(void)
}
// helper to start DMA
static void start_dma(volatile uint32_t* reg_startep)
{
_dcd.dma_running = true;
(*reg_startep) = 1;
__ISB(); __DSB();
// TASKS_EP0STATUS, TASKS_EP0RCVOUT seem to need EasyDMA to be available
// However these don't trigger any DMA transfer and got ENDED event subsequently
// Therefore dma_pending is corrected right away
if ( (reg_startep == &NRF_USBD->TASKS_EP0STATUS) || (reg_startep == &NRF_USBD->TASKS_EP0RCVOUT) )
{
_dcd.dma_running = false;
}
}
// only 1 EasyDMA can be active at any time
// TODO use Cortex M4 LDREX and STREX command (atomic) to have better mutex access to EasyDMA
// since current implementation does not 100% guarded against race condition
static void edpt_dma_start(volatile uint32_t* reg_startep)
{
// Only one dma can be active
if ( _dcd.dma_pending )
// Called in critical section i.e within USB ISR, or USB/Global interrupt disabled
if ( is_in_isr() || __get_PRIMASK() || !NVIC_GetEnableIRQ(USBD_IRQn) )
{
if (is_in_isr())
if (_dcd.dma_running)
{
// Called within ISR, use usbd task to defer later
usbd_defer_func( (osal_task_func_t) edpt_dma_start, (void*) reg_startep, true );
return;
//use usbd task to defer later
usbd_defer_func((osal_task_func_t) edpt_dma_start, (void*) (uintptr_t) reg_startep, true);
}else
{
start_dma(reg_startep);
}
else
}else
{
// Called in non-critical thread-mode, should be 99% of the time.
// Should be safe to blocking wait until previous DMA transfer complete
uint8_t const rhport = 0;
bool started = false;
while(!started)
{
if ( __get_PRIMASK() || !NVIC_GetEnableIRQ(USBD_IRQn) )
{
// Called in critical section with interrupt disabled. We have to manually check
// for the DMA complete by comparing current pending DMA with number of ENDED Events
uint32_t ended = 0;
// LDREX/STREX may be needed in form of std atomic (required C11) or
// use osal mutex to guard against multiple core MCUs such as nRF53
dcd_int_disable(rhport);
while ( _dcd.dma_pending > ((uint8_t) ended) )
{
ended = NRF_USBD->EVENTS_ENDISOIN + NRF_USBD->EVENTS_ENDISOOUT;
for (uint8_t i=0; i<EP_CBI_COUNT; i++)
{
ended += NRF_USBD->EVENTS_ENDEPIN[i] + NRF_USBD->EVENTS_ENDEPOUT[i];
}
}
}else
if ( !_dcd.dma_running )
{
// Called in non-critical thread-mode, should be 99% of the time.
// Should be safe to blocking wait until previous DMA transfer complete
while ( _dcd.dma_pending ) { }
start_dma(reg_startep);
started = true;
}
dcd_int_enable(rhport);
// osal_yield();
}
}
_dcd.dma_pending++;
(*reg_startep) = 1;
__ISB(); __DSB();
}
// DMA is complete
static void edpt_dma_end(void)
{
TU_ASSERT(_dcd.dma_pending, );
_dcd.dma_pending = 0;
}
// helper to set TASKS_EP0STATUS / TASKS_EP0RCVOUT since they also need EasyDMA
// However TASKS_EP0STATUS doesn't trigger any DMA transfer and got ENDED event subsequently
// Therefore dma_running state will be corrected right away
void start_ep0_task(volatile uint32_t* reg_task)
{
edpt_dma_start(reg_task);
// correct the dma_running++ in dma start
if (_dcd.dma_pending) _dcd.dma_pending--;
TU_ASSERT(_dcd.dma_running, );
_dcd.dma_running = false;
}
// helper getting td
@@ -194,7 +192,10 @@ static void xact_out_dma(uint8_t epnum)
{
xact_len = NRF_USBD->SIZE.ISOOUT;
// If ZERO bit is set, ignore ISOOUT length
if (xact_len & USBD_SIZE_ISOOUT_ZERO_Msk) xact_len = 0;
if (xact_len & USBD_SIZE_ISOOUT_ZERO_Msk)
{
xact_len = 0;
}
else
{
// Trigger DMA move data from Endpoint -> SRAM
@@ -206,7 +207,8 @@ static void xact_out_dma(uint8_t epnum)
}
else
{
xact_len = (uint8_t)NRF_USBD->SIZE.EPOUT[epnum];
// limit xact len to remaining length
xact_len = tu_min16((uint16_t) NRF_USBD->SIZE.EPOUT[epnum], xfer->total_len - xfer->actual_len);
// Trigger DMA move data from Endpoint -> SRAM
NRF_USBD->EPOUT[epnum].PTR = (uint32_t) xfer->buffer;
@@ -214,9 +216,6 @@ static void xact_out_dma(uint8_t epnum)
edpt_dma_start(&NRF_USBD->TASKS_STARTEPOUT[epnum]);
}
xfer->buffer += xact_len;
xfer->actual_len += xact_len;
}
// Prepare for a CBI transaction IN, call at the start
@@ -231,8 +230,6 @@ static void xact_in_dma(uint8_t epnum)
NRF_USBD->EPIN[epnum].PTR = (uint32_t) xfer->buffer;
NRF_USBD->EPIN[epnum].MAXCNT = xact_len;
xfer->buffer += xact_len;
edpt_dma_start(&NRF_USBD->TASKS_STARTEPIN[epnum]);
}
@@ -241,6 +238,7 @@ static void xact_in_dma(uint8_t epnum)
//--------------------------------------------------------------------+
void dcd_init (uint8_t rhport)
{
TU_LOG1("dcd init\r\n");
(void) rhport;
}
@@ -306,10 +304,11 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(desc_edpt->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(desc_edpt->bEndpointAddress);
uint8_t const ep_addr = desc_edpt->bEndpointAddress;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
_dcd.xfer[epnum][dir].mps = desc_edpt->wMaxPacketSize.size;
_dcd.xfer[epnum][dir].mps = tu_edpt_packet_size(desc_edpt);
if (desc_edpt->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS)
{
@@ -359,11 +358,48 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
NRF_USBD->EPINEN |= USBD_EPINEN_ISOIN_Msk;
}
}
// clear stall and reset DataToggle
NRF_USBD->EPSTALL = (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | ep_addr;
NRF_USBD->DTOGGLE = (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos) | ep_addr;
__ISB(); __DSB();
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
// disable interrupt to prevent race condition
dcd_int_disable(rhport);
// disable all non-control (bulk + interrupt) endpoints
for ( uint8_t ep = 1; ep < EP_CBI_COUNT; ep++ )
{
NRF_USBD->INTENCLR = TU_BIT(USBD_INTEN_ENDEPOUT0_Pos + ep) | TU_BIT(USBD_INTEN_ENDEPIN0_Pos + ep);
NRF_USBD->TASKS_STARTEPIN[ep] = 0;
NRF_USBD->TASKS_STARTEPOUT[ep] = 0;
tu_memclr(_dcd.xfer[ep], 2*sizeof(xfer_td_t));
}
// disable both ISO
NRF_USBD->INTENCLR = USBD_INTENCLR_SOF_Msk | USBD_INTENCLR_ENDISOOUT_Msk | USBD_INTENCLR_ENDISOIN_Msk;
NRF_USBD->ISOSPLIT = USBD_ISOSPLIT_SPLIT_OneDir;
NRF_USBD->TASKS_STARTISOIN = 0;
NRF_USBD->TASKS_STARTISOOUT = 0;
tu_memclr(_dcd.xfer[EP_ISO_NUM], 2*sizeof(xfer_td_t));
// de-activate all non-control
NRF_USBD->EPOUTEN = 1UL;
NRF_USBD->EPINEN = 1UL;
dcd_int_enable(rhport);
}
void dcd_edpt_close (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
@@ -427,7 +463,7 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t
if ( control_status )
{
// Status Phase also requires EasyDMA has to be available as well !!!!
start_ep0_task(&NRF_USBD->TASKS_EP0STATUS);
edpt_dma_start(&NRF_USBD->TASKS_EP0STATUS);
// The nRF doesn't interrupt on status transmit so we queue up a success response.
dcd_event_xfer_complete(0, ep_addr, 0, XFER_RESULT_SUCCESS, is_in_isr());
@@ -437,15 +473,14 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t
if ( epnum == 0 )
{
// Accept next Control Out packet. TASKS_EP0RCVOUT also require EasyDMA
start_ep0_task(&NRF_USBD->TASKS_EP0RCVOUT);
edpt_dma_start(&NRF_USBD->TASKS_EP0RCVOUT);
}else
{
if ( xfer->data_received )
{
// Data may already be received previously
xfer->data_received = false;
// Data is already received previously
// start DMA to copy to SRAM
xfer->data_received = false;
xact_out_dma(epnum);
}
else
@@ -467,7 +502,11 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t
void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
xfer_td_t* xfer = get_td(epnum, dir);
if ( epnum == 0 )
{
@@ -475,6 +514,14 @@ void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr)
}else if (epnum != EP_ISO_NUM)
{
NRF_USBD->EPSTALL = (USBD_EPSTALL_STALL_Stall << USBD_EPSTALL_STALL_Pos) | ep_addr;
// Note: nRF can auto ACK packet OUT before get stalled.
// There maybe data in endpoint fifo already, we need to pull it out
if ( (dir == TUSB_DIR_OUT) && xfer->data_received )
{
xfer->data_received = false;
xact_out_dma(epnum);
}
}
__ISB(); __DSB();
@@ -488,14 +535,16 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr)
if ( epnum != 0 && epnum != EP_ISO_NUM )
{
// reset data toggle to DATA0
// First write this register with VALUE=Nop to select the endpoint, then either read it to get the status from
// VALUE, or write it again with VALUE=Data0 or Data1
NRF_USBD->DTOGGLE = ep_addr;
NRF_USBD->DTOGGLE = (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos) | ep_addr;
// clear stall
NRF_USBD->EPSTALL = (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | ep_addr;
// reset data toggle to DATA0
NRF_USBD->DTOGGLE = (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos) | ep_addr;
// Write any value to SIZE register will allow nRF to ACK/accept data
// Drop any pending data
if (dir == TUSB_DIR_OUT) NRF_USBD->SIZE.EPOUT[epnum] = 0;
__ISB(); __DSB();
@@ -508,7 +557,9 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr)
void bus_reset(void)
{
// 6.35.6 USB controller automatically disabled all endpoints (except control)
// i.e EPOUTEN and EPINEN and reset USBADDR to 0
NRF_USBD->EPOUTEN = 1UL;
NRF_USBD->EPINEN = 1UL;
for(int i=0; i<8; i++)
{
NRF_USBD->TASKS_STARTEPIN[i] = 0;
@@ -662,7 +713,8 @@ void dcd_int_handler(uint8_t rhport)
if ( int_status & EDPT_END_ALL_MASK )
{
// DMA complete move data from SRAM -> Endpoint
// DMA complete move data from SRAM <-> Endpoint
// Must before endpoint transfer handling
edpt_dma_end();
}
@@ -677,7 +729,7 @@ void dcd_int_handler(uint8_t rhport)
* - Host -> Endpoint
* EPDATA (or EP0DATADONE) interrupted, check EPDATASTATUS.EPOUT[i]
* to start DMA. For Bulk/Interrupt, this step can occur automatically (without sw),
* which means data may or may not be ready (data_received flag).
* which means data may or may not be ready (out_received flag).
* - Endpoint -> RAM
* ENDEPOUT[i] interrupted, transaction complete, sw prepare next transaction
*
@@ -709,20 +761,16 @@ void dcd_int_handler(uint8_t rhport)
xfer_td_t* xfer = get_td(epnum, TUSB_DIR_OUT);
uint8_t const xact_len = NRF_USBD->EPOUT[epnum].AMOUNT;
xfer->buffer += xact_len;
xfer->actual_len += xact_len;
// Transfer complete if transaction len < Max Packet Size or total len is transferred
if ( (epnum != EP_ISO_NUM) && (xact_len == xfer->mps) && (xfer->actual_len < xfer->total_len) )
{
if ( epnum == 0 )
{
// Accept next Control Out packet. TASKS_EP0RCVOUT also require EasyDMA
if ( _dcd.dma_pending )
{
// use usbd task to defer later
usbd_defer_func( (osal_task_func_t) start_ep0_task, (void*) &NRF_USBD->TASKS_EP0RCVOUT, true );
}else
{
start_ep0_task(&NRF_USBD->TASKS_EP0RCVOUT);
}
edpt_dma_start(&NRF_USBD->TASKS_EP0RCVOUT);
}else
{
// nRF auto accept next Bulk/Interrupt OUT packet
@@ -759,8 +807,10 @@ void dcd_int_handler(uint8_t rhport)
if ( tu_bit_test(data_status, epnum) || (epnum == 0 && is_control_in) )
{
xfer_td_t* xfer = get_td(epnum, TUSB_DIR_IN);
uint8_t const xact_len = NRF_USBD->EPIN[epnum].AMOUNT;
xfer->actual_len += NRF_USBD->EPIN[epnum].MAXCNT;
xfer->buffer += xact_len;
xfer->actual_len += xact_len;
if ( xfer->actual_len < xfer->total_len )
{
+7 -1
View File
@@ -251,7 +251,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
/* mine the data for the information we need */
int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
int const size = p_endpoint_desc->wMaxPacketSize.size;
int const size = tu_edpt_packet_size(p_endpoint_desc);
tusb_xfer_type_t const type = (tusb_xfer_type_t) p_endpoint_desc->bmAttributes.xfer;
struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP];
@@ -273,6 +273,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
{
(void) rhport;
+32 -12
View File
@@ -200,11 +200,10 @@ static void bus_reset(void)
}
/* centralized location for USBD interrupt enable bit mask */
#if USE_SOF
static const uint32_t enabled_irqs = USBD_INTSTS_VBDETIF_Msk | USBD_INTSTS_BUSIF_Msk | USBD_INTSTS_SETUP_Msk | USBD_INTSTS_USBIF_Msk | USBD_INTSTS_SOFIF_Msk;
#else
static const uint32_t enabled_irqs = USBD_INTSTS_VBDETIF_Msk | USBD_INTSTS_BUSIF_Msk | USBD_INTSTS_SETUP_Msk | USBD_INTSTS_USBIF_Msk;
#endif
enum {
ENABLED_IRQS = USBD_INTSTS_VBDETIF_Msk | USBD_INTSTS_BUSIF_Msk | USBD_INTSTS_SETUP_Msk |
USBD_INTSTS_USBIF_Msk | (USE_SOF ? USBD_INTSTS_SOFIF_Msk : 0)
};
/*
NUC121/NUC125/NUC126 TinyUSB API driver implementation
@@ -226,8 +225,8 @@ void dcd_init(uint8_t rhport)
usb_attach();
USBD->INTSTS = enabled_irqs;
USBD->INTEN = enabled_irqs;
USBD->INTSTS = ENABLED_IRQS;
USBD->INTEN = ENABLED_IRQS;
}
void dcd_int_enable(uint8_t rhport)
@@ -252,10 +251,23 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
// do it at dcd_edpt0_status_complete()
}
static void remote_wakeup_delay(void)
{
// try to delay for 1 ms
uint32_t count = SystemCoreClock / 1000;
while(count--) __NOP();
}
void dcd_remote_wakeup(uint8_t rhport)
{
(void) rhport;
USBD->ATTR = USBD_ATTR_RWAKEUP_Msk;
// Enable PHY before sending Resume('K') state
USBD->ATTR |= USBD_ATTR_PHYEN_Msk;
USBD->ATTR |= USBD_ATTR_RWAKEUP_Msk;
// Per specs: remote wakeup signal bit must be clear within 1-15ms
remote_wakeup_delay();
USBD->ATTR &=~USBD_ATTR_RWAKEUP_Msk;
}
bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
@@ -267,7 +279,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
/* mine the data for the information we need */
int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
int const size = p_endpoint_desc->wMaxPacketSize.size;
int const size = tu_edpt_packet_size(p_endpoint_desc);
tusb_xfer_type_t const type = (tusb_xfer_type_t) p_endpoint_desc->bmAttributes.xfer;
struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP];
@@ -289,6 +301,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
{
(void) rhport;
@@ -361,14 +379,16 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
USBD_EP_T *ep = ep_entry(ep_addr, false);
ep->CFG |= USBD_CFG_CSTALL_Msk;
ep->CFG = (ep->CFG & ~USBD_CFG_DSQSYNC_Msk) | USBD_CFG_CSTALL_Msk;
}
void dcd_int_handler(uint8_t rhport)
{
(void) rhport;
uint32_t status = USBD->INTSTS;
// Mask non-enabled irqs, ex. SOF
uint32_t status = USBD->INTSTS & (ENABLED_IRQS | 0xffffff00);
#ifdef SUPPORT_LPM
uint32_t state = USBD->ATTR & 0x300f;
#else
@@ -499,7 +519,7 @@ void dcd_int_handler(uint8_t rhport)
}
/* acknowledge all interrupts */
USBD->INTSTS = status & enabled_irqs;
USBD->INTSTS = status & ENABLED_IRQS;
}
// Invoked when a control transfer's status stage is complete.
+13 -2
View File
@@ -144,7 +144,9 @@ static USBD_EP_T *ep_entry(uint8_t ep_addr, bool add)
enum ep_enum ep_index;
struct xfer_ctl_t *xfer;
for (ep_index = PERIPH_EPA, xfer = &xfer_table[PERIPH_EPA], ep = USBD->EP; ep_index < PERIPH_MAX_EP; ep_index++, xfer++, ep++)
for (ep_index = PERIPH_EPA, xfer = &xfer_table[PERIPH_EPA], ep = USBD->EP;
ep_index < PERIPH_MAX_EP;
ep_index++, xfer++, ep++)
{
if (add)
{
@@ -325,7 +327,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
/* mine the data for the information we need */
int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
int const size = p_endpoint_desc->wMaxPacketSize.size;
int const size = tu_edpt_packet_size(p_endpoint_desc);
tusb_xfer_type_t const type = p_endpoint_desc->bmAttributes.xfer;
struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP];
@@ -353,6 +355,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
{
(void) rhport;
@@ -390,6 +398,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t to
/* mine the data for the information we need */
tusb_dir_t dir = tu_edpt_dir(ep_addr);
USBD_EP_T *ep = ep_entry(ep_addr, false);
TU_ASSERT(ep);
struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP];
/* store away the information we'll needing now and later */
@@ -451,6 +460,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
if (tu_edpt_number(ep_addr))
{
USBD_EP_T *ep = ep_entry(ep_addr, false);
TU_ASSERT(ep, );
ep->EPRSPCTL = (ep->EPRSPCTL & 0xf7) | USBD_EPRSPCTL_HALT_Msk;
}
else
@@ -466,6 +476,7 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
if (tu_edpt_number(ep_addr))
{
USBD_EP_T *ep = ep_entry(ep_addr, false);
TU_ASSERT(ep, );
ep->EPRSPCTL = USBD_EPRSPCTL_TOGGLE_Msk;
}
}
+160 -82
View File
@@ -52,23 +52,23 @@ typedef struct TU_ATTR_PACKED
struct {
union {
struct {
uint16_t : 2;
uint16_t tok_pid : 4;
uint16_t data : 1;
uint16_t own : 1;
uint16_t : 8;
uint16_t : 2;
__IO uint16_t tok_pid : 4;
uint16_t data : 1;
__IO uint16_t own : 1;
uint16_t : 8;
};
struct {
uint16_t : 2;
uint16_t bdt_stall: 1;
uint16_t dts : 1;
uint16_t ninc : 1;
uint16_t keep : 1;
uint16_t : 10;
uint16_t : 2;
uint16_t bdt_stall : 1;
uint16_t dts : 1;
uint16_t ninc : 1;
uint16_t keep : 1;
uint16_t : 10;
};
};
uint16_t bc : 10;
uint16_t : 6;
__IO uint16_t bc : 10;
uint16_t : 6;
};
};
uint8_t *addr;
@@ -120,10 +120,8 @@ static void prepare_next_setup_packet(uint8_t rhport)
{
const unsigned out_odd = _dcd.endpoint[0][0].odd;
const unsigned in_odd = _dcd.endpoint[0][1].odd;
if (_dcd.bdt[0][0][out_odd].own) {
TU_LOG1("DCD fail to prepare the next SETUP %d %d\r\n", out_odd, in_odd);
return;
}
TU_ASSERT(0 == _dcd.bdt[0][0][out_odd].own, );
_dcd.bdt[0][0][out_odd].data = 0;
_dcd.bdt[0][0][out_odd ^ 1].data = 1;
_dcd.bdt[0][1][in_odd].data = 1;
@@ -134,10 +132,16 @@ static void prepare_next_setup_packet(uint8_t rhport)
static void process_stall(uint8_t rhport)
{
if (KHCI->ENDPOINT[0].ENDPT & USB_ENDPT_EPSTALL_MASK) {
/* clear stall condition of the control pipe */
prepare_next_setup_packet(rhport);
KHCI->ENDPOINT[0].ENDPT &= ~USB_ENDPT_EPSTALL_MASK;
for (int i = 0; i < 16; ++i) {
unsigned const endpt = KHCI->ENDPOINT[i].ENDPT;
if (endpt & USB_ENDPT_EPSTALL_MASK) {
// prepare next setup if endpoint0
if ( i == 0 ) prepare_next_setup_packet(rhport);
// clear stall bit
KHCI->ENDPOINT[i].ENDPT = endpt & ~USB_ENDPT_EPSTALL_MASK;
}
}
}
@@ -145,12 +149,17 @@ static void process_tokdne(uint8_t rhport)
{
const unsigned s = KHCI->STAT;
KHCI->ISTAT = USB_ISTAT_TOKDNE_MASK; /* fetch the next token if received */
uint8_t const epnum = (s >> USB_STAT_ENDP_SHIFT);
uint8_t const dir = (s & USB_STAT_TX_MASK) >> USB_STAT_TX_SHIFT;
unsigned const odd = (s & USB_STAT_ODD_MASK) ? 1 : 0;
buffer_descriptor_t *bd = (buffer_descriptor_t *)&_dcd.bda[s];
endpoint_state_t *ep = &_dcd.endpoint_unified[s >> 3];
unsigned odd = (s & USB_STAT_ODD_MASK) ? 1 : 0;
/* fetch pid before discarded by the next steps */
const unsigned pid = bd->tok_pid;
/* reset values for a next transfer */
bd->bdt_stall = 0;
bd->dts = 1;
@@ -163,9 +172,6 @@ static void process_tokdne(uint8_t rhport)
KHCI->CTL &= ~USB_CTL_TXSUSPENDTOKENBUSY_MASK;
return;
}
if (s >> 4) {
TU_LOG1("TKDNE %x\r\n", s);
}
const unsigned bc = bd->bc;
const unsigned remaining = ep->remaining - bc;
@@ -184,9 +190,9 @@ static void process_tokdne(uint8_t rhport)
}
const unsigned length = ep->length;
dcd_event_xfer_complete(rhport,
((s & USB_STAT_TX_MASK) << 4) | (s >> USB_STAT_ENDP_SHIFT),
tu_edpt_addr(epnum, dir),
length - remaining, XFER_RESULT_SUCCESS, true);
if (0 == (s & USB_STAT_ENDP_MASK) && 0 == length) {
if (0 == epnum && 0 == length) {
/* After completion a ZLP of control transfer,
* it prepares for the next steup transfer. */
if (_dcd.addr) {
@@ -204,7 +210,8 @@ static void process_bus_reset(uint8_t rhport)
KHCI->USBCTRL &= ~USB_USBCTRL_SUSP_MASK;
KHCI->CTL |= USB_CTL_ODDRST_MASK;
KHCI->ADDR = 0;
KHCI->INTEN = (KHCI->INTEN & ~USB_INTEN_RESUMEEN_MASK) | USB_INTEN_SLEEPEN_MASK;
KHCI->INTEN = USB_INTEN_USBRSTEN_MASK | USB_INTEN_TOKDNEEN_MASK | USB_INTEN_SLEEPEN_MASK |
USB_INTEN_ERROREN_MASK | USB_INTEN_STALLEN_MASK;
KHCI->ENDPOINT[0].ENDPT = USB_ENDPT_EPHSHK_MASK | USB_ENDPT_EPRXEN_MASK | USB_ENDPT_EPTXEN_MASK;
for (unsigned i = 1; i < 16; ++i) {
@@ -229,21 +236,27 @@ static void process_bus_reset(uint8_t rhport)
dcd_event_bus_reset(rhport, TUSB_SPEED_FULL, true);
}
static void process_bus_inactive(uint8_t rhport)
static void process_bus_sleep(uint8_t rhport)
{
(void) rhport;
// Enable resume & disable suspend interrupt
const unsigned inten = KHCI->INTEN;
KHCI->INTEN = (inten & ~USB_INTEN_SLEEPEN_MASK) | USB_INTEN_RESUMEEN_MASK;
KHCI->USBTRC0 |= USB_USBTRC0_USBRESMEN_MASK;
KHCI->USBCTRL |= USB_USBCTRL_SUSP_MASK;
dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true);
}
static void process_bus_active(uint8_t rhport)
static void process_bus_resume(uint8_t rhport)
{
(void) rhport;
KHCI->USBCTRL &= ~USB_USBCTRL_SUSP_MASK;
// Enable suspend & disable resume interrupt
const unsigned inten = KHCI->INTEN;
KHCI->USBCTRL &= ~USB_USBCTRL_SUSP_MASK; // will also clear USB_USBTRC0_USB_RESUME_INT_MASK
KHCI->USBTRC0 &= ~USB_USBTRC0_USBRESMEN_MASK;
KHCI->INTEN = (inten & ~USB_INTEN_RESUMEEN_MASK) | USB_INTEN_SLEEPEN_MASK;
dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true);
}
@@ -256,12 +269,15 @@ void dcd_init(uint8_t rhport)
KHCI->USBTRC0 |= USB_USBTRC0_USBRESET_MASK;
while (KHCI->USBTRC0 & USB_USBTRC0_USBRESET_MASK);
tu_memclr(&_dcd, sizeof(_dcd));
KHCI->USBTRC0 |= TU_BIT(6); /* software must set this bit to 1 */
KHCI->BDTPAGE1 = (uint8_t)((uintptr_t)_dcd.bdt >> 8);
KHCI->BDTPAGE2 = (uint8_t)((uintptr_t)_dcd.bdt >> 16);
KHCI->BDTPAGE3 = (uint8_t)((uintptr_t)_dcd.bdt >> 24);
KHCI->INTEN = USB_INTEN_USBRSTEN_MASK;
dcd_connect(rhport);
NVIC_ClearPendingIRQ(USB0_IRQn);
}
@@ -269,8 +285,6 @@ void dcd_init(uint8_t rhport)
void dcd_int_enable(uint8_t rhport)
{
(void) rhport;
KHCI->INTEN = USB_INTEN_USBRSTEN_MASK | USB_INTEN_TOKDNEEN_MASK |
USB_INTEN_SLEEPEN_MASK | USB_INTEN_ERROREN_MASK | USB_INTEN_STALLEN_MASK;
NVIC_EnableIRQ(USB0_IRQn);
}
@@ -278,13 +292,11 @@ void dcd_int_disable(uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(USB0_IRQn);
KHCI->INTEN = 0;
}
void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
{
(void) rhport;
_dcd.addr = dev_addr & 0x7F;
_dcd.addr = dev_addr & 0x7F;
/* Response with status first before changing device address */
dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0);
}
@@ -292,9 +304,12 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
void dcd_remote_wakeup(uint8_t rhport)
{
(void) rhport;
unsigned cnt = SystemCoreClock / 100;
KHCI->CTL |= USB_CTL_RESUME_MASK;
unsigned cnt = SystemCoreClock / 1000;
while (cnt--) __NOP();
KHCI->CTL &= ~USB_CTL_RESUME_MASK;
}
@@ -321,17 +336,17 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
(void) rhport;
const unsigned ep_addr = ep_desc->bEndpointAddress;
const unsigned epn = ep_addr & 0xFu;
const unsigned dir = (ep_addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT;
const unsigned epn = tu_edpt_number(ep_addr);
const unsigned dir = tu_edpt_dir(ep_addr);
const unsigned xfer = ep_desc->bmAttributes.xfer;
endpoint_state_t *ep = &_dcd.endpoint[epn][dir];
const unsigned odd = ep->odd;
buffer_descriptor_t *bd = &_dcd.bdt[epn][dir][0];
buffer_descriptor_t *bd = _dcd.bdt[epn][dir];
/* No support for control transfer */
TU_ASSERT(epn && (xfer != TUSB_XFER_CONTROL));
ep->max_packet_size = ep_desc->wMaxPacketSize.size;
ep->max_packet_size = tu_edpt_packet_size(ep_desc);
unsigned val = USB_ENDPT_EPCTLDIS_MASK;
val |= (xfer != TUSB_XFER_ISOCHRONOUS) ? USB_ENDPT_EPHSHK_MASK: 0;
val |= dir ? USB_ENDPT_EPTXEN_MASK : USB_ENDPT_EPRXEN_MASK;
@@ -347,35 +362,60 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
return true;
}
void dcd_edpt_close_all(uint8_t rhport)
{
(void) rhport;
const unsigned ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
for (unsigned i = 1; i < 16; ++i) {
KHCI->ENDPOINT[i].ENDPT = 0;
}
if (ie) NVIC_EnableIRQ(USB0_IRQn);
buffer_descriptor_t *bd = _dcd.bdt[1][0];
for (unsigned i = 2; i < sizeof(_dcd.bdt)/sizeof(*bd); ++i, ++bd) {
bd->head = 0;
}
endpoint_state_t *ep = &_dcd.endpoint[1][0];
for (unsigned i = 2; i < sizeof(_dcd.endpoint)/sizeof(*ep); ++i, ++ep) {
/* Clear except the odd */
ep->max_packet_size = 0;
ep->length = 0;
ep->remaining = 0;
}
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
const unsigned epn = ep_addr & 0xFu;
const unsigned dir = (ep_addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT;
const unsigned epn = tu_edpt_number(ep_addr);
const unsigned dir = tu_edpt_dir(ep_addr);
endpoint_state_t *ep = &_dcd.endpoint[epn][dir];
buffer_descriptor_t *bd = &_dcd.bdt[epn][dir][0];
buffer_descriptor_t *bd = _dcd.bdt[epn][dir];
const unsigned msk = dir ? USB_ENDPT_EPTXEN_MASK : USB_ENDPT_EPRXEN_MASK;
const unsigned ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
KHCI->ENDPOINT[epn].ENDPT &= ~msk;
ep->max_packet_size = 0;
ep->length = 0;
ep->remaining = 0;
bd->head = 0;
bd[0].head = 0;
bd[1].head = 0;
if (ie) NVIC_EnableIRQ(USB0_IRQn);
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes)
{
(void) rhport;
NVIC_DisableIRQ(USB0_IRQn);
const unsigned epn = ep_addr & 0xFu;
const unsigned dir = (ep_addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT;
const unsigned epn = tu_edpt_number(ep_addr);
const unsigned dir = tu_edpt_dir(ep_addr);
endpoint_state_t *ep = &_dcd.endpoint[epn][dir];
buffer_descriptor_t *bd = &_dcd.bdt[epn][dir][ep->odd];
TU_ASSERT(0 == bd->own);
const unsigned ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
if (bd->own) {
TU_LOG1("DCD XFER fail %x %d %lx %lx\r\n", ep_addr, total_bytes, ep->state, bd->head);
return false; /* The last transfer has not completed */
}
ep->length = total_bytes;
ep->remaining = total_bytes;
@@ -388,42 +428,69 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t to
next->addr = buffer + mps;
next->own = 1;
}
bd->bc = total_bytes >= mps ? mps: total_bytes;
bd->addr = buffer;
bd->bc = total_bytes >= mps ? mps: total_bytes;
bd->addr = buffer;
__DSB();
bd->own = 1; /* the own bit must set after addr */
NVIC_EnableIRQ(USB0_IRQn);
bd->own = 1; /* This bit must be set last */
if (ie) NVIC_EnableIRQ(USB0_IRQn);
return true;
}
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
const unsigned epn = ep_addr & 0xFu;
const unsigned epn = tu_edpt_number(ep_addr);
if (0 == epn) {
KHCI->ENDPOINT[epn].ENDPT |= USB_ENDPT_EPSTALL_MASK;
} else {
const unsigned dir = (ep_addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT;
buffer_descriptor_t *bd = _dcd.bdt[epn][dir];
bd[0].bdt_stall = 1;
bd[1].bdt_stall = 1;
const unsigned dir = tu_edpt_dir(ep_addr);
const unsigned odd = _dcd.endpoint[epn][dir].odd;
buffer_descriptor_t *bd = &_dcd.bdt[epn][dir][odd];
TU_ASSERT(0 == bd->own,);
const unsigned ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
bd->bdt_stall = 1;
__DSB();
bd->own = 1; /* This bit must be set last */
if (ie) NVIC_EnableIRQ(USB0_IRQn);
}
}
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
const unsigned epn = ep_addr & 0xFu;
const unsigned dir = (ep_addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT;
const unsigned epn = tu_edpt_number(ep_addr);
TU_VERIFY(epn,);
const unsigned dir = tu_edpt_dir(ep_addr);
const unsigned odd = _dcd.endpoint[epn][dir].odd;
buffer_descriptor_t *bd = _dcd.bdt[epn][dir];
TU_VERIFY(bd[odd].own,);
bd[odd ^ 1].own = 0;
bd[odd ^ 1].data = 1;
bd[odd ^ 1].bdt_stall = 0;
bd[odd].own = 0;
bd[odd].data = 0;
bd[odd].bdt_stall = 0;
const unsigned ie = NVIC_GetEnableIRQ(USB0_IRQn);
NVIC_DisableIRQ(USB0_IRQn);
bd[odd].own = 0;
__DSB();
// clear stall
bd[odd].bdt_stall = 0;
// Reset data toggle
bd[odd ].data = 0;
bd[odd ^ 1].data = 1;
// We already cleared this in ISR, but just clear it here to be safe
const unsigned endpt = KHCI->ENDPOINT[epn].ENDPT;
if (endpt & USB_ENDPT_EPSTALL_MASK) {
KHCI->ENDPOINT[epn].ENDPT = endpt & ~USB_ENDPT_EPSTALL_MASK;
}
if (ie) NVIC_EnableIRQ(USB0_IRQn);
}
//--------------------------------------------------------------------+
@@ -431,48 +498,59 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
//--------------------------------------------------------------------+
void dcd_int_handler(uint8_t rhport)
{
(void) rhport;
uint32_t is = KHCI->ISTAT;
uint32_t msk = KHCI->INTEN;
// clear non-enabled interrupts
KHCI->ISTAT = is & ~msk;
is &= msk;
if (is & USB_ISTAT_ERROR_MASK) {
/* TODO: */
uint32_t es = KHCI->ERRSTAT;
KHCI->ERRSTAT = es;
KHCI->ISTAT = is; /* discard any pending events */
return;
}
if (is & USB_ISTAT_USBRST_MASK) {
KHCI->ISTAT = is; /* discard any pending events */
process_bus_reset(rhport);
return;
}
if (is & USB_ISTAT_SLEEP_MASK) {
// TU_LOG2("Suspend: "); TU_LOG2_HEX(is);
// Note Host usually has extra delay after bus reset (without SOF), which could falsely
// detected as Sleep event. Though usbd has debouncing logic so we are good
KHCI->ISTAT = USB_ISTAT_SLEEP_MASK;
process_bus_inactive(rhport);
return;
process_bus_sleep(rhport);
}
#if 0 // ISTAT_RESUME never trigger, probably for host mode ?
if (is & USB_ISTAT_RESUME_MASK) {
// TU_LOG2("ISTAT Resume: "); TU_LOG2_HEX(is);
KHCI->ISTAT = USB_ISTAT_RESUME_MASK;
process_bus_active(rhport);
return;
process_bus_resume(rhport);
}
#endif
if (KHCI->USBTRC0 & USB_USBTRC0_USB_RESUME_INT_MASK) {
// TU_LOG2("USBTRC0 Resume: "); TU_LOG2_HEX(is); TU_LOG2_HEX(KHCI->USBTRC0);
process_bus_resume(rhport);
}
if (is & USB_ISTAT_SOFTOK_MASK) {
KHCI->ISTAT = USB_ISTAT_SOFTOK_MASK;
dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true);
return;
}
if (is & USB_ISTAT_STALL_MASK) {
KHCI->ISTAT = USB_ISTAT_STALL_MASK;
process_stall(rhport);
return;
}
if (is & USB_ISTAT_TOKDNE_MASK) {
process_tokdne(rhport);
return;
}
}
+9 -2
View File
@@ -311,14 +311,15 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
}
//------------- Realize Endpoint with Max Packet Size -------------//
set_ep_size(ep_id, p_endpoint_desc->wMaxPacketSize.size);
const uint16_t ep_size = tu_edpt_packet_size(p_endpoint_desc);
set_ep_size(ep_id, ep_size);
//------------- first DD prepare -------------//
dma_desc_t* const dd = &_dcd.dd[ep_id];
tu_memclr(dd, sizeof(dma_desc_t));
dd->isochronous = (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) ? 1 : 0;
dd->max_packet_size = p_endpoint_desc->wMaxPacketSize.size;
dd->max_packet_size = ep_size;
dd->retired = 1; // invalid at first
sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS + ep_id, 1, 0); // clear all endpoint status
@@ -326,6 +327,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
@@ -323,6 +323,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
static void prepare_setup_packet(uint8_t rhport)
{
if (_dcd_controller[rhport].max_speed == TUSB_SPEED_FULL )
@@ -29,6 +29,8 @@
#if TUSB_OPT_DEVICE_ENABLED && \
(CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX)
#warning "transdimenion is renamed to chipidea (portable/chipidea/ci_hs) to match other opensource naming convention such as linux. This file will be removed in the future, please update your makefile accordingly"
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
@@ -57,11 +59,15 @@
// ENDPTCTRL
enum {
ENDPTCTRL_STALL = TU_BIT(0),
ENDPTCTRL_TOGGLE_INHIBIT = TU_BIT(5), ///< used for test only
ENDPTCTRL_TOGGLE_INHIBIT = TU_BIT(5), // used for test only
ENDPTCTRL_TOGGLE_RESET = TU_BIT(6),
ENDPTCTRL_ENABLE = TU_BIT(7)
};
enum {
ENDPTCTRL_TYPE_POS = 2, // Endpoint type is 2-bit field
};
// USBSTS, USBINTR
enum {
INTR_USB = TU_BIT(0),
@@ -91,12 +97,15 @@ typedef struct
uint32_t : 3 ;
uint32_t int_on_complete : 1 ;
volatile uint32_t total_bytes : 15 ;
uint32_t : 0 ;
uint32_t : 1 ;
// Word 2-6: Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page
uint32_t buffer[5]; ///< buffer1 has frame_n for TODO Isochronous
//------------- DCD Area -------------//
//--------------------------------------------------------------------+
// TD is 32 bytes aligned but occupies only 28 bytes
// Therefore there are 4 bytes padding that we can use.
//--------------------------------------------------------------------+
uint16_t expected_bytes;
uint8_t reserved[2];
} dcd_qtd_t;
@@ -109,11 +118,10 @@ typedef struct
// Word 0: Capabilities and Characteristics
uint32_t : 15 ; ///< Number of packets executed per transaction descriptor 00 - Execute N transactions as demonstrated by the USB variable length protocol where N is computed using Max_packet_length and the Total_bytes field in the dTD. 01 - Execute one transaction 10 - Execute two transactions 11 - Execute three transactions Remark: Non-isochronous endpoints must set MULT = 00. Remark: Isochronous endpoints must set MULT = 01, 10, or 11 as needed.
uint32_t int_on_setup : 1 ; ///< Interrupt on setup This bit is used on control type endpoints to indicate if USBINT is set in response to a setup being received.
uint32_t max_package_size : 11 ; ///< This directly corresponds to the maximum packet size of the associated endpoint (wMaxPacketSize)
uint32_t max_packet_size : 11 ; ///< Endpoint's wMaxPacketSize
uint32_t : 2 ;
uint32_t zero_length_termination : 1 ; ///< This bit is used for non-isochronous endpoints to indicate when a zero-length packet is received to terminate transfers in case the total transfer length is “multiple”. 0 - Enable zero-length packet to terminate transfers equal to a multiple of Max_packet_length (default). 1 - Disable zero-length packet on transfers that are equal in length to a multiple Max_packet_length.
uint32_t iso_mult : 2 ; ///<
uint32_t : 0 ;
// Word 1: Current qTD Pointer
volatile uint32_t qtd_addr;
@@ -125,10 +133,11 @@ typedef struct
volatile tusb_control_request_t setup_request;
//--------------------------------------------------------------------+
/// Due to the fact QHD is 64 bytes aligned but occupies only 48 bytes
/// thus there are 16 bytes padding free that we can make use of.
// QHD is 64 bytes aligned but occupies only 48 bytes
// Therefore there are 16 bytes padding that we can use.
//--------------------------------------------------------------------+
uint8_t reserved[16];
tu_fifo_t * ff;
uint8_t reserved[12];
} dcd_qhd_t;
TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct");
@@ -145,10 +154,6 @@ typedef struct
}dcd_controller_t;
#if CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX
// Each endpoint with direction (IN/OUT) occupies a queue head
// Therefore QHD_MAX is 2 x max endpoint count
#define QHD_MAX (8*2)
static const dcd_controller_t _dcd_controller[] =
{
// RT1010 and RT1020 only has 1 USB controller
@@ -161,8 +166,6 @@ typedef struct
};
#else
#define QHD_MAX (6*2)
static const dcd_controller_t _dcd_controller[] =
{
{ .regs = (dcd_registers_t*) LPC_USB0_BASE, .irqnum = USB0_IRQn, .ep_count = 6 },
@@ -174,8 +177,10 @@ typedef struct
typedef struct {
// Must be at 2K alignment
dcd_qhd_t qhd[QHD_MAX] TU_ATTR_ALIGNED(64);
dcd_qtd_t qtd[QHD_MAX] TU_ATTR_ALIGNED(32); // for portability, TinyUSB only queue 1 TD for each Qhd
// Each endpoint with direction (IN/OUT) occupies a queue head
// for portability, TinyUSB only queue 1 TD for each Qhd
dcd_qhd_t qhd[DCD_ATTR_ENDPOINT_MAX][2] TU_ATTR_ALIGNED(64);
dcd_qtd_t qtd[DCD_ATTR_ENDPOINT_MAX][2] TU_ATTR_ALIGNED(32);
}dcd_data_t;
CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048)
@@ -195,9 +200,9 @@ static void bus_reset(uint8_t rhport)
// endpoint type of the unused direction must be changed from the control type to any other
// type (e.g. bulk). Leaving an un-configured endpoint control will cause undefined behavior
// for the data PID tracking on the active endpoint.
for( int i=1; i < _dcd_controller[rhport].ep_count; i++)
for( uint8_t i=1; i < _dcd_controller[rhport].ep_count; i++)
{
dcd_reg->ENDPTCTRL[i] = (TUSB_XFER_BULK << 2) | (TUSB_XFER_BULK << 18);
dcd_reg->ENDPTCTRL[i] = (TUSB_XFER_BULK << ENDPTCTRL_TYPE_POS) | (TUSB_XFER_BULK << (16+ENDPTCTRL_TYPE_POS));
}
//------------- Clear All Registers -------------//
@@ -217,11 +222,11 @@ static void bus_reset(uint8_t rhport)
tu_memclr(&_dcd_data, sizeof(dcd_data_t));
//------------- Set up Control Endpoints (0 OUT, 1 IN) -------------//
_dcd_data.qhd[0].zero_length_termination = _dcd_data.qhd[1].zero_length_termination = 1;
_dcd_data.qhd[0].max_package_size = _dcd_data.qhd[1].max_package_size = CFG_TUD_ENDPOINT0_SIZE;
_dcd_data.qhd[0].qtd_overlay.next = _dcd_data.qhd[1].qtd_overlay.next = QTD_NEXT_INVALID;
_dcd_data.qhd[0][0].zero_length_termination = _dcd_data.qhd[0][1].zero_length_termination = 1;
_dcd_data.qhd[0][0].max_packet_size = _dcd_data.qhd[0][1].max_packet_size = CFG_TUD_ENDPOINT0_SIZE;
_dcd_data.qhd[0][0].qtd_overlay.next = _dcd_data.qhd[0][1].qtd_overlay.next = QTD_NEXT_INVALID;
_dcd_data.qhd[0].int_on_setup = 1; // OUT only
_dcd_data.qhd[0][0].int_on_setup = 1; // OUT only
}
void dcd_init(uint8_t rhport)
@@ -238,14 +243,15 @@ void dcd_init(uint8_t rhport)
dcd_reg->USBMODE = USBMODE_CM_DEVICE;
dcd_reg->OTGSC = OTGSC_VBUS_DISCHARGE | OTGSC_OTG_TERMINATION;
// TODO Force fullspeed on non-highspeed port
// dcd_reg->PORTSC1 = PORTSC1_FORCE_FULL_SPEED;
#if !TUD_OPT_HIGH_SPEED
dcd_reg->PORTSC1 = PORTSC1_FORCE_FULL_SPEED;
#endif
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
dcd_reg->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment
dcd_reg->USBSTS = dcd_reg->USBSTS;
dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND /*| INTR_SOF*/;
dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_SUSPEND;
dcd_reg->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0
dcd_reg->USBCMD |= USBCMD_RUN_STOP; // Connect
@@ -272,7 +278,8 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
void dcd_remote_wakeup(uint8_t rhport)
{
(void) rhport;
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_reg->PORTSC1 |= PORTSC1_FORCE_PORT_RESUME;
}
void dcd_connect(uint8_t rhport)
@@ -290,26 +297,33 @@ void dcd_disconnect(uint8_t rhport)
//--------------------------------------------------------------------+
// HELPER
//--------------------------------------------------------------------+
// index to bit position in register
static inline uint8_t ep_idx2bit(uint8_t ep_idx)
{
return ep_idx/2 + ( (ep_idx%2) ? 16 : 0);
}
static void qtd_init(dcd_qtd_t* p_qtd, void * data_ptr, uint16_t total_bytes)
{
// Force the CPU to flush the buffer. We increase the size by 31 because the call aligns the
// address to 32-byte boundaries. Buffer must be word aligned
CleanInvalidateDCache_by_Addr((uint32_t*) tu_align((uint32_t) data_ptr, 4), total_bytes + 31);
tu_memclr(p_qtd, sizeof(dcd_qtd_t));
p_qtd->next = QTD_NEXT_INVALID;
p_qtd->active = 1;
p_qtd->total_bytes = p_qtd->expected_bytes = total_bytes;
p_qtd->next = QTD_NEXT_INVALID;
p_qtd->active = 1;
p_qtd->total_bytes = p_qtd->expected_bytes = total_bytes;
p_qtd->int_on_complete = true;
if (data_ptr != NULL)
{
p_qtd->buffer[0] = (uint32_t) data_ptr;
p_qtd->buffer[0] = (uint32_t) data_ptr;
uint32_t const bufend = p_qtd->buffer[0] + total_bytes;
for(uint8_t i=1; i<5; i++)
{
p_qtd->buffer[i] |= tu_align4k( p_qtd->buffer[i-1] ) + 4096;
uint32_t const next_page = tu_align4k( p_qtd->buffer[i-1] ) + 4096;
if ( bufend <= next_page ) break;
p_qtd->buffer[i] = next_page;
// TODO page[1] FRAME_N for ISO transfer
}
}
}
@@ -324,12 +338,15 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_reg->ENDPTCTRL[epnum] |= ENDPTCTRL_STALL << (dir ? 16 : 0);
// flush to abort any primed buffer
dcd_reg->ENDPTFLUSH = TU_BIT(epnum + (dir ? 16 : 0));
}
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
// data toggle also need to be reset
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
@@ -339,39 +356,87 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
{
// TODO not support ISO yet
TU_VERIFY ( p_endpoint_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS);
uint8_t const epnum = tu_edpt_number(p_endpoint_desc->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
uint8_t const ep_idx = 2*epnum + dir;
uint8_t const epnum = tu_edpt_number(p_endpoint_desc->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
// Must not exceed max endpoint number
TU_ASSERT( epnum < _dcd_controller[rhport].ep_count );
//------------- Prepare Queue Head -------------//
dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx];
dcd_qhd_t * p_qhd = &_dcd_data.qhd[epnum][dir];
tu_memclr(p_qhd, sizeof(dcd_qhd_t));
p_qhd->zero_length_termination = 1;
p_qhd->max_package_size = p_endpoint_desc->wMaxPacketSize.size;
p_qhd->max_packet_size = tu_edpt_packet_size(p_endpoint_desc);
if (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS)
{
p_qhd->iso_mult = 1;
}
p_qhd->qtd_overlay.next = QTD_NEXT_INVALID;
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
// Enable EP Control
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_reg->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0);
uint32_t const epctrl = (p_endpoint_desc->bmAttributes.xfer << ENDPTCTRL_TYPE_POS) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET;
if ( dir == TUSB_DIR_OUT )
{
dcd_reg->ENDPTCTRL[epnum] = (dcd_reg->ENDPTCTRL[epnum] & 0xFFFF0000u) | epctrl;
}else
{
dcd_reg->ENDPTCTRL[epnum] = (dcd_reg->ENDPTCTRL[epnum] & 0x0000FFFFu) | (epctrl << 16);
}
return true;
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
void dcd_edpt_close_all (uint8_t rhport)
{
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
uint8_t const ep_idx = 2*epnum + dir;
// Disable all non-control endpoints
for( uint8_t epnum=1; epnum < _dcd_controller[rhport].ep_count; epnum++)
{
_dcd_data.qhd[epnum][TUSB_DIR_OUT].qtd_overlay.halted = 1;
_dcd_data.qhd[epnum][TUSB_DIR_IN ].qtd_overlay.halted = 1;
dcd_reg->ENDPTFLUSH = TU_BIT(epnum) | TU_BIT(epnum+16);
dcd_reg->ENDPTCTRL[epnum] = (TUSB_XFER_BULK << ENDPTCTRL_TYPE_POS) | (TUSB_XFER_BULK << (16+ENDPTCTRL_TYPE_POS));
}
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
_dcd_data.qhd[epnum][dir].qtd_overlay.halted = 1;
// Flush EP
uint32_t const flush_mask = TU_BIT(epnum + (dir ? 16 : 0));
dcd_reg->ENDPTFLUSH = flush_mask;
while(dcd_reg->ENDPTFLUSH & flush_mask);
// Clear EP enable
dcd_reg->ENDPTCTRL[epnum] &=~(ENDPTCTRL_ENABLE << (dir ? 16 : 0));
}
static void qhd_start_xfer(uint8_t rhport, uint8_t epnum, uint8_t dir)
{
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_qhd_t* p_qhd = &_dcd_data.qhd[epnum][dir];
dcd_qtd_t* p_qtd = &_dcd_data.qtd[epnum][dir];
p_qhd->qtd_overlay.halted = false; // clear any previous error
p_qhd->qtd_overlay.next = (uint32_t) p_qtd; // link qtd to qhd
// flush cache
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
if ( epnum == 0 )
{
@@ -380,23 +445,87 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t
while(dcd_reg->ENDPTSETUPSTAT & TU_BIT(0)) {}
}
dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx];
dcd_qtd_t * p_qtd = &_dcd_data.qtd[ep_idx];
// Force the CPU to flush the buffer. We increase the size by 32 because the call aligns the
// address to 32-byte boundaries.
// void* cast to suppress cast-align warning, buffer must be
CleanInvalidateDCache_by_Addr((uint32_t*) tu_align((uint32_t) buffer, 4), total_bytes + 31);
//------------- Prepare qtd -------------//
qtd_init(p_qtd, buffer, total_bytes);
p_qtd->int_on_complete = true;
p_qhd->qtd_overlay.next = (uint32_t) p_qtd; // link qtd to qhd
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
// start transfer
dcd_reg->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ;
dcd_reg->ENDPTPRIME = TU_BIT(epnum + (dir ? 16 : 0));
}
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);
dcd_qhd_t* p_qhd = &_dcd_data.qhd[epnum][dir];
dcd_qtd_t* p_qtd = &_dcd_data.qtd[epnum][dir];
// Prepare qtd
qtd_init(p_qtd, buffer, total_bytes);
// Start qhd transfer
p_qhd->ff = NULL;
qhd_start_xfer(rhport, epnum, dir);
return true;
}
// fifo has to be aligned to 4k boundary
bool dcd_edpt_xfer_fifo (uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_qhd_t * p_qhd = &_dcd_data.qhd[epnum][dir];
dcd_qtd_t * p_qtd = &_dcd_data.qtd[epnum][dir];
tu_fifo_buffer_info_t fifo_info;
if (dir)
{
tu_fifo_get_read_info(ff, &fifo_info);
} else
{
tu_fifo_get_write_info(ff, &fifo_info);
}
if ( fifo_info.len_lin >= total_bytes )
{
// Linear length is enough for this transfer
qtd_init(p_qtd, fifo_info.ptr_lin, total_bytes);
}
else
{
// linear part is not enough
// prepare TD up to linear length
qtd_init(p_qtd, fifo_info.ptr_lin, fifo_info.len_lin);
if ( !tu_offset4k((uint32_t) fifo_info.ptr_wrap) && !tu_offset4k(tu_fifo_depth(ff)) )
{
// If buffer is aligned to 4K & buffer size is multiple of 4K
// We can make use of buffer page array to also combine the linear + wrapped length
p_qtd->total_bytes = p_qtd->expected_bytes = total_bytes;
for(uint8_t i = 1, page = 0; i < 5; i++)
{
// pick up buffer array where linear ends
if (p_qtd->buffer[i] == 0)
{
p_qtd->buffer[i] = (uint32_t) fifo_info.ptr_wrap + 4096 * page;
page++;
}
}
CleanInvalidateDCache_by_Addr((uint32_t*) tu_align((uint32_t) fifo_info.ptr_wrap, 4), total_bytes - fifo_info.len_wrap + 31);
}
else
{
// TODO we may need to carry the wrapped length after the linear part complete
// for now only transfer up to linear part
}
}
// Start qhd transfer
p_qhd->ff = ff;
qhd_start_xfer(rhport, epnum, dir);
return true;
}
@@ -404,9 +533,42 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t
//--------------------------------------------------------------------+
// ISR
//--------------------------------------------------------------------+
static void process_edpt_complete_isr(uint8_t rhport, uint8_t epnum, uint8_t dir)
{
dcd_qhd_t * p_qhd = &_dcd_data.qhd[epnum][dir];
dcd_qtd_t * p_qtd = &_dcd_data.qtd[epnum][dir];
uint8_t result = p_qtd->halted ? XFER_RESULT_STALLED :
( p_qtd->xact_err || p_qtd->buffer_err ) ? XFER_RESULT_FAILED : XFER_RESULT_SUCCESS;
if ( result != XFER_RESULT_SUCCESS )
{
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
// flush to abort error buffer
dcd_reg->ENDPTFLUSH = TU_BIT(epnum + (dir ? 16 : 0));
}
uint16_t const xferred_bytes = p_qtd->expected_bytes - p_qtd->total_bytes;
if (p_qhd->ff)
{
if (dir == TUSB_DIR_IN)
{
tu_fifo_advance_read_pointer(p_qhd->ff, xferred_bytes);
} else
{
tu_fifo_advance_write_pointer(p_qhd->ff, xferred_bytes);
}
}
// only number of bytes in the IOC qtd
dcd_event_xfer_complete(rhport, tu_edpt_addr(epnum, dir), xferred_bytes, result, true);
}
void dcd_int_handler(uint8_t rhport)
{
dcd_registers_t* const dcd_reg = _dcd_controller[rhport].regs;
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
uint32_t const int_enable = dcd_reg->USBINTR;
uint32_t const int_status = dcd_reg->USBSTS & int_enable;
@@ -415,18 +577,46 @@ void dcd_int_handler(uint8_t rhport)
// disabled interrupt sources
if (int_status == 0) return;
if (int_status & INTR_RESET)
{
bus_reset(rhport);
uint32_t speed = (dcd_reg->PORTSC1 & PORTSC1_PORT_SPEED) >> PORTSC1_PORT_SPEED_POS;
dcd_event_bus_reset(rhport, (tusb_speed_t) speed, true);
}
// Set if the port controller enters the full or high-speed operational state.
// either from Bus Reset or Suspended state
if (int_status & INTR_PORT_CHANGE)
{
// TU_LOG2("PortChange %08lx\r\n", dcd_reg->PORTSC1);
// Reset interrupt is not enabled, we manually check if Port Change is due
// to connection / disconnection
if ( dcd_reg->USBSTS & INTR_RESET )
{
dcd_reg->USBSTS = INTR_RESET;
if (dcd_reg->PORTSC1 & PORTSC1_CURRENT_CONNECT_STATUS)
{
uint32_t const speed = (dcd_reg->PORTSC1 & PORTSC1_PORT_SPEED) >> PORTSC1_PORT_SPEED_POS;
bus_reset(rhport);
dcd_event_bus_reset(rhport, (tusb_speed_t) speed, true);
}else
{
dcd_event_bus_signal(rhport, DCD_EVENT_UNPLUGGED, true);
}
}
else
{
// Triggered by resuming from suspended state
if ( !(dcd_reg->PORTSC1 & PORTSC1_SUSPEND) )
{
dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true);
}
}
}
if (int_status & INTR_SUSPEND)
{
// TU_LOG2("Suspend %08lx\r\n", dcd_reg->PORTSC1);
if (dcd_reg->PORTSC1 & PORTSC1_SUSPEND)
{
// Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration.
// Skip suspend event if we are not addressed
if ((dcd_reg->DEVICEADDR >> 25) & 0x0f)
{
dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true);
@@ -434,21 +624,11 @@ void dcd_int_handler(uint8_t rhport)
}
}
// Make sure we read the latest version of _dcd_data.
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
// TODO disconnection does not generate interrupt !!!!!!
// if (int_status & INTR_PORT_CHANGE)
// {
// if ( !(dcd_reg->PORTSC1 & PORTSC1_CURRENT_CONNECT_STATUS) )
// {
// dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_UNPLUGGED };
// dcd_event_handler(&event, true);
// }
// }
if (int_status & INTR_USB)
{
// Make sure we read the latest version of _dcd_data.
CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t));
uint32_t const edpt_complete = dcd_reg->ENDPTCOMPLETE;
dcd_reg->ENDPTCOMPLETE = edpt_complete; // acknowledge
@@ -456,26 +636,21 @@ void dcd_int_handler(uint8_t rhport)
{
//------------- Set up Received -------------//
// 23.10.10.2 Operational model for setup transfers
dcd_reg->ENDPTSETUPSTAT = dcd_reg->ENDPTSETUPSTAT;// acknowledge
dcd_reg->ENDPTSETUPSTAT = dcd_reg->ENDPTSETUPSTAT;
dcd_event_setup_received(rhport, (uint8_t*) &_dcd_data.qhd[0].setup_request, true);
dcd_event_setup_received(rhport, (uint8_t*)(uintptr_t) &_dcd_data.qhd[0][0].setup_request, true);
}
// 23.10.12.3 Failed QTD also get ENDPTCOMPLETE set
// nothing to do, we will submit xfer as error to usbd
// if (int_status & INTR_ERROR) { }
if ( edpt_complete )
{
for(uint8_t ep_idx = 0; ep_idx < QHD_MAX; ep_idx++)
for(uint8_t epnum = 0; epnum < DCD_ATTR_ENDPOINT_MAX; epnum++)
{
if ( tu_bit_test(edpt_complete, ep_idx2bit(ep_idx)) )
{
// 23.10.12.3 Failed QTD also get ENDPTCOMPLETE set
dcd_qtd_t * p_qtd = &_dcd_data.qtd[ep_idx];
uint8_t result = p_qtd->halted ? XFER_RESULT_STALLED :
( p_qtd->xact_err ||p_qtd->buffer_err ) ? XFER_RESULT_FAILED : XFER_RESULT_SUCCESS;
uint8_t const ep_addr = (ep_idx/2) | ( (ep_idx & 0x01) ? TUSB_DIR_IN_MASK : 0 );
dcd_event_xfer_complete(rhport, ep_addr, p_qtd->expected_bytes - p_qtd->total_bytes, result, true); // only number of bytes in the IOC qtd
}
if ( tu_bit_test(edpt_complete, epnum) ) process_edpt_complete_isr(rhport, epnum, TUSB_DIR_OUT);
if ( tu_bit_test(edpt_complete, epnum+16) ) process_edpt_complete_isr(rhport, epnum, TUSB_DIR_IN);
}
}
}
@@ -484,9 +659,6 @@ void dcd_int_handler(uint8_t rhport)
{
dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true);
}
if (int_status & INTR_NAK) {}
if (int_status & INTR_ERROR) TU_ASSERT(false, );
}
#endif
@@ -31,6 +31,8 @@
#if TUSB_OPT_HOST_ENABLED && \
(CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX)
#warning "transdimenion is renamed to chipidea (portable/chipidea/ci_hs) to match other opensource naming convention such as linux. This file will be removed in the future, please update your makefile accordingly"
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
+1 -1
View File
@@ -412,7 +412,7 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const
}
TU_ASSERT(p_ed);
ed_init( p_ed, dev_addr, ep_desc->wMaxPacketSize.size, ep_desc->bEndpointAddress,
ed_init( p_ed, dev_addr, tu_edpt_packet_size(ep_desc), ep_desc->bEndpointAddress,
ep_desc->bmAttributes.xfer, ep_desc->bInterval );
// control of dev0 is used as static async head
+60 -51
View File
@@ -70,7 +70,7 @@ static struct hw_endpoint *hw_endpoint_get_by_addr(uint8_t ep_addr)
static void _hw_endpoint_alloc(struct hw_endpoint *ep, uint8_t transfer_type)
{
// size must be multiple of 64
uint16_t size = tu_div_ceil(ep->wMaxPacketSize, 64) * 64u;
uint size = tu_div_ceil(ep->wMaxPacketSize, 64) * 64u;
// double buffered Bulk endpoint
if ( transfer_type == TUSB_XFER_BULK )
@@ -88,7 +88,7 @@ static void _hw_endpoint_alloc(struct hw_endpoint *ep, uint8_t transfer_type)
pico_info(" Alloced %d bytes at offset 0x%x (0x%p)\r\n", size, dpram_offset, ep->hw_data_buf);
// Fill in endpoint control register with buffer offset
uint32_t const reg = EP_CTRL_ENABLE_BITS | (transfer_type << EP_CTRL_BUFFER_TYPE_LSB) | dpram_offset;
uint32_t const reg = EP_CTRL_ENABLE_BITS | ((uint)transfer_type << EP_CTRL_BUFFER_TYPE_LSB) | dpram_offset;
*ep->endpoint_control = reg;
}
@@ -124,9 +124,7 @@ static void hw_endpoint_init(uint8_t ep_addr, uint16_t wMaxPacketSize, uint8_t t
// For device, IN is a tx transfer and OUT is an rx transfer
ep->rx = (dir == TUSB_DIR_OUT);
// Response to a setup packet on EP0 starts with pid of 1
ep->next_pid = (num == 0 ? 1u : 0u);
ep->next_pid = 0u;
ep->wMaxPacketSize = wMaxPacketSize;
ep->transfer_type = transfer_type;
@@ -145,8 +143,7 @@ static void hw_endpoint_init(uint8_t ep_addr, uint16_t wMaxPacketSize, uint8_t t
if ( num == 0 )
{
// EP0 has no endpoint control register because
// the buffer offsets are fixed
// EP0 has no endpoint control register because the buffer offsets are fixed
ep->endpoint_control = NULL;
// Buffer offset is fixed (also double buffered)
@@ -178,16 +175,18 @@ static void hw_endpoint_xfer(uint8_t ep_addr, uint8_t *buffer, uint16_t total_by
static void hw_handle_buff_status(void)
{
uint32_t remaining_buffers = usb_hw->buf_status;
pico_trace("buf_status 0x%08x\n", remaining_buffers);
pico_trace("buf_status = 0x%08x\n", remaining_buffers);
uint bit = 1u;
for (uint i = 0; remaining_buffers && i < USB_MAX_ENDPOINTS * 2; i++)
for (uint8_t i = 0; remaining_buffers && i < USB_MAX_ENDPOINTS * 2; i++)
{
if (remaining_buffers & bit)
{
// 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)
@@ -202,7 +201,7 @@ static void hw_handle_buff_status(void)
}
}
static void reset_ep0(void)
static void reset_ep0_pid(void)
{
// If we have finished this transfer on EP0 set pid back to 1 for next
// setup transfer. Also clear a stall in case
@@ -214,14 +213,18 @@ static void reset_ep0(void)
}
}
static void reset_all_endpoints(void)
static void reset_non_control_endpoints(void)
{
memset(hw_endpoints, 0, sizeof(hw_endpoints));
next_buffer_ptr = &usb_dpram->epx_data[0];
// Disable all non-control
for ( uint8_t i = 0; i < USB_MAX_ENDPOINTS-1; i++ )
{
usb_dpram->ep_ctrl[i].in = 0;
usb_dpram->ep_ctrl[i].out = 0;
}
// Init Control endpoint out & in
hw_endpoint_init(0x0, 64, TUSB_XFER_CONTROL);
hw_endpoint_init(0x80, 64, TUSB_XFER_CONTROL);
// clear non-control hw endpoints
tu_memclr(hw_endpoints[1], sizeof(hw_endpoints) - 2*sizeof(hw_endpoint_t));
next_buffer_ptr = &usb_dpram->epx_data[0];
}
static void dcd_rp2040_irq(void)
@@ -233,8 +236,10 @@ static void dcd_rp2040_irq(void)
{
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();
// reset pid to both 1 (data and ack)
reset_ep0_pid();
// Pass setup packet to tiny usb
dcd_event_setup_received(0, setup, true);
usb_hw_clear->sie_status = USB_SIE_STATUS_SETUP_REC_BITS;
@@ -274,7 +279,7 @@ static void dcd_rp2040_irq(void)
handled |= USB_INTS_BUS_RESET_BITS;
usb_hw->dev_addr_ctrl = 0;
reset_all_endpoints();
reset_non_control_endpoints();
dcd_event_bus_reset(0, TUSB_SPEED_FULL, true);
usb_hw_clear->sie_status = USB_SIE_STATUS_BUS_RESET_BITS;
@@ -325,7 +330,6 @@ static void dcd_rp2040_irq(void)
void dcd_init (uint8_t rhport)
{
pico_trace("dcd_init %d\n", rhport);
assert(rhport == 0);
// Reset hardware to default state
@@ -338,8 +342,13 @@ void dcd_init (uint8_t rhport)
irq_set_exclusive_handler(USBCTRL_IRQ, dcd_rp2040_irq);
// reset endpoints
reset_all_endpoints();
// Init control endpoints
tu_memclr(hw_endpoints[0], 2*sizeof(hw_endpoint_t));
hw_endpoint_init(0x0, 64, TUSB_XFER_CONTROL);
hw_endpoint_init(0x80, 64, TUSB_XFER_CONTROL);
// Init non-control endpoints
reset_non_control_endpoints();
// Initializes the USB peripheral for device mode and enables it.
// Don't need to enable the pull up here. Force VBUS
@@ -356,30 +365,28 @@ void dcd_init (uint8_t rhport)
dcd_connect(rhport);
}
void dcd_int_enable(uint8_t rhport)
void dcd_int_enable(__unused uint8_t rhport)
{
assert(rhport == 0);
irq_set_enabled(USBCTRL_IRQ, true);
}
void dcd_int_disable(uint8_t rhport)
void dcd_int_disable(__unused uint8_t rhport)
{
assert(rhport == 0);
irq_set_enabled(USBCTRL_IRQ, false);
}
void dcd_set_address (uint8_t rhport, uint8_t dev_addr)
void dcd_set_address (__unused uint8_t rhport, __unused 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
// Send 0len complete response on EP0 IN
reset_ep0();
hw_endpoint_xfer(0x80, NULL, 0);
}
void dcd_remote_wakeup(uint8_t rhport)
void dcd_remote_wakeup(__unused uint8_t rhport)
{
pico_info("dcd_remote_wakeup %d\n", rhport);
assert(rhport == 0);
@@ -387,19 +394,17 @@ void dcd_remote_wakeup(uint8_t rhport)
}
// disconnect by disabling internal pull-up resistor on D+/D-
void dcd_disconnect(uint8_t rhport)
void dcd_disconnect(__unused uint8_t rhport)
{
pico_info("dcd_disconnect %d\n", rhport);
assert(rhport == 0);
usb_hw_clear->sie_ctrl = USB_SIE_CTRL_PULLUP_EN_BITS;
(void) rhport;
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)
void dcd_connect(__unused uint8_t rhport)
{
pico_info("dcd_connect %d\n", rhport);
assert(rhport == 0);
usb_hw_set->sie_ctrl = USB_SIE_CTRL_PULLUP_EN_BITS;
(void) rhport;
usb_hw_set->sie_ctrl = USB_SIE_CTRL_PULLUP_EN_BITS;
}
/*------------------------------------------------------------------*/
@@ -414,21 +419,26 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re
request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD &&
request->bRequest == TUSB_REQ_SET_ADDRESS )
{
pico_trace("Set HW address %d\n", request->wValue);
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)
bool dcd_edpt_open (__unused uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
{
assert(rhport == 0);
hw_endpoint_init(desc_edpt->bEndpointAddress, desc_edpt->wMaxPacketSize.size, desc_edpt->bmAttributes.xfer);
hw_endpoint_init(desc_edpt->bEndpointAddress, tu_edpt_packet_size(desc_edpt), desc_edpt->bmAttributes.xfer);
return true;
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// may need to use EP Abort
reset_non_control_endpoints();
}
bool dcd_edpt_xfer(__unused uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
{
assert(rhport == 0);
hw_endpoint_xfer(ep_addr, buffer, total_bytes);
@@ -437,8 +447,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
pico_trace("dcd_edpt_stall %02x\n", ep_addr);
assert(rhport == 0);
(void) rhport;
if ( tu_edpt_number(ep_addr) == 0 )
{
@@ -448,22 +457,22 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
struct hw_endpoint *ep = hw_endpoint_get_by_addr(ep_addr);
// TODO check with double buffered
_hw_endpoint_buffer_control_set_mask32(ep, USB_BUF_CTRL_STALL);
// stall and clear current pending buffer
// may need to use EP_ABORT
_hw_endpoint_buffer_control_set_value32(ep, USB_BUF_CTRL_STALL);
}
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
pico_trace("dcd_edpt_clear_stall %02x\n", ep_addr);
assert(rhport == 0);
(void) rhport;
if (tu_edpt_number(ep_addr))
{
struct hw_endpoint *ep = hw_endpoint_get_by_addr(ep_addr);
// clear stall also reset toggle to DATA0
// TODO check with double buffered
_hw_endpoint_buffer_control_clear_mask32(ep, USB_BUF_CTRL_STALL | USB_BUF_CTRL_DATA1_PID);
// clear stall also reset toggle to DATA0, ready for next transfer
ep->next_pid = 0;
_hw_endpoint_buffer_control_clear_mask32(ep, USB_BUF_CTRL_STALL);
}
}
+25 -9
View File
@@ -160,12 +160,11 @@ static void hw_handle_buff_status(void)
static void hw_trans_complete(void)
{
struct hw_endpoint *ep = &epx;
assert(ep->active);
if (usb_hw->sie_ctrl & USB_SIE_CTRL_SEND_SETUP_BITS)
{
pico_trace("Sent setup packet\n");
struct hw_endpoint *ep = &epx;
assert(ep->active);
hw_xfer_complete(ep, XFER_RESULT_SUCCESS);
}
else
@@ -201,7 +200,6 @@ static void hcd_rp2040_irq(void)
{
handled |= USB_INTS_BUFF_STATUS_BITS;
TU_LOG(2, "Buffer complete\n");
// print_bufctrl32(*epx.buffer_control);
hw_handle_buff_status();
}
@@ -231,7 +229,7 @@ static void hcd_rp2040_irq(void)
if (status & USB_INTS_ERROR_DATA_SEQ_BITS)
{
usb_hw_clear->sie_status = USB_SIE_STATUS_DATA_SEQ_ERROR_BITS;
print_bufctrl32(*epx.buffer_control);
TU_LOG(3, " Seq Error: [0] = 0x%04u [1] = 0x%04x\r\n", tu_u32_low16(*epx.buffer_control), tu_u32_high16(*epx.buffer_control));
panic("Data Seq Error \n");
}
@@ -414,10 +412,28 @@ tusb_speed_t hcd_port_speed_get(uint8_t rhport)
// Close all opened endpoint belong to this device
void hcd_device_close(uint8_t rhport, uint8_t dev_addr)
{
(void) rhport;
(void) dev_addr;
pico_trace("hcd_device_close %d\n", dev_addr);
(void) rhport;
pico_trace("hcd_device_close %d\n", dev_addr);
if (dev_addr == 0) return;
for (size_t i = 1; i < TU_ARRAY_SIZE(ep_pool); i++)
{
hw_endpoint_t* ep = &ep_pool[i];
if (ep->dev_addr == dev_addr && ep->configured)
{
// in case it is an interrupt endpoint, disable it
usb_hw_clear->int_ep_ctrl = (1 << (ep->interrupt_num + 1));
usb_hw->int_ep_addr_ctrl[ep->interrupt_num] = 0;
// unconfigure the endpoint
ep->configured = false;
*ep->endpoint_control = 0;
*ep->buffer_control = 0;
hw_endpoint_reset_transfer(ep);
}
}
}
uint32_t hcd_frame_number(uint8_t rhport)
@@ -455,7 +471,7 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const
_hw_endpoint_init(ep,
dev_addr,
ep_desc->bEndpointAddress,
ep_desc->wMaxPacketSize.size,
tu_edpt_packet_size(ep_desc),
ep_desc->bmAttributes.xfer,
ep_desc->bInterval);
+9 -12
View File
@@ -38,7 +38,7 @@ const char *ep_dir_string[] = {
"in",
};
static inline void _hw_endpoint_lock_update(struct hw_endpoint *ep, int delta) {
static inline void _hw_endpoint_lock_update(__unused struct hw_endpoint * ep, __unused 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.
@@ -67,7 +67,6 @@ void rp2040_usb_init(void)
void hw_endpoint_reset_transfer(struct hw_endpoint *ep)
{
ep->stalled = false;
ep->active = false;
ep->remaining_len = 0;
ep->xferred_len = 0;
@@ -108,7 +107,7 @@ void _hw_endpoint_buffer_control_update32(struct hw_endpoint *ep, uint32_t and_m
static uint32_t prepare_ep_buffer(struct hw_endpoint *ep, uint8_t buf_id)
{
uint16_t const buflen = tu_min16(ep->remaining_len, ep->wMaxPacketSize);
ep->remaining_len -= buflen;
ep->remaining_len = (uint16_t)(ep->remaining_len - buflen);
uint32_t buf_ctrl = buflen | USB_BUF_CTRL_AVAIL;
@@ -171,8 +170,7 @@ static void _hw_endpoint_start_next_buffer(struct hw_endpoint *ep)
*ep->endpoint_control = ep_ctrl;
TU_LOG(3, "Prepare Buffer Control:\r\n");
print_bufctrl32(buf_ctrl);
TU_LOG(3, " Prepare BufCtrl: [0] = 0x%04u [1] = 0x%04x\r\n", tu_u32_low16(buf_ctrl), tu_u32_high16(buf_ctrl));
// Finally, write to buffer_control which will trigger the transfer
// the next time the controller polls this dpram address
@@ -216,7 +214,7 @@ static uint16_t sync_ep_buffer(struct hw_endpoint *ep, uint8_t buf_id)
// sent some data can increase the length we have sent
assert(!(buf_ctrl & USB_BUF_CTRL_FULL));
ep->xferred_len += xferred_bytes;
ep->xferred_len = (uint16_t)(ep->xferred_len + xferred_bytes);
}else
{
// If we have received some data, so can increase the length
@@ -224,14 +222,14 @@ static uint16_t sync_ep_buffer(struct hw_endpoint *ep, uint8_t buf_id)
assert(buf_ctrl & USB_BUF_CTRL_FULL);
memcpy(ep->user_buf, ep->hw_data_buf + buf_id*64, xferred_bytes);
ep->xferred_len += xferred_bytes;
ep->xferred_len = (uint16_t)(ep->xferred_len + xferred_bytes);
ep->user_buf += xferred_bytes;
}
// Short packet
if (xferred_bytes < ep->wMaxPacketSize)
{
pico_trace("Short rx transfer on buffer %d with %u bytes\n", buf_id, xferred_bytes);
pico_trace(" Short packet on buffer %d with %u bytes\n", buf_id, xferred_bytes);
// Reduce total length as this is last packet
ep->remaining_len = 0;
}
@@ -244,9 +242,8 @@ static void _hw_endpoint_xfer_sync (struct hw_endpoint *ep)
// Update hw endpoint struct with info from hardware
// after a buff status interrupt
uint32_t buf_ctrl = _hw_endpoint_buffer_control_get_value32(ep);
TU_LOG(3, "_hw_endpoint_xfer_sync:\r\n");
print_bufctrl32(buf_ctrl);
uint32_t __unused buf_ctrl = _hw_endpoint_buffer_control_get_value32(ep);
TU_LOG(3, " Sync BufCtrl: [0] = 0x%04u [1] = 0x%04x\r\n", tu_u32_low16(buf_ctrl), tu_u32_high16(buf_ctrl));
// always sync buffer 0
uint16_t buf0_bytes = sync_ep_buffer(ep, 0);
@@ -284,7 +281,7 @@ static void _hw_endpoint_xfer_sync (struct hw_endpoint *ep)
usb_hw->abort &= ~TU_BIT(ep_id);
TU_LOG(3, "----SHORT PACKET buffer0 on EP %02X:\r\n", ep->ep_addr);
print_bufctrl32(buf_ctrl);
TU_LOG(3, " BufCtrl: [0] = 0x%04u [1] = 0x%04x\r\n", tu_u32_low16(buf_ctrl), tu_u32_high16(buf_ctrl));
#endif
}
}
+2 -53
View File
@@ -21,7 +21,7 @@
#define pico_trace(...) TU_LOG(3, __VA_ARGS__)
// Hardware information per endpoint
struct hw_endpoint
typedef struct hw_endpoint
{
// Is this a valid struct
bool configured;
@@ -42,9 +42,6 @@ struct hw_endpoint
// Buffer pointer in usb dpram
uint8_t *hw_data_buf;
// Have we been stalled TODO remove later
bool stalled;
// Current transfer information
bool active;
uint16_t remaining_len;
@@ -66,7 +63,7 @@ struct hw_endpoint
// If interrupt endpoint
uint8_t interrupt_num;
#endif
};
} hw_endpoint_t;
void rp2040_usb_init(void);
@@ -96,52 +93,4 @@ static inline uintptr_t hw_data_offset(uint8_t *buf)
extern const char *ep_dir_string[];
typedef union TU_ATTR_PACKED
{
uint16_t u16;
struct TU_ATTR_PACKED
{
uint16_t xfer_len : 10;
uint16_t available : 1;
uint16_t stall : 1;
uint16_t reset_bufsel : 1;
uint16_t data_toggle : 1;
uint16_t last_buf : 1;
uint16_t full : 1;
};
} rp2040_buffer_control_t;
TU_VERIFY_STATIC(sizeof(rp2040_buffer_control_t) == 2, "size is not correct");
#if CFG_TUSB_DEBUG >= 3
static inline void print_bufctrl16(uint32_t u16)
{
rp2040_buffer_control_t bufctrl = {
.u16 = u16
};
TU_LOG(3, "len = %u, available = %u, full = %u, last = %u, stall = %u, reset = %u, toggle = %u\r\n",
bufctrl.xfer_len, bufctrl.available, bufctrl.full, bufctrl.last_buf, bufctrl.stall, bufctrl.reset_bufsel, bufctrl.data_toggle);
}
static inline void print_bufctrl32(uint32_t u32)
{
uint16_t u16;
u16 = u32 >> 16;
TU_LOG(3, " Buffer Control 1 0x%x: ", u16);
print_bufctrl16(u16);
u16 = u32 & 0x0000ffff;
TU_LOG(3, " Buffer Control 0 0x%x: ", u16);
print_bufctrl16(u16);
}
#else
#define print_bufctrl16(u16)
#define print_bufctrl32(u32)
#endif
#endif
+16 -4
View File
@@ -259,7 +259,7 @@ static inline void pipe_wait_for_ready(unsigned num)
static void pipe_write_packet(void *buf, volatile void *fifo, unsigned len)
{
hw_fifo_t *reg = (hw_fifo_t*)fifo;
volatile hw_fifo_t *reg = (volatile hw_fifo_t*) fifo;
uintptr_t addr = (uintptr_t)buf;
while (len >= 2) {
reg->u16 = *(const uint16_t *)addr;
@@ -275,7 +275,7 @@ static void pipe_write_packet(void *buf, volatile void *fifo, unsigned len)
static void pipe_read_packet(void *buf, volatile void *fifo, unsigned len)
{
uint8_t *p = (uint8_t*)buf;
uint8_t *reg = (uint8_t*)fifo; /* byte access is always at base register address */
volatile uint8_t *reg = (volatile uint8_t*)fifo; /* byte access is always at base register address */
while (len--) *p++ = *reg;
}
@@ -695,7 +695,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
const unsigned dir = tu_edpt_dir(ep_addr);
const unsigned xfer = ep_desc->bmAttributes.xfer;
const unsigned mps = tu_le16toh(ep_desc->wMaxPacketSize.size);
const unsigned mps = tu_edpt_packet_size(ep_desc);
if (xfer == TUSB_XFER_ISOCHRONOUS && mps > 256) {
/* USBa supports up to 256 bytes */
return false;
@@ -711,7 +711,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
USB0.PIPESEL.WORD = num;
USB0.PIPEMAXP.WORD = mps;
volatile uint16_t *ctr = get_pipectr(num);
*ctr = USB_PIPECTR_ACLRM;
*ctr = USB_PIPECTR_ACLRM | USB_PIPECTR_SQCLR;
*ctr = 0;
unsigned cfg = (dir << 4) | epn;
if (xfer == TUSB_XFER_BULK) {
@@ -733,6 +733,18 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
return true;
}
void dcd_edpt_close_all(uint8_t rhport)
{
unsigned i = TU_ARRAY_SIZE(_dcd.pipe);
dcd_int_disable(rhport);
while (--i) { /* Close all pipes except 0 */
const unsigned ep_addr = _dcd.pipe[i].ep;
if (!ep_addr) continue;
dcd_edpt_close(rhport, ep_addr);
}
dcd_int_enable(rhport);
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
(void)rhport;
-931
View File
@@ -1,931 +0,0 @@
/*
* 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.
*/
#include "tusb_option.h"
#if TUSB_OPT_DEVICE_ENABLED && ( \
(CFG_TUSB_MCU == OPT_MCU_EFM32GG) || \
(CFG_TUSB_MCU == OPT_MCU_EFM32GG11) || \
(CFG_TUSB_MCU == OPT_MCU_EFM32GG12) )
/* Silabs */
#include "em_device.h"
#include "device/dcd.h"
/*
* Since TinyUSB doesn't use SOF for now, and this interrupt too often (1ms interval)
* We disable SOF for now until needed later on
*/
#define USE_SOF 0
/*
* Number of endpoints
* 12 software-configurable endpoints (6 IN, 6 OUT) in addition to endpoint 0
*/
#define EP_COUNT 7
/* FIFO size in bytes */
#define EP_FIFO_SIZE 2048
/* Max number of IN EP FIFOs */
#define EP_FIFO_NUM 7
/* */
typedef struct {
uint8_t *buffer;
uint16_t total_len;
uint16_t queued_len;
uint16_t max_size;
bool short_packet;
} xfer_ctl_t;
static uint32_t _setup_packet[2];
#define XFER_CTL_BASE(_ep, _dir) &xfer_status[_ep][_dir]
static xfer_ctl_t xfer_status[EP_COUNT][2];
/* Keep count of how many FIFOs are in use */
static uint8_t _allocated_fifos = 1; /* FIFO0 is always in use */
static volatile uint32_t* tx_fifo[EP_FIFO_NUM] = {
USB->FIFO0D,
USB->FIFO1D,
USB->FIFO2D,
USB->FIFO3D,
USB->FIFO4D,
USB->FIFO5D,
USB->FIFO6D,
};
/* Register Helpers */
#define DCTL_WO_BITMASK (USB_DCTL_CGOUTNAK | USB_DCTL_SGOUTNAK | USB_DCTL_CGNPINNAK | USB_DCTL_SGNPINNAK)
#define GUSBCFG_WO_BITMASK (USB_GUSBCFG_CORRUPTTXPKT)
#define DEPCTL_WO_BITMASK (USB_DIEP_CTL_CNAK | USB_DIEP_CTL_SNAK | USB_DIEP_CTL_SETD0PIDEF | USB_DIEP_CTL_SETD1PIDOF)
/* Will either return an unused FIFO number, or 0 if all are used. */
static uint8_t get_free_fifo(void)
{
if(_allocated_fifos < EP_FIFO_NUM) return _allocated_fifos++;
return 0;
}
/*
static void flush_rx_fifo(void)
{
USB->GRSTCTL = USB_GRSTCTL_RXFFLSH;
while(USB->GRSTCTL & USB_GRSTCTL_RXFFLSH);
}
*/
static void flush_tx_fifo(uint8_t fifo_num)
{
USB->GRSTCTL = USB_GRSTCTL_TXFFLSH | (fifo_num << _USB_GRSTCTL_TXFNUM_SHIFT);
while(USB->GRSTCTL & USB_GRSTCTL_TXFFLSH);
}
/* Setup the control endpoint 0. */
static void bus_reset(void)
{
USB->DOEP0CTL |= USB_DIEP_CTL_SNAK;
for(uint8_t i = 0; i < EP_COUNT - 1; i++)
{
USB->DOEP[i].CTL |= USB_DIEP_CTL_SNAK;
}
/* reset address */
USB->DCFG &= ~_USB_DCFG_DEVADDR_MASK;
USB->DAINTMSK |= USB_DAINTMSK_OUTEPMSK0 | USB_DAINTMSK_INEPMSK0;
USB->DOEPMSK |= USB_DOEPMSK_SETUPMSK | USB_DOEPMSK_XFERCOMPLMSK;
USB->DIEPMSK |= USB_DIEPMSK_TIMEOUTMSK | USB_DIEPMSK_XFERCOMPLMSK;
/*
* - All EP OUT shared a unique OUT FIFO which uses
* * 10 locations in hardware for setup packets + setup control words (up to 3 setup packets).
* * 2 locations for OUT endpoint control words.
* * 16 for largest packet size of 64 bytes. ( TODO Highspeed is 512 bytes)
* * 1 location for global NAK (not required/used here).
* * It is recommended to allocate 2 times the largest packet size, therefore
* Recommended value = 10 + 1 + 2 x (16+2) = 47 --> Let's make it 52
*/
flush_tx_fifo(_USB_GRSTCTL_TXFNUM_FALL); // Flush All
USB->GRXFSIZ = 52;
/* Control IN uses FIFO 0 with 64 bytes ( 16 32-bit word ) */
USB->GNPTXFSIZ = (16 << _USB_GNPTXFSIZ_NPTXFINEPTXF0DEP_SHIFT) | (USB->GRXFSIZ & _USB_GNPTXFSIZ_NPTXFSTADDR_MASK);
/* Ready to receive SETUP packet */
USB->DOEP0TSIZ |= (1 << _USB_DOEP0TSIZ_SUPCNT_SHIFT);
USB->GINTMSK |= USB_GINTMSK_IEPINTMSK | USB_GINTMSK_OEPINTMSK;
}
static void enum_done_processing(void)
{
/* Maximum packet size for EP 0 is set for both directions by writing DIEPCTL */
if((USB->DSTS & _USB_DSTS_ENUMSPD_MASK) == USB_DSTS_ENUMSPD_FS)
{
/* Full Speed (PHY on 48 MHz) */
USB->DOEP0CTL = (USB->DOEP0CTL & ~_USB_DOEP0CTL_MPS_MASK) | _USB_DOEP0CTL_MPS_64B; /* Maximum Packet Size 64 bytes */
USB->DOEP0CTL &= ~_USB_DOEP0CTL_STALL_MASK; /* clear Stall */
xfer_status[0][TUSB_DIR_OUT].max_size = 64;
xfer_status[0][TUSB_DIR_IN].max_size = 64;
}
else
{
/* Low Speed (PHY on 6 MHz) */
USB->DOEP0CTL = (USB->DOEP0CTL & ~_USB_DOEP0CTL_MPS_MASK) | _USB_DOEP0CTL_MPS_8B; /* Maximum Packet Size 64 bytes */
USB->DOEP0CTL &= ~_USB_DOEP0CTL_STALL_MASK; /* clear Stall */
xfer_status[0][TUSB_DIR_OUT].max_size = 8;
xfer_status[0][TUSB_DIR_IN].max_size = 8;
}
}
/*------------------------------------------------------------------*/
/* Controller API */
/*------------------------------------------------------------------*/
void dcd_init(uint8_t rhport)
{
(void) rhport;
/* Reset Core */
USB->PCGCCTL &= ~USB_PCGCCTL_STOPPCLK;
USB->PCGCCTL &= ~(USB_PCGCCTL_PWRCLMP | USB_PCGCCTL_RSTPDWNMODULE);
/* Core Soft Reset */
USB->GRSTCTL |= USB_GRSTCTL_CSFTRST;
while(USB->GRSTCTL & USB_GRSTCTL_CSFTRST);
while(!(USB->GRSTCTL & USB_GRSTCTL_AHBIDLE));
/* Enable PHY pins */
USB->ROUTE = USB_ROUTE_PHYPEN;
dcd_disconnect(rhport);
/*
* Set device speed (Full speed PHY)
* Stall on non-zero len status OUT packets (ctrl transfers)
* periodic frame interval to 80%
*/
USB->DCFG = (USB->DCFG & ~(_USB_DCFG_DEVSPD_MASK | _USB_DCFG_PERFRINT_MASK)) | USB_DCFG_DEVSPD_FS | USB_DCFG_NZSTSOUTHSHK;
/* Enable Global Interrupts */
USB->GAHBCFG = (USB->GAHBCFG & ~_USB_GAHBCFG_HBSTLEN_MASK) | USB_GAHBCFG_GLBLINTRMSK;
/* Force Device Mode */
USB->GUSBCFG = (USB->GUSBCFG & ~(GUSBCFG_WO_BITMASK | USB_GUSBCFG_FORCEHSTMODE)) | USB_GUSBCFG_FORCEDEVMODE;
/* No Overrides */
USB->GOTGCTL &= ~(USB_GOTGCTL_BVALIDOVVAL | USB_GOTGCTL_BVALIDOVEN | USB_GOTGCTL_VBVALIDOVVAL);
/* Ignore frame numbers on ISO transfers. */
USB->DCTL = (USB->DCTL & ~DCTL_WO_BITMASK) | USB_DCTL_IGNRFRMNUM;
/* Setting SNAKs */
USB->DOEP0CTL |= USB_DIEP_CTL_SNAK;
for(uint8_t i = 0; i < EP_COUNT - 1; i++)
{
USB->DOEP[i].CTL |= USB_DIEP_CTL_SNAK;
}
/* D. Interruption masking */
/* Disable all device interrupts */
USB->DIEPMSK = 0;
USB->DOEPMSK = 0;
USB->DAINTMSK = 0;
USB->DIEPEMPMSK = 0;
USB->GINTMSK = 0;
USB->GOTGINT = ~0U; /* clear OTG ints */
USB->GINTSTS = ~0U; /* clear pending ints */
USB->GINTMSK = USB_GINTMSK_MODEMISMSK |
#if USE_SOF
USB_GINTMSK_SOFMSK |
#endif
USB_GINTMSK_ERLYSUSPMSK |
USB_GINTMSK_USBSUSPMSK |
USB_GINTMSK_USBRSTMSK |
USB_GINTMSK_ENUMDONEMSK |
USB_GINTMSK_RESETDETMSK |
USB_GINTMSK_DISCONNINTMSK;
NVIC_ClearPendingIRQ(USB_IRQn);
dcd_connect(rhport);
}
void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
{
(void) rhport;
USB->DCFG = (USB->DCFG & ~_USB_DCFG_DEVADDR_MASK) | (dev_addr << _USB_DCFG_DEVADDR_SHIFT);
/* 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;
}
void dcd_connect(uint8_t rhport)
{
(void) rhport;
/* connect by enabling internal pull-up resistor on D+/D- */
USB->DCTL &= ~(DCTL_WO_BITMASK | USB_DCTL_SFTDISCON);
}
void dcd_disconnect(uint8_t rhport)
{
(void) rhport;
/* disconnect by disabling internal pull-up resistor on D+/D- */
USB->DCTL = (USB->DCTL & ~(DCTL_WO_BITMASK)) | USB_DCTL_SFTDISCON;
}
/*------------------------------------------------------------------*/
/* DCD Endpoint Port */
/*------------------------------------------------------------------*/
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
if(dir == TUSB_DIR_IN)
{
if(epnum == 0)
{
USB->DIEP0CTL = (USB->DIEP0CTL & ~DEPCTL_WO_BITMASK) | USB_DIEP0CTL_SNAK | USB_DIEP0CTL_STALL;
flush_tx_fifo(_USB_GRSTCTL_TXFNUM_F0);
}
else
{
/* Only disable currently enabled non-control endpoint */
if(USB->DIEP[epnum - 1].CTL & USB_DIEP_CTL_EPENA)
{
USB->DIEP[epnum - 1].CTL = (USB->DIEP[epnum - 1].CTL & ~DEPCTL_WO_BITMASK) | USB_DIEP_CTL_EPDIS | USB_DIEP_CTL_SNAK | USB_DIEP_CTL_STALL;
while(!(USB->DIEP[epnum - 1].INT & USB_DIEP_INT_EPDISBLD));
USB->DIEP[epnum - 1].INT |= USB_DIEP_INT_EPDISBLD;
}
else
{
USB->DIEP[epnum - 1].CTL = (USB->DIEP[epnum - 1].CTL & ~DEPCTL_WO_BITMASK) | USB_DIEP_CTL_SNAK | USB_DIEP_CTL_STALL;
}
/* Flush the FIFO */
uint8_t const fifo_num = ((USB->DIEP[epnum - 1].CTL & _USB_DIEP_CTL_TXFNUM_MASK) >> _USB_DIEP_CTL_TXFNUM_SHIFT);
flush_tx_fifo(fifo_num);
}
}
else
{
if(epnum == 0)
{
USB->DOEP0CTL = (USB->DOEP0CTL & ~DEPCTL_WO_BITMASK) | USB_DIEP0CTL_STALL;
}
else
{
/* Only disable currently enabled non-control endpoint */
if(USB->DOEP[epnum - 1].CTL & USB_DIEP_CTL_EPENA)
{
/* Asserting GONAK is required to STALL an OUT endpoint. */
USB->DCTL |= USB_DCTL_SGOUTNAK;
while(!(USB->GINTSTS & USB_GINTSTS_GOUTNAKEFF));
/* Disable the endpoint. Note that only STALL and not SNAK is set here. */
USB->DOEP[epnum - 1].CTL = (USB->DOEP[epnum - 1].CTL & ~DEPCTL_WO_BITMASK) | USB_DIEP_CTL_EPDIS | USB_DIEP_CTL_STALL;
while(USB->DOEP[epnum - 1].INT & USB_DIEP_INT_EPDISBLD);
USB->DOEP[epnum - 1].INT |= USB_DIEP_INT_EPDISBLD;
/* Allow other OUT endpoints to keep receiving. */
USB->DCTL |= USB_DCTL_CGOUTNAK;
}
else
{
USB->DIEP[epnum - 1].CTL = (USB->DIEP[epnum - 1].CTL & ~DEPCTL_WO_BITMASK) | USB_DIEP_CTL_STALL;
}
}
}
}
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
if(dir == TUSB_DIR_IN)
{
if(epnum == 0)
{
USB->DIEP0CTL &= ~(DEPCTL_WO_BITMASK | USB_DIEP0CTL_STALL);
}
else
{
USB->DIEP[epnum - 1].CTL &= ~(DEPCTL_WO_BITMASK | USB_DIEP_CTL_STALL);
/* Required by USB spec to reset DATA toggle bit to DATA0 on interrupt and bulk endpoints. */
uint8_t eptype = (USB->DIEP[epnum - 1].CTL & _USB_DIEP_CTL_EPTYPE_MASK) >> _USB_DIEP_CTL_EPTYPE_SHIFT;
if((eptype == _USB_DIEP_CTL_EPTYPE_BULK) || (eptype == _USB_DIEP_CTL_EPTYPE_INT))
{
USB->DIEP[epnum - 1].CTL |= USB_DIEP_CTL_SETD0PIDEF;
}
}
}
else
{
if(epnum == 0)
{
USB->DOEP0CTL &= ~(DEPCTL_WO_BITMASK | USB_DOEP0CTL_STALL);
}
else
{
USB->DOEP[epnum - 1].CTL &= ~(DEPCTL_WO_BITMASK | USB_DOEP_CTL_STALL);
/* Required by USB spec to reset DATA toggle bit to DATA0 on interrupt and bulk endpoints. */
uint8_t eptype = (USB->DOEP[epnum - 1].CTL & _USB_DOEP_CTL_EPTYPE_MASK) >> _USB_DOEP_CTL_EPTYPE_SHIFT;
if((eptype == _USB_DOEP_CTL_EPTYPE_BULK) || (eptype == _USB_DOEP_CTL_EPTYPE_INT))
{
USB->DOEP[epnum - 1].CTL |= USB_DOEP_CTL_SETD0PIDEF;
}
}
}
}
bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
{
(void)rhport;
uint8_t const epnum = tu_edpt_number(p_endpoint_desc->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
TU_ASSERT(p_endpoint_desc->wMaxPacketSize.size <= 64);
TU_ASSERT(epnum < EP_COUNT);
TU_ASSERT(epnum != 0);
xfer_ctl_t *xfer = XFER_CTL_BASE(epnum, dir);
xfer->max_size = p_endpoint_desc->wMaxPacketSize.size;
if(dir == TUSB_DIR_OUT)
{
USB->DOEP[epnum - 1].CTL |= USB_DOEP_CTL_USBACTEP |
(p_endpoint_desc->bmAttributes.xfer << _USB_DOEP_CTL_EPTYPE_SHIFT) |
(p_endpoint_desc->wMaxPacketSize.size << _USB_DOEP_CTL_MPS_SHIFT);
USB->DAINTMSK |= (1 << (_USB_DAINTMSK_OUTEPMSK0_SHIFT + epnum));
}
else
{
uint8_t fifo_num = get_free_fifo();
TU_ASSERT(fifo_num != 0);
USB->DIEP[epnum - 1].CTL &= ~(_USB_DIEP_CTL_TXFNUM_MASK | _USB_DIEP_CTL_EPTYPE_MASK | USB_DIEP_CTL_SETD0PIDEF | _USB_DIEP_CTL_MPS_MASK);
USB->DIEP[epnum - 1].CTL |= USB_DIEP_CTL_USBACTEP |
(fifo_num << _USB_DIEP_CTL_TXFNUM_SHIFT) |
(p_endpoint_desc->bmAttributes.xfer << _USB_DIEP_CTL_EPTYPE_SHIFT) |
((p_endpoint_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS) ? USB_DIEP_CTL_SETD0PIDEF : 0) |
(p_endpoint_desc->wMaxPacketSize.size << 0);
USB->DAINTMSK |= (1 << epnum);
/* Both TXFD and TXSA are in unit of 32-bit words. */
/* IN FIFO 0 was configured during enumeration, hence the "+ 16". */
uint16_t const allocated_size = (USB->GRXFSIZ & _USB_GRXFSIZ_RXFDEP_MASK) + 16;
uint16_t const fifo_size = (EP_FIFO_SIZE/4 - allocated_size) / (EP_FIFO_NUM-1);
uint32_t const fifo_offset = allocated_size + fifo_size*(fifo_num-1);
/* DIEPTXF starts at FIFO #1. */
volatile uint32_t* usb_dieptxf = &USB->DIEPTXF1;
usb_dieptxf[epnum - 1] = (fifo_size << _USB_DIEPTXF1_INEPNTXFDEP_SHIFT) | fifo_offset;
}
return true;
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes)
{
(void)rhport;
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->total_len = total_bytes;
xfer->queued_len = 0;
xfer->short_packet = false;
uint16_t num_packets = (total_bytes / xfer->max_size);
uint8_t short_packet_size = total_bytes % xfer->max_size;
// Zero-size packet is special case.
if(short_packet_size > 0 || (total_bytes == 0))
{
num_packets++;
}
// IN and OUT endpoint xfers are interrupt-driven, we just schedule them
// here.
if(dir == TUSB_DIR_IN)
{
if(epnum == 0)
{
// A full IN transfer (multiple packets, possibly) triggers XFRC.
USB->DIEP0TSIZ = (num_packets << _USB_DIEP0TSIZ_PKTCNT_SHIFT) | total_bytes;
USB->DIEP0CTL |= USB_DIEP0CTL_EPENA | USB_DIEP0CTL_CNAK; // Enable | CNAK
}
else
{
// A full IN transfer (multiple packets, possibly) triggers XFRC.
USB->DIEP[epnum - 1].TSIZ = (num_packets << _USB_DIEP_TSIZ_PKTCNT_SHIFT) | total_bytes;
USB->DIEP[epnum - 1].CTL |= USB_DIEP_CTL_EPENA | USB_DIEP_CTL_CNAK; // Enable | CNAK
}
// Enable fifo empty interrupt only if there are something to put in the fifo.
if(total_bytes != 0)
{
USB->DIEPEMPMSK |= (1 << epnum);
}
}
else
{
if(epnum == 0)
{
// A full IN transfer (multiple packets, possibly) triggers XFRC.
USB->DOEP0TSIZ |= (1 << _USB_DOEP0TSIZ_PKTCNT_SHIFT) | ((xfer->max_size & _USB_DOEP0TSIZ_XFERSIZE_MASK) << _USB_DOEP0TSIZ_XFERSIZE_SHIFT);
USB->DOEP0CTL |= USB_DOEP0CTL_EPENA | USB_DOEP0CTL_CNAK;
}
else
{
// A full IN transfer (multiple packets, possibly) triggers XFRC.
USB->DOEP[epnum - 1].TSIZ |= (1 << _USB_DOEP_TSIZ_PKTCNT_SHIFT) | ((xfer->max_size & _USB_DOEP_TSIZ_XFERSIZE_MASK) << _USB_DOEP_TSIZ_XFERSIZE_SHIFT);
USB->DOEP[epnum - 1].CTL |= USB_DOEP_CTL_EPENA | USB_DOEP_CTL_CNAK;
}
}
return true;
}
/*------------------------------------------------------------------*/
/* IRQ */
/*------------------------------------------------------------------*/
void dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(USB_IRQn);
}
void dcd_int_disable(uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(USB_IRQn);
}
static void receive_packet(xfer_ctl_t *xfer, uint16_t xfer_size)
{
uint16_t remaining = xfer->total_len - xfer->queued_len;
uint16_t to_recv_size;
if(remaining <= xfer->max_size)
{
/* Avoid buffer overflow. */
to_recv_size = (xfer_size > remaining) ? remaining : xfer_size;
}
else
{
/* Room for full packet, choose recv_size based on what the microcontroller claims. */
to_recv_size = (xfer_size > xfer->max_size) ? xfer->max_size : xfer_size;
}
uint8_t to_recv_rem = to_recv_size % 4;
uint16_t to_recv_size_aligned = to_recv_size - to_recv_rem;
/* Do not assume xfer buffer is aligned. */
uint8_t *base = (xfer->buffer + xfer->queued_len);
/* This for loop always runs at least once- skip if less than 4 bytes to collect. */
if(to_recv_size >= 4)
{
for(uint16_t i = 0; i < to_recv_size_aligned; i += 4)
{
uint32_t tmp = (*USB->FIFO0D);
base[i] = tmp & 0x000000FF;
base[i + 1] = (tmp & 0x0000FF00) >> 8;
base[i + 2] = (tmp & 0x00FF0000) >> 16;
base[i + 3] = (tmp & 0xFF000000) >> 24;
}
}
/* Do not read invalid bytes from RX FIFO. */
if(to_recv_rem != 0)
{
uint32_t tmp = (*USB->FIFO0D);
uint8_t *last_32b_bound = base + to_recv_size_aligned;
last_32b_bound[0] = tmp & 0x000000FF;
if(to_recv_rem > 1)
{
last_32b_bound[1] = (tmp & 0x0000FF00) >> 8;
}
if(to_recv_rem > 2)
{
last_32b_bound[2] = (tmp & 0x00FF0000) >> 16;
}
}
xfer->queued_len += xfer_size;
/* Per USB spec, a short OUT packet (including length 0) is always */
/* indicative of the end of a transfer (at least for ctl, bulk, int). */
xfer->short_packet = (xfer_size < xfer->max_size);
}
static void transmit_packet(xfer_ctl_t *xfer, uint8_t fifo_num)
{
uint16_t remaining;
if(fifo_num == 0)
{
remaining = (USB->DIEP0TSIZ & 0x7FFFFU) >> _USB_DIEP0TSIZ_XFERSIZE_SHIFT;
}
else
{
remaining = (USB->DIEP[fifo_num - 1].TSIZ & 0x7FFFFU) >> _USB_DIEP_TSIZ_XFERSIZE_SHIFT;
}
xfer->queued_len = xfer->total_len - remaining;
uint16_t to_xfer_size = (remaining > xfer->max_size) ? xfer->max_size : remaining;
uint8_t to_xfer_rem = to_xfer_size % 4;
uint16_t to_xfer_size_aligned = to_xfer_size - to_xfer_rem;
/* Buffer might not be aligned to 32b, so we need to force alignment by copying to a temp var. */
uint8_t *base = (xfer->buffer + xfer->queued_len);
/* This for loop always runs at least once- skip if less than 4 bytes to send off. */
if(to_xfer_size >= 4)
{
for(uint16_t i = 0; i < to_xfer_size_aligned; i += 4)
{
uint32_t tmp = base[i] | (base[i + 1] << 8) | (base[i + 2] << 16) | (base[i + 3] << 24);
*tx_fifo[fifo_num] = tmp;
}
}
/* Do not read beyond end of buffer if not divisible by 4. */
if(to_xfer_rem != 0)
{
uint32_t tmp = 0;
uint8_t *last_32b_bound = base + to_xfer_size_aligned;
tmp |= last_32b_bound[0];
if(to_xfer_rem > 1)
{
tmp |= (last_32b_bound[1] << 8);
}
if(to_xfer_rem > 2)
{
tmp |= (last_32b_bound[2] << 16);
}
*tx_fifo[fifo_num] = tmp;
}
}
static void read_rx_fifo(void)
{
/*
* Pop control word off FIFO (completed xfers will have 2 control words,
* we only pop one ctl word each interrupt).
*/
uint32_t const ctl_word = USB->GRXSTSP;
uint8_t const pktsts = (ctl_word & _USB_GRXSTSP_PKTSTS_MASK) >> _USB_GRXSTSP_PKTSTS_SHIFT;
uint8_t const epnum = (ctl_word & _USB_GRXSTSP_CHNUM_MASK ) >> _USB_GRXSTSP_CHNUM_SHIFT;
uint16_t const bcnt = (ctl_word & _USB_GRXSTSP_BCNT_MASK ) >> _USB_GRXSTSP_BCNT_SHIFT;
switch(pktsts)
{
case 0x01: /* Global OUT NAK (Interrupt) */
break;
case 0x02:
{
/* Out packet recvd */
xfer_ctl_t *xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT);
receive_packet(xfer, bcnt);
}
break;
case 0x03:
/* Out packet done (Interrupt) */
break;
case 0x04:
/* Step 2: Setup transaction completed (Interrupt) */
/* After this event, OEPINT interrupt will occur with SETUP bit set */
if(epnum == 0)
{
USB->DOEP0TSIZ |= (1 << _USB_DOEP0TSIZ_SUPCNT_SHIFT);
}
break;
case 0x06:
{
/* Step1: Setup data packet received */
/*
* We can receive up to three setup packets in succession, but
* only the last one is valid. Therefore we just overwrite it
*/
_setup_packet[0] = (*USB->FIFO0D);
_setup_packet[1] = (*USB->FIFO0D);
}
break;
default:
/* Invalid, breakpoint. */
TU_BREAKPOINT();
break;
}
}
static void handle_epout_ints(void)
{
// GINTSTS will be cleared with DAINT == 0
// DAINT for a given EP clears when DOEPINTx is cleared.
// DOEPINT will be cleared when DAINT's out bits are cleared.
for(uint8_t n = 0; n < EP_COUNT; n++)
{
xfer_ctl_t *xfer = XFER_CTL_BASE(n, TUSB_DIR_OUT);
if(n == 0)
{
if(USB->DAINT & (1 << (_USB_DAINT_OUTEPINT0_SHIFT + n)))
{
// SETUP packet Setup Phase done.
if((USB->DOEP0INT & USB_DOEP0INT_SETUP))
{
USB->DOEP0INT = USB_DOEP0INT_STUPPKTRCVD | USB_DOEP0INT_SETUP; // clear
dcd_event_setup_received(0, (uint8_t *)&_setup_packet[0], true);
}
// OUT XFER complete (single packet).q
if(USB->DOEP0INT & USB_DOEP0INT_XFERCOMPL)
{
USB->DOEP0INT = USB_DOEP0INT_XFERCOMPL;
// Transfer complete if short packet or total len is transferred
if(xfer->short_packet || (xfer->queued_len == xfer->total_len))
{
xfer->short_packet = false;
dcd_event_xfer_complete(0, n, xfer->queued_len, XFER_RESULT_SUCCESS, true);
}
else
{
// Schedule another packet to be received.
USB->DOEP0TSIZ |= (1 << _USB_DOEP0TSIZ_PKTCNT_SHIFT) | ((xfer->max_size & _USB_DOEP0TSIZ_XFERSIZE_MASK) << _USB_DOEP0TSIZ_XFERSIZE_SHIFT);
USB->DOEP0CTL |= USB_DOEP0CTL_EPENA | USB_DOEP0CTL_CNAK;
}
}
}
}
else
{
if(USB->DAINT & (1 << (_USB_DAINT_OUTEPINT0_SHIFT + n)))
{
// SETUP packet Setup Phase done.
if((USB->DOEP[n - 1].INT & USB_DOEP_INT_SETUP))
{
USB->DOEP[n - 1].INT = USB_DOEP_INT_STUPPKTRCVD | USB_DOEP_INT_SETUP; // clear
dcd_event_setup_received(0, (uint8_t *)&_setup_packet[0], true);
}
// OUT XFER complete (single packet).q
if(USB->DOEP[n - 1].INT & USB_DOEP_INT_XFERCOMPL)
{
USB->DOEP[n - 1].INT = USB_DOEP_INT_XFERCOMPL;
// Transfer complete if short packet or total len is transferred
if(xfer->short_packet || (xfer->queued_len == xfer->total_len))
{
xfer->short_packet = false;
dcd_event_xfer_complete(0, n, xfer->queued_len, XFER_RESULT_SUCCESS, true);
}
else
{
// Schedule another packet to be received.
USB->DOEP[n - 1].TSIZ |= (1 << _USB_DOEP_TSIZ_PKTCNT_SHIFT) | ((xfer->max_size & _USB_DOEP_TSIZ_XFERSIZE_MASK) << _USB_DOEP_TSIZ_XFERSIZE_SHIFT);
USB->DOEP[n - 1].CTL |= USB_DOEP_CTL_EPENA | USB_DOEP_CTL_CNAK;
}
}
}
}
}
}
static void handle_epin_ints(void)
{
for(uint32_t n = 0; n < EP_COUNT; n++)
{
xfer_ctl_t *xfer = &xfer_status[n][TUSB_DIR_IN];
if(n == 0)
{
if(USB->DAINT & (1 << n))
{
/* IN XFER complete (entire xfer). */
if(USB->DIEP0INT & USB_DIEP0INT_XFERCOMPL)
{
USB->DIEP0INT = USB_DIEP0INT_XFERCOMPL;
dcd_event_xfer_complete(0, n | TUSB_DIR_IN_MASK, xfer->total_len, XFER_RESULT_SUCCESS, true);
}
/* XFER FIFO empty */
if(USB->DIEP0INT & USB_DIEP0INT_TXFEMP)
{
USB->DIEP0INT = USB_DIEP0INT_TXFEMP;
transmit_packet(xfer, n);
/* Turn off TXFE if all bytes are written. */
if(xfer->queued_len == xfer->total_len)
{
USB->DIEPEMPMSK &= ~(1 << n);
}
}
/* XFER Timeout */
if(USB->DIEP0INT & USB_DIEP0INT_TIMEOUT)
{
/* Clear interrupt or enpoint will hang. */
USB->DIEP0INT = USB_DIEP0INT_TIMEOUT;
}
}
}
else
{
if(USB->DAINT & (1 << n))
{
/* IN XFER complete (entire xfer). */
if(USB->DIEP[n - 1].INT & USB_DIEP_INT_XFERCOMPL)
{
USB->DIEP[n - 1].INT = USB_DIEP_INT_XFERCOMPL;
dcd_event_xfer_complete(0, n | TUSB_DIR_IN_MASK, xfer->total_len, XFER_RESULT_SUCCESS, true);
}
/* XFER FIFO empty */
if(USB->DIEP[n - 1].INT & USB_DIEP_INT_TXFEMP)
{
USB->DIEP[n - 1].INT = USB_DIEP_INT_TXFEMP;
transmit_packet(xfer, n);
/* Turn off TXFE if all bytes are written. */
if(xfer->queued_len == xfer->total_len)
{
USB->DIEPEMPMSK &= ~(1 << n);
}
}
/* XFER Timeout */
if(USB->DIEP[n - 1].INT & USB_DIEP_INT_TIMEOUT)
{
/* Clear interrupt or enpoint will hang. */
USB->DIEP[n - 1].INT = USB_DIEP_INT_TIMEOUT;
}
}
}
}
}
void dcd_int_handler(uint8_t rhport)
{
(void) rhport;
const uint32_t int_status = USB->GINTSTS;
/* USB Reset */
if(int_status & USB_GINTSTS_USBRST)
{
/* start of reset */
USB->GINTSTS = USB_GINTSTS_USBRST;
/* FIFOs will be reassigned when the endpoints are reopen */
_allocated_fifos = 1;
bus_reset();
}
/* Reset detected Interrupt */
if(int_status & USB_GINTSTS_RESETDET)
{
USB->GINTSTS = USB_GINTSTS_RESETDET;
bus_reset();
}
/* Enumeration Done */
if(int_status & USB_GINTSTS_ENUMDONE)
{
/* This interrupt is considered the end of reset. */
USB->GINTSTS = USB_GINTSTS_ENUMDONE;
enum_done_processing();
dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true);
}
/* OTG Interrupt */
if(int_status & USB_GINTSTS_OTGINT)
{
/* OTG INT bit is read-only */
uint32_t const otg_int = USB->GOTGINT;
if(otg_int & USB_GOTGINT_SESENDDET)
{
dcd_event_bus_signal(0, DCD_EVENT_UNPLUGGED, true);
}
USB->GOTGINT = otg_int;
}
#if USE_SOF
if(int_status & USB_GINTSTS_SOF)
{
USB->GINTSTS = USB_GINTSTS_SOF;
dcd_event_bus_signal(0, DCD_EVENT_SOF, true);
}
#endif
/* RxFIFO Non-Empty */
if(int_status & USB_GINTSTS_RXFLVL)
{
/* RXFLVL bit is read-only */
/* Mask out RXFLVL while reading data from FIFO */
USB->GINTMSK &= ~USB_GINTMSK_RXFLVLMSK;
read_rx_fifo();
USB->GINTMSK |= USB_GINTMSK_RXFLVLMSK;
}
/* OUT Endpoints Interrupt */
if(int_status & USB_GINTMSK_OEPINTMSK)
{
/* OEPINT is read-only */
handle_epout_ints();
}
/* IN Endpoints Interrupt */
if(int_status & USB_GINTMSK_IEPINTMSK)
{
/* IEPINT bit read-only */
handle_epin_ints();
}
/* unhandled */
USB->GINTSTS |= USB_GINTSTS_CURMOD |
USB_GINTSTS_MODEMIS |
USB_GINTSTS_OTGINT |
USB_GINTSTS_NPTXFEMP |
USB_GINTSTS_GINNAKEFF |
USB_GINTSTS_GOUTNAKEFF |
USB_GINTSTS_ERLYSUSP |
USB_GINTSTS_USBSUSP |
USB_GINTSTS_ISOOUTDROP |
USB_GINTSTS_EOPF |
USB_GINTSTS_EPMIS |
USB_GINTSTS_INCOMPISOIN |
USB_GINTSTS_INCOMPLP |
USB_GINTSTS_FETSUSP |
USB_GINTSTS_PTXFEMP;
}
#endif
+12 -4
View File
@@ -134,7 +134,7 @@ static int _dcd_setup(FAR struct usbdevclass_driver_s *driver, FAR struct usbdev
if (usbdcd_driver.setup_processed)
{
usbdcd_driver.setup_processed = false;
dcd_event_setup_received(0, (uint8_t *) ctrl, true);
dcd_event_setup_received(0, (uint8_t const *) ctrl, true);
}
else
{
@@ -257,6 +257,8 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const *p_endpoint_desc)
uint8_t epnum = tu_edpt_number(p_endpoint_desc->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
uint8_t xfrtype = 0;
uint16_t const ep_mps = tu_edpt_packet_size(p_endpoint_desc);
struct usb_epdesc_s epdesc;
if (epnum >= CXD56_EPNUM)
@@ -287,7 +289,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const *p_endpoint_desc)
usbdcd_driver.req[epnum] = EP_ALLOCREQ(usbdcd_driver.ep[epnum]);
if (usbdcd_driver.req[epnum] != NULL)
{
usbdcd_driver.req[epnum]->len = p_endpoint_desc->wMaxPacketSize.size;
usbdcd_driver.req[epnum]->len = ep_mps;
}
else
{
@@ -300,8 +302,8 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const *p_endpoint_desc)
epdesc.type = p_endpoint_desc->bDescriptorType;
epdesc.addr = p_endpoint_desc->bEndpointAddress;
epdesc.attr = xfrtype;
epdesc.mxpacketsize[0] = LSBYTE(p_endpoint_desc->wMaxPacketSize.size);
epdesc.mxpacketsize[1] = MSBYTE(p_endpoint_desc->wMaxPacketSize.size);
epdesc.mxpacketsize[0] = LSBYTE(ep_mps);
epdesc.mxpacketsize[1] = MSBYTE(ep_mps);
epdesc.interval = p_endpoint_desc->bInterval;
if (EP_CONFIGURE(usbdcd_driver.ep[epnum], &epdesc, false) < 0)
@@ -312,6 +314,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const *p_endpoint_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
{
(void) rhport;
+30 -13
View File
@@ -109,13 +109,10 @@
#define STM32F1_FSDEV
#endif
#if (TUSB_OPT_DEVICE_ENABLED) && ( \
(CFG_TUSB_MCU == OPT_MCU_STM32F0 ) || \
(CFG_TUSB_MCU == OPT_MCU_STM32F1 && defined(STM32F1_FSDEV)) || \
(CFG_TUSB_MCU == OPT_MCU_STM32F3 ) || \
(CFG_TUSB_MCU == OPT_MCU_STM32L0 ) || \
(CFG_TUSB_MCU == OPT_MCU_STM32L1 ) \
)
#if TUSB_OPT_DEVICE_ENABLED && \
( TU_CHECK_MCU(OPT_MCU_STM32F0, OPT_MCU_STM32F3, OPT_MCU_STM32L0, OPT_MCU_STM32L1, OPT_MCU_STM32G4) || \
(TU_CHECK_MCU(OPT_MCU_STM32F1) && defined(STM32F1_FSDEV)) \
)
// In order to reduce the dependance on HAL, we undefine this.
// Some definitions are copied to our private include file.
@@ -299,8 +296,10 @@ void dcd_int_enable (uint8_t rhport)
__ISB();
#if CFG_TUSB_MCU == OPT_MCU_STM32F0 || CFG_TUSB_MCU == OPT_MCU_STM32L0
NVIC_EnableIRQ(USB_IRQn);
#elif CFG_TUSB_MCU == OPT_MCU_STM32L1
NVIC_EnableIRQ(USB_LP_IRQn);
#elif CFG_TUSB_MCU == OPT_MCU_STM32F3
// Some STM32F302/F303 devices allow to remap the USB interrupt vectors from
// shared USB/CAN IRQs to separate CAN and USB IRQs.
@@ -323,6 +322,12 @@ void dcd_int_enable (uint8_t rhport)
NVIC_EnableIRQ(USB_HP_CAN1_TX_IRQn);
NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
NVIC_EnableIRQ(USBWakeUp_IRQn);
#elif CFG_TUSB_MCU == OPT_MCU_STM32G4
NVIC_EnableIRQ(USB_HP_IRQn);
NVIC_EnableIRQ(USB_LP_IRQn);
NVIC_EnableIRQ(USBWakeUp_IRQn);
#else
#error Unknown arch in USB driver
#endif
@@ -359,6 +364,12 @@ void dcd_int_disable(uint8_t rhport)
NVIC_DisableIRQ(USB_HP_CAN1_TX_IRQn);
NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
NVIC_DisableIRQ(USBWakeUp_IRQn);
#elif CFG_TUSB_MCU == OPT_MCU_STM32G4
NVIC_DisableIRQ(USB_HP_IRQn);
NVIC_DisableIRQ(USB_LP_IRQn);
NVIC_DisableIRQ(USBWakeUp_IRQn);
#else
#error Unknown arch in USB driver
#endif
@@ -394,7 +405,7 @@ static const tusb_desc_endpoint_t ep0OUT_desc =
.bEndpointAddress = 0x00,
.bmAttributes = { .xfer = TUSB_XFER_CONTROL },
.wMaxPacketSize = { .size = CFG_TUD_ENDPOINT0_SIZE },
.wMaxPacketSize = CFG_TUD_ENDPOINT0_SIZE,
.bInterval = 0
};
@@ -405,7 +416,7 @@ static const tusb_desc_endpoint_t ep0IN_desc =
.bEndpointAddress = 0x80,
.bmAttributes = { .xfer = TUSB_XFER_CONTROL },
.wMaxPacketSize = { .size = CFG_TUD_ENDPOINT0_SIZE },
.wMaxPacketSize = CFG_TUD_ENDPOINT0_SIZE,
.bInterval = 0
};
@@ -741,7 +752,7 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc
(void)rhport;
uint8_t const epnum = tu_edpt_number(p_endpoint_desc->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
const uint16_t epMaxPktSize = p_endpoint_desc->wMaxPacketSize.size;
const uint16_t epMaxPktSize = tu_edpt_packet_size(p_endpoint_desc);
uint16_t pma_addr;
uint32_t wType;
@@ -778,19 +789,19 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc
// or being double-buffered (bulk endpoints)
pcd_clear_ep_kind(USB,0);
pma_addr = dcd_pma_alloc(p_endpoint_desc->bEndpointAddress, p_endpoint_desc->wMaxPacketSize.size);
pma_addr = dcd_pma_alloc(p_endpoint_desc->bEndpointAddress, epMaxPktSize);
if(dir == TUSB_DIR_IN)
{
*pcd_ep_tx_address_ptr(USB, epnum) = pma_addr;
pcd_set_ep_tx_cnt(USB, epnum, p_endpoint_desc->wMaxPacketSize.size);
pcd_set_ep_tx_cnt(USB, epnum, epMaxPktSize);
pcd_clear_tx_dtog(USB, epnum);
pcd_set_ep_tx_status(USB,epnum,USB_EP_TX_NAK);
}
else
{
*pcd_ep_rx_address_ptr(USB, epnum) = pma_addr;
pcd_set_ep_rx_cnt(USB, epnum, p_endpoint_desc->wMaxPacketSize.size);
pcd_set_ep_rx_cnt(USB, epnum, epMaxPktSize);
pcd_clear_rx_dtog(USB, epnum);
pcd_set_ep_rx_status(USB, epnum, USB_EP_RX_NAK);
}
@@ -800,6 +811,12 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
/**
* Close an endpoint.
*
@@ -87,6 +87,10 @@
#include "stm32l1xx.h"
#define PMA_LENGTH (512u)
#elif CFG_TUSB_MCU == OPT_MCU_STM32G4
#include "stm32g4xx.h"
#define PMA_LENGTH (1024u)
#else
#error You are using an untested or unimplemented STM32 variant. Please update the driver.
// This includes L1x0, L1x1, L1x2, L4x2 and L4x3, G1x1, G1x3, and G1x4
+86 -39
View File
@@ -96,6 +96,9 @@
#elif CFG_TUSB_MCU == OPT_MCU_GD32VF103
#include "synopsys_common.h"
// for remote wakeup delay
#define __NOP() __asm volatile ("nop")
// These numbers are the same for the whole GD32VF103 family.
#define OTG_FS_IRQn 86
#define EP_MAX_FS 4
@@ -213,17 +216,18 @@ static void bus_reset(uint8_t rhport)
tu_memclr(xfer_status, sizeof(xfer_status));
_out_ep_closed = false;
// clear device address
dev->DCFG &= ~USB_OTG_DCFG_DAD_Msk;
// 1. NAK for all OUT endpoints
for(uint8_t n = 0; n < EP_MAX; n++) {
out_ep[n].DOEPCTL |= USB_OTG_DOEPCTL_SNAK;
}
// clear device address
dev->DCFG &= ~USB_OTG_DCFG_DAD_Msk;
// TODO should probably assign value when reset rather than OR
dev->DAINTMSK |= (1 << USB_OTG_DAINTMSK_OEPM_Pos) | (1 << USB_OTG_DAINTMSK_IEPM_Pos);
dev->DOEPMSK |= USB_OTG_DOEPMSK_STUPM | USB_OTG_DOEPMSK_XFRCM;
dev->DIEPMSK |= USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM;
// 2. Un-mask interrupt bits
dev->DAINTMSK = (1 << USB_OTG_DAINTMSK_OEPM_Pos) | (1 << USB_OTG_DAINTMSK_IEPM_Pos);
dev->DOEPMSK = USB_OTG_DOEPMSK_STUPM | USB_OTG_DOEPMSK_XFRCM;
dev->DIEPMSK = USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM;
// "USB Data FIFOs" section in reference manual
// Peripheral FIFO architecture
@@ -307,8 +311,6 @@ static void set_turnaround(USB_OTG_GlobalTypeDef * usb_otg, tusb_speed_t speed)
// Turnaround timeout depends on the MCU clock
uint32_t turnaround;
TU_LOG_INT(2, SystemCoreClock);
if ( SystemCoreClock >= 32000000U )
turnaround = 0x6U;
else if ( SystemCoreClock >= 27500000U )
@@ -368,7 +370,7 @@ static bool USB_HS_PHYCInit(void)
{
USB_HS_PHYC_GlobalTypeDef *usb_hs_phyc = (USB_HS_PHYC_GlobalTypeDef*) USB_HS_PHYC_CONTROLLER_BASE;
// Enable LDO
// Enable LDO: Note STM32F72/3xx Reference Manual rev 3 June 2018 incorrectly defined this bit as Disabled !!
usb_hs_phyc->USB_HS_PHYC_LDO |= USB_HS_PHYC_LDO_ENABLE;
// Wait until LDO ready
@@ -556,13 +558,34 @@ void dcd_set_address (uint8_t rhport, uint8_t dev_addr)
dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0);
}
static void remote_wakeup_delay(void)
{
// try to delay for 1 ms
uint32_t count = SystemCoreClock / 1000;
while ( count-- )
{
__NOP();
}
}
void dcd_remote_wakeup(uint8_t rhport)
{
(void) rhport;
// TODO must manually clear this bit after 1-15 ms
// USB_OTG_DeviceTypeDef * dev = DEVICE_BASE(rhport);
// dev->DCTL |= USB_OTG_DCTL_RWUSIG;
USB_OTG_GlobalTypeDef * usb_otg = GLOBAL_BASE(rhport);
USB_OTG_DeviceTypeDef * dev = DEVICE_BASE(rhport);
// set remote wakeup
dev->DCTL |= USB_OTG_DCTL_RWUSIG;
// enable SOF to detect bus resume
usb_otg->GINTSTS = USB_OTG_GINTSTS_SOF;
usb_otg->GINTMSK |= USB_OTG_GINTMSK_SOFM;
// Per specs: remote wakeup signal bit must be clear within 1-15ms
remote_wakeup_delay();
dev->DCTL &= ~USB_OTG_DCTL_RWUSIG;
}
void dcd_connect(uint8_t rhport)
@@ -599,10 +622,10 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
TU_ASSERT(epnum < EP_MAX);
xfer_ctl_t * xfer = XFER_CTL_BASE(epnum, dir);
xfer->max_size = desc_edpt->wMaxPacketSize.size;
xfer->max_size = tu_edpt_packet_size(desc_edpt);
xfer->interval = desc_edpt->bInterval;
uint16_t const fifo_size = (desc_edpt->wMaxPacketSize.size + 3) / 4; // Round up to next full word
uint16_t const fifo_size = (xfer->max_size + 3) / 4; // Round up to next full word
if(dir == TUSB_DIR_OUT)
{
@@ -618,9 +641,10 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
usb_otg->GRXFSIZ = sz;
}
out_ep[epnum].DOEPCTL |= (1 << USB_OTG_DOEPCTL_USBAEP_Pos) |
(desc_edpt->bmAttributes.xfer << USB_OTG_DOEPCTL_EPTYP_Pos) |
(desc_edpt->wMaxPacketSize.size << USB_OTG_DOEPCTL_MPSIZ_Pos);
out_ep[epnum].DOEPCTL |= (1 << USB_OTG_DOEPCTL_USBAEP_Pos) |
(desc_edpt->bmAttributes.xfer << USB_OTG_DOEPCTL_EPTYP_Pos) |
(desc_edpt->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS ? USB_OTG_DOEPCTL_SD0PID_SEVNFRM : 0) |
(xfer->max_size << USB_OTG_DOEPCTL_MPSIZ_Pos);
dev->DAINTMSK |= (1 << (USB_OTG_DAINTMSK_OEPM_Pos + epnum));
}
@@ -661,8 +685,8 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
in_ep[epnum].DIEPCTL |= (1 << USB_OTG_DIEPCTL_USBAEP_Pos) |
(epnum << USB_OTG_DIEPCTL_TXFNUM_Pos) |
(desc_edpt->bmAttributes.xfer << USB_OTG_DIEPCTL_EPTYP_Pos) |
(desc_edpt->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS ? USB_OTG_DOEPCTL_SD0PID_SEVNFRM : 0) |
(desc_edpt->wMaxPacketSize.size << USB_OTG_DIEPCTL_MPSIZ_Pos);
(desc_edpt->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS ? USB_OTG_DIEPCTL_SD0PID_SEVNFRM : 0) |
(xfer->max_size << USB_OTG_DIEPCTL_MPSIZ_Pos);
dev->DAINTMSK |= (1 << (USB_OTG_DAINTMSK_IEPM_Pos + epnum));
}
@@ -670,6 +694,34 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
return true;
}
// Close all non-control endpoints, cancel all pending transfers if any.
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// USB_OTG_GlobalTypeDef * usb_otg = GLOBAL_BASE(rhport);
USB_OTG_DeviceTypeDef * dev = DEVICE_BASE(rhport);
USB_OTG_OUTEndpointTypeDef * out_ep = OUT_EP_BASE(rhport);
USB_OTG_INEndpointTypeDef * in_ep = IN_EP_BASE(rhport);
// Disable non-control interrupt
dev->DAINTMSK = (1 << USB_OTG_DAINTMSK_OEPM_Pos) | (1 << USB_OTG_DAINTMSK_IEPM_Pos);
for(uint8_t n = 1; n < EP_MAX; n++)
{
// disable OUT endpoint
out_ep[n].DOEPCTL = 0;
xfer_status[n][TUSB_DIR_OUT].max_size = 0;
// disable IN endpoint
in_ep[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);
@@ -829,22 +881,13 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr)
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) {
in_ep[epnum].DIEPCTL &= ~USB_OTG_DIEPCTL_STALL;
uint8_t eptype = (in_ep[epnum].DIEPCTL & USB_OTG_DIEPCTL_EPTYP_Msk) >> USB_OTG_DIEPCTL_EPTYP_Pos;
// Required by USB spec to reset DATA toggle bit to DATA0 on interrupt and bulk endpoints.
if(eptype == 2 || eptype == 3) {
in_ep[epnum].DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM;
}
in_ep[epnum].DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM;
} else {
out_ep[epnum].DOEPCTL &= ~USB_OTG_DOEPCTL_STALL;
uint8_t eptype = (out_ep[epnum].DOEPCTL & USB_OTG_DOEPCTL_EPTYP_Msk) >> USB_OTG_DOEPCTL_EPTYP_Pos;
// Required by USB spec to reset DATA toggle bit to DATA0 on interrupt and bulk endpoints.
if(eptype == 2 || eptype == 3) {
out_ep[epnum].DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM;
}
out_ep[epnum].DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM;
}
}
@@ -933,7 +976,7 @@ static void handle_rxflvl_ints(uint8_t rhport, USB_OTG_OUTEndpointTypeDef * out_
if (xfer->ff)
{
// Ring buffer
tu_fifo_write_n_const_addr_full_words(xfer->ff, (const void *) rx_fifo, bcnt);
tu_fifo_write_n_const_addr_full_words(xfer->ff, (const void *)(uintptr_t) rx_fifo, bcnt);
}
else
{
@@ -1053,7 +1096,7 @@ static void handle_epin_ints(uint8_t rhport, USB_OTG_DeviceTypeDef * dev, USB_OT
if (xfer->ff)
{
usb_fifo_t tx_fifo = FIFO_BASE(rhport, n);
tu_fifo_read_n_const_addr_full_words(xfer->ff, (void *) tx_fifo, packet_size);
tu_fifo_read_n_const_addr_full_words(xfer->ff, (void *)(uintptr_t) tx_fifo, packet_size);
}
else
{
@@ -1081,7 +1124,7 @@ void dcd_int_handler(uint8_t rhport)
USB_OTG_OUTEndpointTypeDef * out_ep = OUT_EP_BASE(rhport);
USB_OTG_INEndpointTypeDef * in_ep = IN_EP_BASE(rhport);
uint32_t int_status = usb_otg->GINTSTS;
uint32_t const int_status = usb_otg->GINTSTS & usb_otg->GINTMSK;
if(int_status & USB_OTG_GINTSTS_USBRST)
{
@@ -1114,6 +1157,9 @@ void dcd_int_handler(uint8_t rhport)
dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true);
}
// TODO check USB_OTG_GINTSTS_DISCINT for disconnect detection
// if(int_status & USB_OTG_GINTSTS_DISCINT)
if(int_status & USB_OTG_GINTSTS_OTGINT)
{
// OTG INT bit is read-only
@@ -1127,13 +1173,15 @@ void dcd_int_handler(uint8_t rhport)
usb_otg->GOTGINT = otg_int;
}
#if USE_SOF
if(int_status & USB_OTG_GINTSTS_SOF)
{
usb_otg->GINTSTS = USB_OTG_GINTSTS_SOF;
// Disable SOF interrupt since currently only used for remote wakeup detection
usb_otg->GINTMSK &= ~USB_OTG_GINTMSK_SOFM;
dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true);
}
#endif
// RxFIFO non-empty interrupt handling.
if(int_status & USB_OTG_GINTSTS_RXFLVL)
@@ -1147,8 +1195,7 @@ void dcd_int_handler(uint8_t rhport)
do
{
handle_rxflvl_ints(rhport, out_ep);
int_status = usb_otg->GINTSTS;
} while(int_status & USB_OTG_GINTSTS_RXFLVL);
} while(usb_otg->GINTSTS & USB_OTG_GINTSTS_RXFLVL);
// Manage RX FIFO size
if (_out_ep_closed)
File diff suppressed because it is too large Load Diff
+89
View File
@@ -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/interrupts.h"
#include "broadcom/caches.h"
#define DWC2_REG_BASE USB_OTG_GLOBAL_BASE
#define DWC2_EP_MAX 8
#define DWC2_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)
{
(void) rhport;
BP_EnableIRQ(USB_IRQn);
__asm__ volatile("isb"); // needed if TIMER1 IRQ is not enabled !?
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
BP_DisableIRQ(USB_IRQn);
__asm__ volatile("isb"); // needed if TIMER1 IRQ is not enabled !?
}
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
+87
View File
@@ -0,0 +1,87 @@
/*
* 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
#define DWC2_EP_FIFO_SIZE 2048
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(USB_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(USB_IRQn);
}
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
+94
View File
@@ -0,0 +1,94 @@
/*
* 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 5 // USB_OUT_EP_NUM
#define DWC2_EP_FIFO_SIZE 1024
// #define EP_FIFO_NUM 5
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_ */
+100
View File
@@ -0,0 +1,100 @@
/*
* 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
#define DWC2_EP_FIFO_SIZE 1280
#define RHPORT_IRQn 86
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)
{
(void) rhport;
__eclic_enable_interrupt(RHPORT_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
__eclic_disable_interrupt(RHPORT_IRQn);
}
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_ */
+205
View File
@@ -0,0 +1,205 @@
/*
* 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
#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
#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
#else
#error "Unsupported MCUs"
#endif
// On STM32 we associate Port0 to OTG_FS, and Port1 to OTG_HS
#if TUD_OPT_RHPORT == 0
#define DWC2_REG_BASE USB_OTG_FS_PERIPH_BASE
#define DWC2_EP_MAX EP_MAX_FS
#define DWC2_EP_FIFO_SIZE EP_FIFO_SIZE_FS
#define RHPORT_IRQn OTG_FS_IRQn
#else
#define DWC2_REG_BASE USB_OTG_HS_PERIPH_BASE
#define DWC2_EP_MAX EP_MAX_HS
#define DWC2_EP_FIFO_SIZE EP_FIFO_SIZE_HS
#define RHPORT_IRQn OTG_HS_IRQn
#endif
extern uint32_t SystemCoreClock;
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(RHPORT_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(RHPORT_IRQn);
}
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
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;
}else
{
// Disable FS PHY
dwc2->stm32_gccfg &= ~STM32_GCCFG_PWRDWN;
// 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;
#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 /* _DWC2_STM32_H_ */
File diff suppressed because it is too large Load Diff
+87
View File
@@ -0,0 +1,87 @@
/*
* 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_XMC_H_
#define _DWC2_XMC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "xmc_device.h"
// XMC has custom control register before DWC registers
#define DWC2_REG_BASE USB0_BASE
#define DWC2_EP_MAX 7
#define DWC2_EP_FIFO_SIZE 2048
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(USB0_0_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(USB0_0_IRQn);
}
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;
// XMC Manual: turn around must be 5 (reset & default value)
// dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_TRDT_Msk) | (5u << GUSBCFG_TRDT_Pos);
}
#ifdef __cplusplus
}
#endif
#endif
+777
View File
@@ -0,0 +1,777 @@
# DWC2 Hardware Configuration Registers
## Broadcom BCM2711 (Pi4)
dwc2->guid = 2708A000
dwc2->gsnpsid = 4F54280A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 228DDD50
hw_cfg2->op_mode = 0
hw_cfg2->arch = 2
hw_cfg2->point2point = 0
hw_cfg2->hs_phy_type = 1
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 7
hw_cfg2->num_host_ch = 7
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 0
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = FF000E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 0
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 0
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 0
hw_cfg3->lpm_mode = 0
hw_cfg3->total_fifo_size = 4080
dwc2->ghwcfg4 = 1FF00020
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 0
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 0
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 15
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## EFM32GG FS
dwc2->guid = 0
dwc2->gsnpsid = 4F54330A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 228F5910
hw_cfg2->op_mode = 0
hw_cfg2->arch = 2
hw_cfg2->point2point = 0
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 6
hw_cfg2->num_host_ch = 13
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 0
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 1F204E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 0
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 1
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 0
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 0
hw_cfg3->lpm_mode = 0
hw_cfg3->total_fifo_size = 498
dwc2->ghwcfg4 = 1BF08030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 2
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 13
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## ESP32-S2 Fullspeed
dwc2->guid = 0
dwc2->gsnpsid = 4F54400A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 224DD930
hw_cfg2->op_mode = 2
hw_cfg2->arch = 3
hw_cfg2->point2point = 0
hw_cfg2->hs_phy_type = 1
hw_cfg2->fs_phy_type = 2
hw_cfg2->num_dev_ep = 6
hw_cfg2->num_host_ch = 9
hw_cfg2->period_channel_support = 0
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 1
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 22
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = C804B5
hw_cfg3->xfer_size_width = 10
hw_cfg3->packet_size_width = 5
hw_cfg3->otg_enable = 0
hw_cfg3->i2c_enable = 0
hw_cfg3->vendor_ctrl_itf = 1
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 1
hw_cfg3->otg_adp_support = 1
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 1
hw_cfg3->lpm_mode = 0
hw_cfg3->total_fifo_size = 23130
dwc2->ghwcfg4 = D3F0A030
hw_cfg4->num_dev_period_in_ep = 10
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 0
hw_cfg4->hibernation = 1
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 1
hw_cfg4->acg_enable = 1
hw_cfg4->utmi_phy_data_width = 1
hw_cfg4->dev_ctrl_ep_num = 10
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 0
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 0
hw_cfg4->dedicated_fifos = 0
hw_cfg4->num_dev_in_eps = 13
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 1
## STM32F407 and STM32F207
STM32F407 and STM32F207 are exactly the same
### STM32F407 Fullspeed
dwc2->guid = 1200
dwc2->gsnpsid = 4F54281A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229DCD20
hw_cfg2->op_mode = 0
hw_cfg2->arch = 0
hw_cfg2->point2point = 1
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 3
hw_cfg2->num_host_ch = 7
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 20001E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 1
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 0
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 0
hw_cfg3->lpm_mode = 0
hw_cfg3->total_fifo_size = 512
dwc2->ghwcfg4 = FF08030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 2
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 7
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
### STM32F407 Highspeed
dwc2->guid = 1100
dwc2->gsnpsid = 4F54281A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229ED590
hw_cfg2->op_mode = 0
hw_cfg2->arch = 2
hw_cfg2->point2point = 0
hw_cfg2->hs_phy_type = 2
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 5
hw_cfg2->num_host_ch = 11
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 3F403E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 1
hw_cfg3->vendor_ctrl_itf = 1
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 0
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 0
hw_cfg3->lpm_mode = 0
hw_cfg3->total_fifo_size = 1012
dwc2->ghwcfg4 = 17F00030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 0
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 11
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## STM32F411 Fullspeed
dwc2->guid = 1200
dwc2->gsnpsid = 4F54281A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229DCD20
hw_cfg2->op_mode = 0
hw_cfg2->arch = 0
hw_cfg2->point2point = 1
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 3
hw_cfg2->num_host_ch = 7
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 20001E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 1
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 0
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 0
hw_cfg3->lpm_mode = 0
hw_cfg3->total_fifo_size = 512
dwc2->ghwcfg4 = FF08030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 2
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 7
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## STM32F412 FS
dwc2->guid = 2000
dwc2->gsnpsid = 4F54320A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229ED520
hw_cfg2->op_mode = 0
hw_cfg2->arch = 0
hw_cfg2->point2point = 1
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 5
hw_cfg2->num_host_ch = 11
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 200D1E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 1
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 1
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 1
hw_cfg3->lpm_mode = 1
hw_cfg3->total_fifo_size = 512
dwc2->ghwcfg4 = 17F08030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 2
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 11
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## STM32F723
### STM32F723 HighSpeed
dwc2->guid = 3100
dwc2->gsnpsid = 4F54330A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229FE1D0
hw_cfg2->op_mode = 0
hw_cfg2->arch = 2
hw_cfg2->point2point = 0
hw_cfg2->hs_phy_type = 3
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 8
hw_cfg2->num_host_ch = 15
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 3EED2E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 0
hw_cfg3->vendor_ctrl_itf = 1
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 1
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 1
hw_cfg3->lpm_mode = 1
hw_cfg3->total_fifo_size = 1006
dwc2->ghwcfg4 = 23F00030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 0
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 1
hw_cfg4->dma_desc_enable = 1
hw_cfg4->dma_dynamic = 0
### STM32F723 Fullspeed
dwc2->guid = 3000
dwc2->gsnpsid = 4F54330A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229ED520
hw_cfg2->op_mode = 0
hw_cfg2->arch = 0
hw_cfg2->point2point = 1
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 5
hw_cfg2->num_host_ch = 11
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 200D1E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 1
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 1
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 1
hw_cfg3->lpm_mode = 1
hw_cfg3->total_fifo_size = 512
dwc2->ghwcfg4 = 17F08030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 2
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 11
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## STM32F767 FS
dwc2->guid = 2000
dwc2->gsnpsid = 4F54320A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229ED520
hw_cfg2->op_mode = 0
hw_cfg2->arch = 0
hw_cfg2->point2point = 1
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 5
hw_cfg2->num_host_ch = 11
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 200D1E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 1
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 1
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 1
hw_cfg3->lpm_mode = 1
hw_cfg3->total_fifo_size = 512
dwc2->ghwcfg4 = 17F08030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 2
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 11
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## STM32H743 (both cores HS)
dwc2->guid = 2300
dwc2->gsnpsid = 4F54330A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229FE190
hw_cfg2->op_mode = 0
hw_cfg2->arch = 2
hw_cfg2->point2point = 0
hw_cfg2->hs_phy_type = 2
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 8
hw_cfg2->num_host_ch = 15
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 3B8D2E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 0
hw_cfg3->vendor_ctrl_itf = 1
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 1
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 1
hw_cfg3->lpm_mode = 1
hw_cfg3->total_fifo_size = 952
dwc2->ghwcfg4 = E3F00030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 0
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 1
hw_cfg4->dma_desc_enable = 1
hw_cfg4->dma_dynamic = 1
## STM32L476 FS
dwc2->guid = 2000
dwc2->gsnpsid = 4F54310A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 229ED520
hw_cfg2->op_mode = 0
hw_cfg2->arch = 0
hw_cfg2->point2point = 1
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 5
hw_cfg2->num_host_ch = 11
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 1
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 200D1E8
hw_cfg3->xfer_size_width = 8
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 1
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 1
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 1
hw_cfg3->lpm_mode = 1
hw_cfg3->total_fifo_size = 512
dwc2->ghwcfg4 = 17F08030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 2
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 11
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## GD32VF103 Fullspeed
dwc2->guid = 1000
dwc2->gsnpsid = 0
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 0
hw_cfg2->op_mode = 0
hw_cfg2->arch = 0
hw_cfg2->point2point = 0
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 0
hw_cfg2->num_dev_ep = 0
hw_cfg2->num_host_ch = 0
hw_cfg2->period_channel_support = 0
hw_cfg2->enable_dynamic_fifo = 0
hw_cfg2->mul_cpu_int = 0
hw_cfg2->nperiod_tx_q_depth = 0
hw_cfg2->host_period_tx_q_depth = 0
hw_cfg2->dev_token_q_depth = 0
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 0
hw_cfg3->xfer_size_width = 0
hw_cfg3->packet_size_width = 0
hw_cfg3->otg_enable = 0
hw_cfg3->i2c_enable = 0
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 0
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 0
hw_cfg3->lpm_mode = 0
hw_cfg3->total_fifo_size = 0
dwc2->ghwcfg4 = 0
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 0
hw_cfg4->ahb_freq_min = 0
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 0
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 0
hw_cfg4->vbus_valid_filter_enabled = 0
hw_cfg4->a_valid_filter_enabled = 0
hw_cfg4->b_valid_filter_enabled = 0
hw_cfg4->dedicated_fifos = 0
hw_cfg4->num_dev_in_eps = 0
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 0
## XMC4500
dwc2->guid = AEC000
dwc2->gsnpsid = 4F54292A
dwc2->ghwcfg1 = 0
dwc2->ghwcfg2 = 228F5930
hw_cfg2->op_mode = 0
hw_cfg2->arch = 2
hw_cfg2->point2point = 1
hw_cfg2->hs_phy_type = 0
hw_cfg2->fs_phy_type = 1
hw_cfg2->num_dev_ep = 6
hw_cfg2->num_host_ch = 13
hw_cfg2->period_channel_support = 1
hw_cfg2->enable_dynamic_fifo = 1
hw_cfg2->mul_cpu_int = 0
hw_cfg2->nperiod_tx_q_depth = 2
hw_cfg2->host_period_tx_q_depth = 2
hw_cfg2->dev_token_q_depth = 8
hw_cfg2->otg_enable_ic_usb = 0
dwc2->ghwcfg3 = 27A01E5
hw_cfg3->xfer_size_width = 5
hw_cfg3->packet_size_width = 6
hw_cfg3->otg_enable = 1
hw_cfg3->i2c_enable = 1
hw_cfg3->vendor_ctrl_itf = 0
hw_cfg3->optional_feature_removed = 0
hw_cfg3->synch_reset = 0
hw_cfg3->otg_adp_support = 0
hw_cfg3->otg_enable_hsic = 0
hw_cfg3->battery_charger_support = 0
hw_cfg3->lpm_mode = 0
hw_cfg3->total_fifo_size = 634
dwc2->ghwcfg4 = DBF08030
hw_cfg4->num_dev_period_in_ep = 0
hw_cfg4->power_optimized = 1
hw_cfg4->ahb_freq_min = 1
hw_cfg4->hibernation = 0
hw_cfg4->service_interval_mode = 0
hw_cfg4->ipg_isoc_en = 0
hw_cfg4->acg_enable = 0
hw_cfg4->utmi_phy_data_width = 2
hw_cfg4->dev_ctrl_ep_num = 0
hw_cfg4->iddg_filter_enabled = 1
hw_cfg4->vbus_valid_filter_enabled = 1
hw_cfg4->a_valid_filter_enabled = 1
hw_cfg4->b_valid_filter_enabled = 1
hw_cfg4->dedicated_fifos = 1
hw_cfg4->num_dev_in_eps = 13
hw_cfg4->dma_desc_enable = 0
hw_cfg4->dma_dynamic = 1
+5
View File
@@ -94,6 +94,11 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
return false;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
}
// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack
bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
{
+9 -4
View File
@@ -242,7 +242,7 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
}
xfer_ctl_t * xfer = XFER_CTL_BASE(epnum, dir);
xfer->max_size = desc_edpt->wMaxPacketSize.size;
xfer->max_size = tu_edpt_packet_size(desc_edpt);
// Buffer allocation scheme:
// For simplicity, only single buffer for now, since tinyusb currently waits
@@ -275,7 +275,7 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
// Also, DBUF got set on OUT EP 2 while debugging. Only OUT EPs seem to be
// affected at this time. USB RAM directly precedes main RAM; perhaps I'm
// overwriting registers via buffer overflow w/ my debugging code?
ep_regs[SIZXY] = desc_edpt->wMaxPacketSize.size;
ep_regs[SIZXY] = tu_edpt_packet_size(desc_edpt);
ep_regs[BCTX] |= NAK;
ep_regs[BBAX] = buf_base;
ep_regs[CNF] &= ~(TOGGLE | STALL | DBUF); // ISO xfers not supported on
@@ -298,6 +298,12 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
{
(void) rhport;
@@ -541,6 +547,7 @@ static void transmit_packet(uint8_t ep_num)
}
// Then actually commit to transmit a packet.
uint8_t * base = (xfer->buffer + xfer->queued_len);
uint16_t remaining = xfer->total_len - xfer->queued_len;
uint8_t xfer_size = (xfer->max_size < xfer->total_len) ? xfer->max_size : remaining;
@@ -554,7 +561,6 @@ static void transmit_packet(uint8_t ep_num)
if(ep_num == 0)
{
volatile uint8_t * ep0in_buf = &USBIEP0BUF;
uint8_t * base = (xfer->buffer + xfer->queued_len);
for(uint16_t i = 0; i < xfer_size; i++)
{
ep0in_buf[i] = base[i];
@@ -576,7 +582,6 @@ static void transmit_packet(uint8_t ep_num)
else
#endif
{
uint8_t * base = (xfer->buffer + xfer->queued_len);
for(int i = 0; i < xfer_size; i++)
{
ep_buf[i] = base[i];
+12 -6
View File
@@ -314,13 +314,13 @@ static void dcd_reset(void)
usb_in_ctrl_write(1 << CSR_USB_IN_CTRL_RESET_OFFSET);
usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_RESET_OFFSET);
memset((void *)rx_buffer, 0, sizeof(rx_buffer));
memset((void *)rx_buffer_max, 0, sizeof(rx_buffer_max));
memset((void *)rx_buffer_offset, 0, sizeof(rx_buffer_offset));
memset((void *)(uintptr_t) rx_buffer, 0, sizeof(rx_buffer));
memset((void *)(uintptr_t) rx_buffer_max, 0, sizeof(rx_buffer_max));
memset((void *)(uintptr_t) rx_buffer_offset, 0, sizeof(rx_buffer_offset));
memset((void *)tx_buffer, 0, sizeof(tx_buffer));
memset((void *)tx_buffer_max, 0, sizeof(tx_buffer_max));
memset((void *)tx_buffer_offset, 0, sizeof(tx_buffer_offset));
memset((void *)(uintptr_t) tx_buffer, 0, sizeof(tx_buffer));
memset((void *)(uintptr_t) tx_buffer_max, 0, sizeof(tx_buffer_max));
memset((void *)(uintptr_t) tx_buffer_offset, 0, sizeof(tx_buffer_offset));
tx_ep = 0;
tx_active = false;
@@ -429,6 +429,12 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
(void) rhport;
// TODO implement dcd_edpt_close_all()
}
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
+3 -4
View File
@@ -69,7 +69,7 @@ bool tusb_inited(void)
bool tu_edpt_validate(tusb_desc_endpoint_t const * desc_ep, tusb_speed_t speed)
{
uint16_t const max_packet_size = tu_le16toh(desc_ep->wMaxPacketSize.size);
uint16_t const max_packet_size = tu_edpt_packet_size(desc_ep);
TU_LOG2(" Open EP %02X with Size = %u\r\n", desc_ep->bEndpointAddress, max_packet_size);
switch (desc_ep->bmAttributes.xfer)
@@ -109,9 +109,9 @@ bool tu_edpt_validate(tusb_desc_endpoint_t const * desc_ep, tusb_speed_t speed)
void tu_edpt_bind_driver(uint8_t ep2drv[][2], tusb_desc_interface_t const* desc_itf, uint16_t desc_len, uint8_t driver_id)
{
uint8_t const* p_desc = (uint8_t const*) desc_itf;
uint16_t len = 0;
uint8_t const* desc_end = p_desc + desc_len;
while( len < desc_len )
while( p_desc < desc_end )
{
if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
{
@@ -121,7 +121,6 @@ void tu_edpt_bind_driver(uint8_t ep2drv[][2], tusb_desc_interface_t const* desc_
ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)] = driver_id;
}
len = (uint16_t)(len + tu_desc_len(p_desc));
p_desc = tu_desc_next(p_desc);
}
}
+8 -4
View File
@@ -76,9 +76,13 @@
#include "class/msc/msc_device.h"
#endif
#if CFG_TUD_AUDIO
#include "class/audio/audio_device.h"
#endif
#if CFG_TUD_AUDIO
#include "class/audio/audio_device.h"
#endif
#if CFG_TUD_VIDEO
#include "class/video/video_device.h"
#endif
#if CFG_TUD_MIDI
#include "class/midi/midi_device.h"
@@ -100,7 +104,7 @@
#include "class/dfu/dfu_device.h"
#endif
#if CFG_TUD_NET
#if CFG_TUD_ECM_RNDIS || CFG_TUD_NCM
#include "class/net/net_device.h"
#endif
+81 -23
View File
@@ -27,8 +27,10 @@
#ifndef _TUSB_OPTION_H_
#define _TUSB_OPTION_H_
#include "common/tusb_compiler.h"
#define TUSB_VERSION_MAJOR 0
#define TUSB_VERSION_MINOR 11
#define TUSB_VERSION_MINOR 12
#define TUSB_VERSION_REVISION 0
#define TUSB_VERSION_STRING TU_STRING(TUSB_VERSION_MAJOR) "." TU_STRING(TUSB_VERSION_MINOR) "." TU_STRING(TUSB_VERSION_REVISION)
@@ -36,7 +38,6 @@
// Supported MCUs
// CFG_TUSB_MCU must be defined to one of following value
//--------------------------------------------------------------------+
#define TU_CHECK_MCU(_m) (CFG_TUSB_MCU == OPT_MCU_##_m)
#define OPT_MCU_NONE 0
@@ -67,22 +68,27 @@
#define OPT_MCU_SAMX7X 207 ///< MicroChip SAME70, S70, V70, V71 family
// STM32
#define OPT_MCU_STM32F0 300 ///< ST STM32F0
#define OPT_MCU_STM32F1 301 ///< ST STM32F1
#define OPT_MCU_STM32F2 302 ///< ST STM32F2
#define OPT_MCU_STM32F3 303 ///< ST STM32F3
#define OPT_MCU_STM32F4 304 ///< ST STM32F4
#define OPT_MCU_STM32F7 305 ///< ST STM32F7
#define OPT_MCU_STM32H7 306 ///< ST STM32H7
#define OPT_MCU_STM32L0 307 ///< ST STM32L0
#define OPT_MCU_STM32L1 308 ///< ST STM32L1
#define OPT_MCU_STM32L4 309 ///< ST STM32L4
#define OPT_MCU_STM32F0 300 ///< ST F0
#define OPT_MCU_STM32F1 301 ///< ST F1
#define OPT_MCU_STM32F2 302 ///< ST F2
#define OPT_MCU_STM32F3 303 ///< ST F3
#define OPT_MCU_STM32F4 304 ///< ST F4
#define OPT_MCU_STM32F7 305 ///< ST F7
#define OPT_MCU_STM32H7 306 ///< ST H7
#define OPT_MCU_STM32L1 308 ///< ST L1
#define OPT_MCU_STM32L0 307 ///< ST L0
#define OPT_MCU_STM32L4 309 ///< ST L4
#define OPT_MCU_STM32G0 310 ///< ST G0
#define OPT_MCU_STM32G4 311 ///< ST G4
// Sony
#define OPT_MCU_CXD56 400 ///< SONY CXD56
// TI MSP430
// TI
#define OPT_MCU_MSP430x5xx 500 ///< TI MSP430x5xx
#define OPT_MCU_MSP432E4 510 ///< TI MSP432E4xx
#define OPT_MCU_TM4C123 511 ///< TI Tiva-C 123x
#define OPT_MCU_TM4C129 512 ///< TI Tiva-C 129x
// ValentyUSB eptri
#define OPT_MCU_VALENTYUSB_EPTRI 600 ///< Fomu eptri config
@@ -112,8 +118,6 @@
// Silabs
#define OPT_MCU_EFM32GG 1300 ///< Silabs EFM32GG
#define OPT_MCU_EFM32GG11 1301 ///< Silabs EFM32GG11
#define OPT_MCU_EFM32GG12 1302 ///< Silabs EFM32GG12
// Renesas RX
#define OPT_MCU_RX63X 1400 ///< Renesas RX63N/631
@@ -126,9 +130,20 @@
// GigaDevice
#define OPT_MCU_GD32VF103 1600 ///< GigaDevice GD32VF103
// Broadcom
#define OPT_MCU_BCM2711 1700 ///< Broadcom BCM2711
// Infineon
#define OPT_MCU_XMC4000 1800 ///< Infineon XMC4000
// BridgeTek
#define OPT_MCU_FT90X 1700 ///< BridgeTek FT90x
#define OPT_MCU_FT93X 1701 ///< BridgeTek FT93x
#define OPT_MCU_FT90X 1900 ///< BridgeTek FT90x
#define OPT_MCU_FT93X 1901 ///< BridgeTek FT93x
// Helper to check if configured MCU is one of listed
// Apply _TU_CHECK_MCU with || as separator to list of input
#define _TU_CHECK_MCU(_m) (CFG_TUSB_MCU == _m)
#define TU_CHECK_MCU(...) (TU_ARGS_APPLY(_TU_CHECK_MCU, ||, __VA_ARGS__))
//--------------------------------------------------------------------+
// Supported OS
@@ -207,14 +222,20 @@
#define CFG_TUSB_MEM_SECTION
#endif
// alignment requirement of buffer used for endpoint transferring
#ifndef CFG_TUSB_MEM_ALIGN
#define CFG_TUSB_MEM_ALIGN TU_ATTR_ALIGNED(4)
#endif
// OS selection
#ifndef CFG_TUSB_OS
#define CFG_TUSB_OS OPT_OS_NONE
#endif
#ifndef CFG_TUSB_OS_INC_PATH
#define CFG_TUSB_OS_INC_PATH
#endif
//--------------------------------------------------------------------
// DEVICE OPTIONS
//--------------------------------------------------------------------
@@ -239,6 +260,10 @@
#define CFG_TUD_AUDIO 0
#endif
#ifndef CFG_TUD_VIDEO
#define CFG_TUD_VIDEO 0
#endif
#ifndef CFG_TUD_MIDI
#define CFG_TUD_MIDI 0
#endif
@@ -259,14 +284,23 @@
#define CFG_TUD_DFU 0
#endif
#ifndef CFG_TUD_NET
#define CFG_TUD_NET 0
#endif
#ifndef CFG_TUD_BTH
#define CFG_TUD_BTH 0
#endif
#ifndef CFG_TUD_ECM_RNDIS
#ifdef CFG_TUD_NET
#warning "CFG_TUD_NET is renamed to CFG_TUD_ECM_RNDIS"
#define CFG_TUD_ECM_RNDIS CFG_TUD_NET
#else
#define CFG_TUD_ECM_RNDIS 0
#endif
#endif
#ifndef CFG_TUD_NCM
#define CFG_TUD_NCM 0
#endif
//--------------------------------------------------------------------
// HOST OPTIONS
//--------------------------------------------------------------------
@@ -278,10 +312,34 @@
#ifndef CFG_TUH_ENUMERATION_BUFSIZE
#define CFG_TUH_ENUMERATION_BUFSIZE 256
#endif
//------------- CLASS -------------//
#endif // TUSB_OPT_HOST_ENABLED
//------------- CLASS -------------//
#ifndef CFG_TUH_HUB
#define CFG_TUH_HUB 0
#endif
#ifndef CFG_TUH_CDC
#define CFG_TUH_CDC 0
#endif
#ifndef CFG_TUH_HID
#define CFG_TUH_HID 0
#endif
#ifndef CFG_TUH_MIDI
#define CFG_TUH_MIDI 0
#endif
#ifndef CFG_TUH_MSC
#define CFG_TUH_MSC 0
#endif
#ifndef CFG_TUH_VENDOR
#define CFG_TUH_VENDOR 0
#endif
//--------------------------------------------------------------------+
// Port Specific
// TUP stand for TinyUSB Port (can be renamed)