diff options
| author | hathach <[email protected]> | 2018-12-12 16:49:38 +0700 |
|---|---|---|
| committer | hathach <[email protected]> | 2018-12-12 16:49:38 +0700 |
| commit | aa17ec60d3abdc3179d4d496bc072ed633bb67ce (patch) | |
| tree | cda3b554b289ab50f650aa0e7b30adb79e33be22 /src | |
| parent | c4a37237171855c0147699c263673c88f2fa6d5d (diff) | |
| parent | 908931320e206e6ae6610cfc56b2a0950f252172 (diff) | |
Merge branch 'develop'
Diffstat (limited to 'src')
75 files changed, 20039 insertions, 0 deletions
diff --git a/src/class/cdc/cdc.h b/src/class/cdc/cdc.h new file mode 100644 index 000000000..d07c62429 --- /dev/null +++ b/src/class/cdc/cdc.h @@ -0,0 +1,413 @@ +/**************************************************************************/
+/*!
+ @file cdc.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_class
+ * \defgroup ClassDriver_CDC Communication Device Class (CDC)
+ * Currently only Abstract Control Model subclass is supported
+ * @{ */
+
+#ifndef _TUSB_CDC_H__
+#define _TUSB_CDC_H__
+
+#include "common/tusb_common.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/** \defgroup ClassDriver_CDC_Common Common Definitions
+ * @{ */
+
+
+/// CDC Pipe ID, used to indicate which pipe the API is addressing to (Notification, Out, In)
+typedef enum
+{
+ CDC_PIPE_NOTIFICATION , ///< Notification pipe
+ CDC_PIPE_DATA_IN , ///< Data in pipe
+ CDC_PIPE_DATA_OUT , ///< Data out pipe
+ CDC_PIPE_ERROR , ///< Invalid Pipe ID
+}cdc_pipeid_t;
+
+//--------------------------------------------------------------------+
+// CDC COMMUNICATION INTERFACE CLASS
+//--------------------------------------------------------------------+
+/// 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_NETWORKING_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_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_type_t;
+
+//------------- SubType Descriptor in COMM Functional Descriptor -------------//
+/// Communication Interface SubType Descriptor
+typedef enum
+{
+ CDC_FUNC_DESC_HEADER = 0x00 , ///< Header Functional Descriptor, which marks the beginning of the concatenated set of functional descriptors for the interface.
+ CDC_FUNC_DESC_CALL_MANAGEMENT = 0x01 , ///< Call Management Functional Descriptor.
+ CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT = 0x02 , ///< Abstract Control Management Functional Descriptor.
+ CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT = 0x03 , ///< Direct Line Management Functional Descriptor.
+ CDC_FUNC_DESC_TELEPHONE_RINGER = 0x04 , ///< Telephone Ringer Functional Descriptor.
+ CDC_FUNC_DESC_TELEPHONE_CALL_AND_LINE_STATE_REPORTING_CAPACITY = 0x05 , ///< Telephone Call and Line State Reporting Capabilities Functional Descriptor.
+ CDC_FUNC_DESC_UNION = 0x06 , ///< Union Functional Descriptor
+ CDC_FUNC_DESC_COUNTRY_SELECTION = 0x07 , ///< Country Selection Functional Descriptor
+ CDC_FUNC_DESC_TELEPHONE_OPERATIONAL_MODES = 0x08 , ///< Telephone Operational ModesFunctional Descriptor
+ CDC_FUNC_DESC_USB_TERMINAL = 0x09 , ///< USB Terminal Functional Descriptor
+ CDC_FUNC_DESC_NETWORK_CHANNEL_TERMINAL = 0x0A , ///< Network Channel Terminal Descriptor
+ CDC_FUNC_DESC_PROTOCOL_UNIT = 0x0B , ///< Protocol Unit Functional Descriptor
+ CDC_FUNC_DESC_EXTENSION_UNIT = 0x0C , ///< Extension Unit Functional Descriptor
+ CDC_FUNC_DESC_MULTICHANEL_MANAGEMENT = 0x0D , ///< Multi-Channel Management Functional Descriptor
+ CDC_FUNC_DESC_CAPI_CONTROL_MANAGEMENT = 0x0E , ///< CAPI Control Management Functional Descriptor
+ CDC_FUNC_DESC_ETHERNET_NETWORKING = 0x0F , ///< Ethernet Networking Functional Descriptor
+ CDC_FUNC_DESC_ATM_NETWORKING = 0x10 , ///< ATM Networking Functional Descriptor
+ CDC_FUNC_DESC_WIRELESS_HANDSET_CONTROL_MODEL = 0x11 , ///< Wireless Handset Control Model Functional Descriptor
+ CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL = 0x12 , ///< Mobile Direct Line Model Functional Descriptor
+ CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL_DETAIL = 0x13 , ///< MDLM Detail Functional Descriptor
+ CDC_FUNC_DESC_DEVICE_MANAGEMENT_MODEL = 0x14 , ///< Device Management Model Functional Descriptor
+ CDC_FUNC_DESC_OBEX = 0x15 , ///< OBEX Functional Descriptor
+ 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_type_t;
+
+//--------------------------------------------------------------------+
+// CDC DATA INTERFACE CLASS
+//--------------------------------------------------------------------+
+
+// SUBCLASS code of Data Interface is not used and should/must be zero
+/// Data Interface Protocol Codes
+typedef enum{
+ CDC_DATA_PROTOCOL_ISDN_BRI = 0x30, ///< Physical interface protocol for ISDN BRI
+ CDC_DATA_PROTOCOL_HDLC = 0x31, ///< HDLC
+ CDC_DATA_PROTOCOL_TRANSPARENT = 0x32, ///< Transparent
+ CDC_DATA_PROTOCOL_Q921_MANAGEMENT = 0x50, ///< Management protocol for Q.921 data link protocol
+ CDC_DATA_PROTOCOL_Q921_DATA_LINK = 0x51, ///< Data link protocol for Q.931
+ CDC_DATA_PROTOCOL_Q921_TEI_MULTIPLEXOR = 0x52, ///< TEI-multiplexor for Q.921 data link protocol
+ CDC_DATA_PROTOCOL_V42BIS_DATA_COMPRESSION = 0x90, ///< Data compression procedures
+ CDC_DATA_PROTOCOL_EURO_ISDN = 0x91, ///< Euro-ISDN protocol control
+ CDC_DATA_PROTOCOL_V24_RATE_ADAPTION_TO_ISDN = 0x92, ///< V.24 rate adaptation to ISDN
+ CDC_DATA_PROTOCOL_CAPI_COMMAND = 0x93, ///< CAPI Commands
+ CDC_DATA_PROTOCOL_HOST_BASED_DRIVER = 0xFD, ///< Host based driver. Note: This protocol code should only be used in messages between host and device to identify the host driver portion of a protocol stack.
+ CDC_DATA_PROTOCOL_IN_PROTOCOL_UNIT_FUNCTIONAL_DESCRIPTOR = 0xFE ///< The protocol(s) are described using a ProtocolUnit Functional Descriptors on Communications Class Interface
+}cdc_data_protocol_type_t;
+
+//--------------------------------------------------------------------+
+// MANAGEMENT ELEMENT REQUEST (CONTROL ENDPOINT)
+//--------------------------------------------------------------------+
+/// Communication Interface Management Element Request Codes
+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,
+
+ CDC_REQUEST_SET_AUX_LINE_STATE = 0x10,
+ CDC_REQUEST_SET_HOOK_STATE = 0x11,
+ CDC_REQUEST_PULSE_SETUP = 0x12,
+ CDC_REQUEST_SEND_PULSE = 0x13,
+ CDC_REQUEST_SET_PULSE_TIME = 0x14,
+ CDC_REQUEST_RING_AUX_JACK = 0x15,
+
+ CDC_REQUEST_SET_LINE_CODING = 0x20,
+ CDC_REQUEST_GET_LINE_CODING = 0x21,
+ CDC_REQUEST_SET_CONTROL_LINE_STATE = 0x22,
+ CDC_REQUEST_SEND_BREAK = 0x23,
+
+ CDC_REQUEST_SET_RINGER_PARMS = 0x30,
+ CDC_REQUEST_GET_RINGER_PARMS = 0x31,
+ CDC_REQUEST_SET_OPERATION_PARMS = 0x32,
+ CDC_REQUEST_GET_OPERATION_PARMS = 0x33,
+ CDC_REQUEST_SET_LINE_PARMS = 0x34,
+ CDC_REQUEST_GET_LINE_PARMS = 0x35,
+ CDC_REQUEST_DIAL_DIGITS = 0x36,
+ CDC_REQUEST_SET_UNIT_PARAMETER = 0x37,
+ CDC_REQUEST_GET_UNIT_PARAMETER = 0x38,
+ CDC_REQUEST_CLEAR_UNIT_PARAMETER = 0x39,
+ CDC_REQUEST_GET_PROFILE = 0x3A,
+
+ CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS = 0x40,
+ CDC_REQUEST_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x41,
+ CDC_REQUEST_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x42,
+ CDC_REQUEST_SET_ETHERNET_PACKET_FILTER = 0x43,
+ CDC_REQUEST_GET_ETHERNET_STATISTIC = 0x44,
+
+ CDC_REQUEST_SET_ATM_DATA_FORMAT = 0x50,
+ CDC_REQUEST_GET_ATM_DEVICE_STATISTICS = 0x51,
+ CDC_REQUEST_SET_ATM_DEFAULT_VC = 0x52,
+ CDC_REQUEST_GET_ATM_VC_STATISTICS = 0x53,
+
+ CDC_REQUEST_MDLM_SEMANTIC_MODEL = 0x60,
+}cdc_management_request_t;
+
+//--------------------------------------------------------------------+
+// MANAGEMENT ELEMENENT NOTIFICATION (NOTIFICATION ENDPOINT)
+//--------------------------------------------------------------------+
+/// Communication Interface Management Element 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_notification_request_t;
+
+//--------------------------------------------------------------------+
+// FUNCTIONAL DESCRIPTOR (COMMUNICATION INTERFACE)
+//--------------------------------------------------------------------+
+/// Header Functional Descriptor (Communication Interface)
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+ uint16_t bcdCDC ; ///< CDC release number in Binary-Coded Decimal
+}cdc_desc_func_header_t;
+
+/// Union Functional Descriptor (Communication Interface)
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+ uint8_t bControlInterface ; ///< Interface number of Communication Interface
+ uint8_t bSubordinateInterface ; ///< Array of Interface number of Data Interface
+}cdc_desc_func_union_t;
+
+#define cdc_desc_func_union_n_t(no_slave)\
+ struct ATTR_PACKED { \
+ uint8_t bLength ;\
+ uint8_t bDescriptorType ;\
+ uint8_t bDescriptorSubType ;\
+ uint8_t bControlInterface ;\
+ uint8_t bSubordinateInterface[no_slave] ;\
+}
+
+/// Country Selection Functional Descriptor (Communication Interface)
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+ uint8_t iCountryCodeRelDate ; ///< Index of a string giving the release date for the implemented ISO 3166 Country Codes.
+ uint16_t wCountryCode[] ; ///< Country code in the format as defined in [ISO3166], release date as specified inoffset 3 for the first supported country.
+}cdc_desc_func_country_selection_t;
+
+#define cdc_desc_func_country_selection_n_t(no_country) \
+ struct ATTR_PACKED {\
+ uint8_t bLength ;\
+ uint8_t bDescriptorType ;\
+ uint8_t bDescriptorSubType ;\
+ uint8_t iCountryCodeRelDate ;\
+ uint16_t wCountryCode[no_country] ;\
+}
+
+//--------------------------------------------------------------------+
+// PUBLIC SWITCHED TELEPHONE NETWORK (PSTN) SUBCLASS
+//--------------------------------------------------------------------+
+
+/// \brief Call Management Functional Descriptor
+/// \details This functional descriptor describes the processing of calls for the Communications Class interface.
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+
+ struct {
+ uint8_t handle_call : 1; ///< 0 - Device sends/receives call management information only over the Communications Class interface. 1 - Device can send/receive call management information over a Data Class interface.
+ uint8_t send_recv_call : 1; ///< 0 - Device does not handle call management itself. 1 - Device handles call management itself.
+ uint8_t : 0;
+ } bmCapabilities;
+
+ uint8_t bDataInterface;
+}cdc_desc_func_call_management_t;
+
+
+typedef struct ATTR_PACKED
+{
+ uint8_t support_comm_request : 1; ///< Device supports the request combination of Set_Comm_Feature, Clear_Comm_Feature, and Get_Comm_Feature.
+ uint8_t support_line_request : 1; ///< Device supports the request combination of Set_Line_Coding, Set_Control_Line_State, Get_Line_Coding, and the notification Serial_State.
+ uint8_t support_send_break : 1; ///< Device supports the request Send_Break
+ uint8_t support_notification_network_connection : 1; ///< Device supports the notification Network_Connection.
+ uint8_t : 0;
+}cdc_acm_capability_t;
+
+TU_VERIFY_STATIC(sizeof(cdc_acm_capability_t) == 1, "mostly problem with compiler");
+
+/// \brief Abstract Control Management Functional Descriptor
+/// \details This functional descriptor describes the commands supported by by the Communications Class interface with SubClass code of \ref CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+ cdc_acm_capability_t bmCapabilities ;
+}cdc_desc_func_acm_t;
+
+/// \brief Direct Line Management Functional Descriptor
+/// \details This functional descriptor describes the commands supported by the Communications Class interface with SubClass code of \ref CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+ struct {
+ uint8_t require_pulse_setup : 1; ///< Device requires extra Pulse_Setup request during pulse dialing sequence to disengage holding circuit.
+ uint8_t support_aux_request : 1; ///< Device supports the request combination of Set_Aux_Line_State, Ring_Aux_Jack, and notification Aux_Jack_Hook_State.
+ uint8_t support_pulse_request : 1; ///< Device supports the request combination of Pulse_Setup, Send_Pulse, and Set_Pulse_Time.
+ uint8_t : 0;
+ } bmCapabilities;
+}cdc_desc_func_direct_line_management_t;
+
+/// \brief Telephone Ringer Functional Descriptor
+/// \details The Telephone Ringer functional descriptor describes the ringer capabilities supported by the Communications Class interface,
+/// with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+ uint8_t bRingerVolSteps ;
+ uint8_t bNumRingerPatterns ;
+}cdc_desc_func_telephone_ringer_t;
+
+/// \brief Telephone Operational Modes Functional Descriptor
+/// \details The Telephone Operational Modes functional descriptor describes the operational modes supported by
+/// the Communications Class interface, with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+ struct {
+ uint8_t simple_mode : 1;
+ uint8_t standalone_mode : 1;
+ uint8_t computer_centric_mode : 1;
+ uint8_t : 0;
+ } bmCapabilities;
+}cdc_desc_func_telephone_operational_modes_t;
+
+/// \brief Telephone Call and Line State Reporting Capabilities Descriptor
+/// \details The Telephone Call and Line State Reporting Capabilities functional descriptor describes the abilities of a
+/// telephone device to report optional call and line states.
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
+ uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
+ struct {
+ uint32_t interrupted_dialtone : 1; ///< 0 : Reports only dialtone (does not differentiate between normal and interrupted dialtone). 1 : Reports interrupted dialtone in addition to normal dialtone
+ uint32_t ringback_busy_fastbusy : 1; ///< 0 : Reports only dialing state. 1 : Reports ringback, busy, and fast busy states.
+ uint32_t caller_id : 1; ///< 0 : Does not report caller ID. 1 : Reports caller ID information.
+ uint32_t incoming_distinctive : 1; ///< 0 : Reports only incoming ringing. 1 : Reports incoming distinctive ringing patterns.
+ uint32_t dual_tone_multi_freq : 1; ///< 0 : Cannot report dual tone multi-frequency (DTMF) digits input remotely over the telephone line. 1 : Can report DTMF digits input remotely over the telephone line.
+ uint32_t line_state_change : 1; ///< 0 : Does not support line state change notification. 1 : Does support line state change notification
+ uint32_t : 0;
+ } bmCapabilities;
+}cdc_desc_func_telephone_call_state_reporting_capabilities_t;
+
+static inline uint8_t cdc_functional_desc_typeof(uint8_t const * p_desc)
+{
+ return p_desc[2];
+}
+
+//--------------------------------------------------------------------+
+// Requests
+//--------------------------------------------------------------------+
+typedef struct ATTR_PACKED
+{
+ uint32_t bit_rate;
+ uint8_t stop_bits; ///< 0: 1 stop bit - 1: 1.5 stop bits - 2: 2 stop bits
+ uint8_t parity; ///< 0: None - 1: Odd - 2: Even - 3: Mark - 4: Space
+ uint8_t data_bits; ///< can be 5, 6, 7, 8 or 16
+} cdc_line_coding_t;
+
+TU_VERIFY_STATIC(sizeof(cdc_line_coding_t) == 7, "size is not correct");
+
+typedef struct ATTR_PACKED
+{
+ uint16_t dte_is_present : 1; ///< Indicates to DCE if DTE is presentor not. This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR.
+ uint16_t half_duplex_carrier_control : 1;
+ uint16_t : 14;
+} cdc_line_control_state_t;
+
+TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct");
+
+/** @} */
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif
+
+/** @} */
diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c new file mode 100644 index 000000000..7ec7a1eb2 --- /dev/null +++ b/src/class/cdc/cdc_device.c @@ -0,0 +1,395 @@ +/**************************************************************************/
+/*!
+ @file cdc_device.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_CDC)
+
+#define _TINY_USB_SOURCE_FILE_
+
+#include "cdc_device.h"
+#include "device/usbd_pvt.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+typedef struct
+{
+ uint8_t itf_num;
+ uint8_t ep_notif;
+ uint8_t ep_in;
+ uint8_t ep_out;
+
+ // Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send)
+ uint8_t line_state;
+
+ /*------------- From this point, data is not cleared by bus reset -------------*/
+ char wanted_char;
+ cdc_line_coding_t line_coding;
+
+ // FIFO
+ tu_fifo_t rx_ff;
+ tu_fifo_t tx_ff;
+
+ uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE];
+ uint8_t tx_ff_buf[CFG_TUD_CDC_TX_BUFSIZE];
+
+#if CFG_FIFO_MUTEX
+ osal_mutex_def_t rx_ff_mutex;
+ osal_mutex_def_t tx_ff_mutex;
+#endif
+
+ // Endpoint Transfer buffer
+ CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_CDC_EPSIZE];
+ CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE];
+
+}cdcd_interface_t;
+
+#define ITF_MEM_RESET_SIZE offsetof(cdcd_interface_t, wanted_char)
+
+//--------------------------------------------------------------------+
+// INTERNAL OBJECT & FUNCTION DECLARATION
+//--------------------------------------------------------------------+
+CFG_TUSB_MEM_SECTION static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC];
+
+//--------------------------------------------------------------------+
+// APPLICATION API
+//--------------------------------------------------------------------+
+bool tud_cdc_n_connected(uint8_t itf)
+{
+ // DTR (bit 0) active is considered as connected
+ return BIT_TEST_(_cdcd_itf[itf].line_state, 0);
+}
+
+uint8_t tud_cdc_n_get_line_state (uint8_t itf)
+{
+ return _cdcd_itf[itf].line_state;
+}
+
+void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding)
+{
+ (*coding) = _cdcd_itf[itf].line_coding;
+}
+
+void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted)
+{
+ _cdcd_itf[itf].wanted_char = wanted;
+}
+
+
+//--------------------------------------------------------------------+
+// READ API
+//--------------------------------------------------------------------+
+uint32_t tud_cdc_n_available(uint8_t itf)
+{
+ return tu_fifo_count(&_cdcd_itf[itf].rx_ff);
+}
+
+char tud_cdc_n_read_char(uint8_t itf)
+{
+ char ch;
+ return tu_fifo_read(&_cdcd_itf[itf].rx_ff, &ch) ? ch : (-1);
+}
+
+uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize)
+{
+ return tu_fifo_read_n(&_cdcd_itf[itf].rx_ff, buffer, bufsize);
+}
+
+char tud_cdc_n_peek(uint8_t itf, int pos)
+{
+ char ch;
+ return tu_fifo_peek_at(&_cdcd_itf[itf].rx_ff, pos, &ch) ? ch : (-1);
+}
+
+void tud_cdc_n_read_flush (uint8_t itf)
+{
+ tu_fifo_clear(&_cdcd_itf[itf].rx_ff);
+}
+
+//--------------------------------------------------------------------+
+// WRITE API
+//--------------------------------------------------------------------+
+
+uint32_t tud_cdc_n_write_char(uint8_t itf, char ch)
+{
+ return tud_cdc_n_write(itf, &ch, 1);
+}
+
+uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str)
+{
+ return tud_cdc_n_write(itf, str, strlen(str));
+}
+
+uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize)
+{
+ uint16_t ret = tu_fifo_write_n(&_cdcd_itf[itf].tx_ff, buffer, bufsize);
+
+#if 0 // TODO issue with circuitpython's REPL
+ // flush if queue more than endpoint size
+ if ( tu_fifo_count(&_cdcd_itf[itf].tx_ff) >= CFG_TUD_CDC_EPSIZE )
+ {
+ tud_cdc_n_write_flush(itf);
+ }
+#endif
+
+ return ret;
+}
+
+bool tud_cdc_n_write_flush (uint8_t itf)
+{
+ cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
+ TU_VERIFY( !dcd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete
+
+ uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE);
+ if ( count )
+ {
+ TU_VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected
+ TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_in, p_cdc->epin_buf, count) );
+ }
+
+ return true;
+}
+
+
+//--------------------------------------------------------------------+
+// USBD Driver API
+//--------------------------------------------------------------------+
+void cdcd_init(void)
+{
+ tu_memclr(_cdcd_itf, sizeof(_cdcd_itf));
+
+ for(uint8_t i=0; i<CFG_TUD_CDC; i++)
+ {
+ cdcd_interface_t* p_cdc = &_cdcd_itf[i];
+
+ p_cdc->wanted_char = -1;
+
+ // default line coding is : stop bit = 1, parity = none, data bits = 8
+ p_cdc->line_coding.bit_rate = 115200;
+ p_cdc->line_coding.stop_bits = 0;
+ p_cdc->line_coding.parity = 0;
+ p_cdc->line_coding.data_bits = 8;
+
+ // config fifo
+ tu_fifo_config(&p_cdc->rx_ff, p_cdc->rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, true);
+ tu_fifo_config(&p_cdc->tx_ff, p_cdc->tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false);
+
+#if CFG_FIFO_MUTEX
+ tu_fifo_config_mutex(&p_cdc->rx_ff, osal_mutex_create(&p_cdc->rx_ff_mutex));
+ tu_fifo_config_mutex(&p_cdc->tx_ff, osal_mutex_create(&p_cdc->tx_ff_mutex));
+#endif
+ }
+}
+
+void cdcd_reset(uint8_t rhport)
+{
+ (void) rhport;
+
+ for(uint8_t i=0; i<CFG_TUD_CDC; i++)
+ {
+ tu_memclr(&_cdcd_itf[i], ITF_MEM_RESET_SIZE);
+ tu_fifo_clear(&_cdcd_itf[i].rx_ff);
+ tu_fifo_clear(&_cdcd_itf[i].tx_ff);
+ }
+}
+
+bool cdcd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length)
+{
+ // Only support ACM subclass
+ TU_ASSERT ( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL == itf_desc->bInterfaceSubClass);
+
+ // Only support AT commands, no protocol and vendor specific commands.
+ TU_ASSERT(tu_within(CDC_COMM_PROTOCOL_NONE, itf_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) ||
+ itf_desc->bInterfaceProtocol == 0xff);
+
+ // Find available interface
+ cdcd_interface_t * p_cdc = NULL;
+ for(uint8_t i=0; i<CFG_TUD_CDC; i++)
+ {
+ if ( _cdcd_itf[i].ep_in == 0 )
+ {
+ p_cdc = &_cdcd_itf[i];
+ break;
+ }
+ }
+ TU_ASSERT(p_cdc);
+
+ //------------- Control Interface -------------//
+ p_cdc->itf_num = itf_desc->bInterfaceNumber;
+
+ uint8_t const * p_desc = tu_desc_next( itf_desc );
+ (*p_length) = sizeof(tusb_desc_interface_t);
+
+ // Communication Functional Descriptors
+ while ( TUSB_DESC_CLASS_SPECIFIC == tu_desc_type(p_desc) )
+ {
+ (*p_length) += tu_desc_len(p_desc);
+ p_desc = tu_desc_next(p_desc);
+ }
+
+ if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
+ {
+ // notification endpoint if any
+ TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc) );
+
+ p_cdc->ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress;
+
+ (*p_length) += p_desc[DESC_OFFSET_LEN];
+ p_desc = tu_desc_next(p_desc);
+ }
+
+ //------------- Data Interface (if any) -------------//
+ if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) &&
+ (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) )
+ {
+ // next to endpoint descriptor
+ (*p_length) += tu_desc_len(p_desc);
+ p_desc = tu_desc_next(p_desc);
+
+ // Open endpoint pair with usbd helper
+ tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) p_desc;
+ TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_cdc->ep_out, &p_cdc->ep_in) );
+
+ (*p_length) += 2*sizeof(tusb_desc_endpoint_t);
+ }
+
+ // Prepare for incoming data
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE) );
+
+ return true;
+}
+
+// Invoked when class request DATA stage is finished.
+// return false to stall control endpoint (e.g Host send non-sense DATA)
+bool cdcd_control_request_complete(uint8_t rhport, tusb_control_request_t const * request)
+{
+ (void) rhport;
+
+ //------------- Class Specific Request -------------//
+ TU_VERIFY (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
+
+ // TODO Support multiple interfaces
+ uint8_t const itf = 0;
+ cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
+
+ // Invoke callback
+ if ( CDC_REQUEST_SET_LINE_CODING == request->bRequest )
+ {
+ if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding);
+ }
+
+ return true;
+}
+
+// Handle class control request
+// return false to stall control endpoint (e.g unsupported request)
+bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request)
+{
+ //------------- Class Specific Request -------------//
+ TU_ASSERT(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
+
+ // TODO Support multiple interfaces
+ uint8_t const itf = 0;
+ cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
+
+ switch ( request->bRequest )
+ {
+ case CDC_REQUEST_SET_LINE_CODING:
+ usbd_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t));
+ break;
+
+ case CDC_REQUEST_GET_LINE_CODING:
+ usbd_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t));
+ break;
+
+ case CDC_REQUEST_SET_CONTROL_LINE_STATE:
+ // CDC PSTN v1.2 section 6.3.12
+ // Bit 0: Indicates if DTE is present or not.
+ // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready)
+ // Bit 1: Carrier control for half-duplex modems.
+ // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send)
+ p_cdc->line_state = (uint8_t) request->wValue;
+
+ usbd_control_status(rhport, request);
+
+ // Invoke callback
+ if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, BIT_TEST_(request->wValue, 0), BIT_TEST_(request->wValue, 1));
+ break;
+
+ default: return false; // stall unsupported request
+ }
+
+ return true;
+}
+
+bool cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
+{
+ (void) result;
+
+ // TODO Support multiple interfaces
+ uint8_t const itf = 0;
+ cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
+
+ // receive new data
+ if ( ep_addr == p_cdc->ep_out )
+ {
+ for(uint32_t i=0; i<xferred_bytes; i++)
+ {
+ tu_fifo_write(&p_cdc->rx_ff, &p_cdc->epout_buf[i]);
+
+ // Check for wanted char and invoke callback if needed
+ if ( tud_cdc_rx_wanted_cb && ( ((signed char) p_cdc->wanted_char) != -1 ) && ( p_cdc->wanted_char == p_cdc->epout_buf[i] ) )
+ {
+ tud_cdc_rx_wanted_cb(itf, p_cdc->wanted_char);
+ }
+ }
+
+ // invoke receive callback (if there is still data)
+ if (tud_cdc_rx_cb && tu_fifo_count(&p_cdc->rx_ff) ) tud_cdc_rx_cb(itf);
+
+ // prepare for incoming data
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_cdc->ep_out, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE) );
+ }
+
+ // nothing to do with in and notif endpoint
+
+ return true;
+}
+
+#endif
diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h new file mode 100644 index 000000000..5ee649c4b --- /dev/null +++ b/src/class/cdc/cdc_device.h @@ -0,0 +1,131 @@ +/**************************************************************************/
+/*!
+ @file cdc_device.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_CDC_DEVICE_H_
+#define _TUSB_CDC_DEVICE_H_
+
+#include "common/tusb_common.h"
+#include "device/usbd.h"
+#include "cdc.h"
+
+//--------------------------------------------------------------------+
+// Class Driver Configuration
+//--------------------------------------------------------------------+
+#ifndef CFG_TUD_CDC_EPSIZE
+#define CFG_TUD_CDC_EPSIZE 64
+#endif
+
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/** \addtogroup CDC_Serial Serial
+ * @{
+ * \defgroup CDC_Serial_Device Device
+ * @{ */
+
+//--------------------------------------------------------------------+
+// APPLICATION API (Multiple Interfaces)
+// CFG_TUD_CDC > 1
+//--------------------------------------------------------------------+
+bool tud_cdc_n_connected (uint8_t itf);
+uint8_t tud_cdc_n_get_line_state (uint8_t itf);
+void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding);
+void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted);
+
+uint32_t tud_cdc_n_available (uint8_t itf);
+char tud_cdc_n_read_char (uint8_t itf);
+uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize);
+void tud_cdc_n_read_flush (uint8_t itf);
+char tud_cdc_n_peek (uint8_t itf, int pos);
+
+uint32_t tud_cdc_n_write_char (uint8_t itf, char ch);
+uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize);
+uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str);
+bool tud_cdc_n_write_flush (uint8_t itf);
+
+//--------------------------------------------------------------------+
+// APPLICATION API (Interface0)
+//--------------------------------------------------------------------+
+static inline bool tud_cdc_connected (void) { return tud_cdc_n_connected(0); }
+static inline uint8_t tud_cdc_get_line_state (void) { return tud_cdc_n_get_line_state(0); }
+static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding) { return tud_cdc_n_get_line_coding(0, coding);}
+static inline void tud_cdc_set_wanted_char (char wanted) { tud_cdc_n_set_wanted_char(0, wanted); }
+
+static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); }
+static inline char tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); }
+static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_cdc_n_read(0, buffer, bufsize); }
+static inline void tud_cdc_read_flush (void) { tud_cdc_n_read_flush(0); }
+static inline char tud_cdc_peek (int pos) { return tud_cdc_n_peek(0, pos); }
+
+static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); }
+static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_cdc_n_write(0, buffer, bufsize); }
+static inline uint32_t tud_cdc_write_str (char const* str) { return tud_cdc_n_write_str(0, str); }
+static inline bool tud_cdc_write_flush (void) { return tud_cdc_n_write_flush(0); }
+
+//--------------------------------------------------------------------+
+// APPLICATION CALLBACK API (WEAK is optional)
+//--------------------------------------------------------------------+
+ATTR_WEAK void tud_cdc_rx_cb(uint8_t itf);
+ATTR_WEAK void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char);
+ATTR_WEAK void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts);
+ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding);
+
+//--------------------------------------------------------------------+
+// USBD-CLASS DRIVER API
+//--------------------------------------------------------------------+
+#ifdef _TINY_USB_SOURCE_FILE_
+
+void cdcd_init (void);
+bool cdcd_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length);
+bool cdcd_control_request (uint8_t rhport, tusb_control_request_t const * p_request);
+bool cdcd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request);
+bool cdcd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
+void cdcd_reset (uint8_t rhport);
+
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_CDC_DEVICE_H_ */
+
+/** @} */
+/** @} */
diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c new file mode 100644 index 000000000..d6767d0a7 --- /dev/null +++ b/src/class/cdc/cdc_host.c @@ -0,0 +1,239 @@ +/**************************************************************************/
+/*!
+ @file cdc_host.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if (TUSB_OPT_HOST_ENABLED && CFG_TUH_CDC)
+
+#define _TINY_USB_SOURCE_FILE_
+
+#include "common/tusb_common.h"
+#include "cdc_host.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+typedef struct {
+ uint8_t itf_num;
+ uint8_t itf_protocol;
+
+ uint8_t ep_notif;
+ uint8_t ep_in;
+ uint8_t ep_out;
+
+ cdc_acm_capability_t acm_capability;
+
+} cdch_data_t;
+
+//--------------------------------------------------------------------+
+// INTERNAL OBJECT & FUNCTION DECLARATION
+//--------------------------------------------------------------------+
+static cdch_data_t cdch_data[CFG_TUSB_HOST_DEVICE_MAX];
+
+bool tuh_cdc_mounted(uint8_t dev_addr)
+{
+ cdch_data_t* cdc = &cdch_data[dev_addr-1];
+ return cdc->ep_in && cdc->ep_out;
+}
+
+bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid)
+{
+ if ( !tuh_cdc_mounted(dev_addr) ) return false;
+
+ cdch_data_t const * p_cdc = &cdch_data[dev_addr-1];
+
+ switch (pipeid)
+ {
+ case CDC_PIPE_NOTIFICATION:
+ return hcd_edpt_busy(dev_addr, p_cdc->ep_notif );
+
+ case CDC_PIPE_DATA_IN:
+ return hcd_edpt_busy(dev_addr, p_cdc->ep_in );
+
+ case CDC_PIPE_DATA_OUT:
+ return hcd_edpt_busy(dev_addr, p_cdc->ep_out );
+
+ default:
+ return false;
+ }
+}
+
+//--------------------------------------------------------------------+
+// APPLICATION API (parameter validation needed)
+//--------------------------------------------------------------------+
+bool tuh_cdc_serial_is_mounted(uint8_t dev_addr)
+{
+ // TODO consider all AT Command as serial candidate
+ return tuh_cdc_mounted(dev_addr) &&
+ (CDC_COMM_PROTOCOL_ATCOMMAND <= cdch_data[dev_addr-1].itf_protocol) &&
+ (cdch_data[dev_addr-1].itf_protocol <= CDC_COMM_PROTOCOL_ATCOMMAND_CDMA);
+}
+
+bool tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify)
+{
+ TU_VERIFY( tuh_cdc_mounted(dev_addr) );
+ TU_VERIFY( p_data != NULL && length, TUSB_ERROR_INVALID_PARA);
+
+ uint8_t const ep_out = cdch_data[dev_addr-1].ep_out;
+ if ( hcd_edpt_busy(dev_addr, ep_out) ) return false;
+
+ return hcd_pipe_xfer(dev_addr, ep_out, (void *) p_data, length, is_notify);
+}
+
+bool tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify)
+{
+ TU_VERIFY( tuh_cdc_mounted(dev_addr) );
+ TU_VERIFY( p_buffer != NULL && length, TUSB_ERROR_INVALID_PARA);
+
+ uint8_t const ep_in = cdch_data[dev_addr-1].ep_in;
+ if ( hcd_edpt_busy(dev_addr, ep_in) ) return false;
+
+ return hcd_pipe_xfer(dev_addr, ep_in, p_buffer, length, is_notify);
+}
+
+//--------------------------------------------------------------------+
+// USBH-CLASS DRIVER API
+//--------------------------------------------------------------------+
+void cdch_init(void)
+{
+ tu_memclr(cdch_data, sizeof(cdch_data_t)*CFG_TUSB_HOST_DEVICE_MAX);
+}
+
+bool cdch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length)
+{
+ // Only support ACM
+ TU_VERIFY( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL == itf_desc->bInterfaceSubClass);
+
+ // Only support AT commands, no protocol and vendor specific commands.
+ TU_VERIFY(tu_within(CDC_COMM_PROTOCOL_NONE, itf_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) ||
+ 0xff == itf_desc->bInterfaceProtocol);
+
+ uint8_t const * p_desc;
+ cdch_data_t * p_cdc;
+
+ p_desc = tu_desc_next(itf_desc);
+ p_cdc = &cdch_data[dev_addr-1];
+
+ p_cdc->itf_num = itf_desc->bInterfaceNumber;
+ p_cdc->itf_protocol = itf_desc->bInterfaceProtocol; // TODO 0xff is consider as rndis candidate, other is virtual Com
+
+ //------------- Communication Interface -------------//
+ (*p_length) = sizeof(tusb_desc_interface_t);
+
+ // Communication Functional Descriptors
+ while( TUSB_DESC_CLASS_SPECIFIC == p_desc[DESC_OFFSET_TYPE] )
+ {
+ if ( CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc) )
+ {
+ // save ACM bmCapabilities
+ p_cdc->acm_capability = ((cdc_desc_func_acm_t const *) p_desc)->bmCapabilities;
+ }
+
+ (*p_length) += p_desc[DESC_OFFSET_LEN];
+ p_desc = tu_desc_next(p_desc);
+ }
+
+ if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE])
+ {
+ // notification endpoint
+ tusb_desc_endpoint_t const * ep_desc = (tusb_desc_endpoint_t const *) p_desc;
+
+ TU_ASSERT( hcd_edpt_open(rhport, dev_addr, ep_desc) );
+ p_cdc->ep_notif = ep_desc->bEndpointAddress;
+
+ (*p_length) += p_desc[DESC_OFFSET_LEN];
+ p_desc = tu_desc_next(p_desc);
+ }
+
+ //------------- Data Interface (if any) -------------//
+ if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) &&
+ (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) )
+ {
+ (*p_length) += p_desc[DESC_OFFSET_LEN];
+ p_desc = tu_desc_next(p_desc);
+
+ // data endpoints expected to be in pairs
+ for(uint32_t i=0; i<2; i++)
+ {
+ tusb_desc_endpoint_t const *ep_desc = (tusb_desc_endpoint_t const *) p_desc;
+ TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType);
+ TU_ASSERT(TUSB_XFER_BULK == ep_desc->bmAttributes.xfer);
+
+ TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc));
+
+ if ( tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN )
+ {
+ p_cdc->ep_in = ep_desc->bEndpointAddress;
+ }else
+ {
+ p_cdc->ep_out = ep_desc->bEndpointAddress;
+ }
+
+ (*p_length) += p_desc[DESC_OFFSET_LEN];
+ p_desc = tu_desc_next( p_desc );
+ }
+ }
+
+ // FIXME move to seperate API : connect
+ tusb_control_request_t request =
+ {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT },
+ .bRequest = CDC_REQUEST_SET_CONTROL_LINE_STATE,
+ .wValue = 0x03, // dtr on, cst on
+ .wIndex = p_cdc->itf_num,
+ .wLength = 0
+ };
+
+ TU_ASSERT( usbh_control_xfer(dev_addr, &request, NULL) );
+
+ return true;
+}
+
+void cdch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
+{
+ (void) ep_addr;
+ tuh_cdc_xfer_isr( dev_addr, event, 0, xferred_bytes );
+}
+
+void cdch_close(uint8_t dev_addr)
+{
+ cdch_data_t * p_cdc = &cdch_data[dev_addr-1];
+ tu_memclr(p_cdc, sizeof(cdch_data_t));
+}
+
+#endif
diff --git a/src/class/cdc/cdc_host.h b/src/class/cdc/cdc_host.h new file mode 100644 index 000000000..5388a8f60 --- /dev/null +++ b/src/class/cdc/cdc_host.h @@ -0,0 +1,140 @@ +/**************************************************************************/
+/*!
+ @file cdc_host.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+
+#ifndef _TUSB_CDC_HOST_H_
+#define _TUSB_CDC_HOST_H_
+
+#include "common/tusb_common.h"
+#include "host/usbh.h"
+#include "cdc.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// CDC APPLICATION PUBLIC API
+//--------------------------------------------------------------------+
+/** \ingroup ClassDriver_CDC Communication Device Class (CDC)
+ * \addtogroup CDC_Serial Serial
+ * @{
+ * \defgroup CDC_Serial_Host Host
+ * @{ */
+
+/** \brief Check if device support CDC Serial interface or not
+ * \param[in] dev_addr device address
+ * \retval true if device supports
+ * \retval false if device does not support or is not mounted
+ */
+bool tuh_cdc_serial_is_mounted(uint8_t dev_addr);
+
+/** \brief Check if the interface is currently busy or not
+ * \param[in] dev_addr device address
+ * \param[in] pipeid value from \ref cdc_pipeid_t to indicate target pipe.
+ * \retval true if the interface is busy, meaning the stack is still transferring/waiting data from/to device
+ * \retval false if the interface is not busy, meaning the stack successfully transferred data from/to device
+ * \note This function is used to check if previous transfer is complete (success or error), so that the next transfer
+ * can be scheduled. User needs to make sure the corresponding interface is mounted
+ * (by \ref tuh_cdc_serial_is_mounted) before calling this function.
+ */
+bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid);
+
+/** \brief Perform USB OUT transfer to device
+ * \param[in] dev_addr device address
+ * \param[in] p_data Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \param[in] length Number of bytes to be transferred via USB bus
+ * \retval TUSB_ERROR_NONE on success
+ * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
+ * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
+ * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
+ * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the
+ * interface's callback function. \a p_data must be declared with \ref CFG_TUSB_MEM_SECTION.
+ */
+bool tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify);
+
+/** \brief Perform USB IN transfer to get data from device
+ * \param[in] dev_addr device address
+ * \param[in] p_buffer Buffer containing received data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \param[in] length Number of bytes to be transferred via USB bus
+ * \retval TUSB_ERROR_NONE on success
+ * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
+ * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
+ * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
+ * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the
+ * interface's callback function. \a p_data must be declared with \ref CFG_TUSB_MEM_SECTION.
+ */
+bool tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify);
+
+//--------------------------------------------------------------------+
+// CDC APPLICATION CALLBACKS
+//--------------------------------------------------------------------+
+
+/** \brief Callback function that is invoked when an transferring event occurred
+ * \param[in] dev_addr Address of device
+ * \param[in] event an value from \ref xfer_result_t
+ * \param[in] pipe_id value from \ref cdc_pipeid_t indicate the pipe
+ * \param[in] xferred_bytes Number of bytes transferred via USB bus
+ * \note event can be one of following
+ * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully.
+ * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error.
+ * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device.
+ * \note
+ */
+void tuh_cdc_xfer_isr(uint8_t dev_addr, xfer_result_t event, cdc_pipeid_t pipe_id, uint32_t xferred_bytes);
+
+/// @} // group CDC_Serial_Host
+/// @}
+
+//--------------------------------------------------------------------+
+// USBH-CLASS API
+//--------------------------------------------------------------------+
+#ifdef _TINY_USB_SOURCE_FILE_
+
+void cdch_init(void);
+bool cdch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length);
+void cdch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
+void cdch_close(uint8_t dev_addr);
+
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_CDC_HOST_H_ */
diff --git a/src/class/cdc/cdc_rndis.h b/src/class/cdc/cdc_rndis.h new file mode 100644 index 000000000..20da5660b --- /dev/null +++ b/src/class/cdc/cdc_rndis.h @@ -0,0 +1,313 @@ +/**************************************************************************/ +/*! + @file cdc_rndis.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup ClassDriver_CDC Communication Device Class (CDC) + * \defgroup CDC_RNDIS Remote Network Driver Interface Specification (RNDIS) + * @{ + * \defgroup CDC_RNDIS_Common Common Definitions + * @{ */ + +#ifndef _TUSB_CDC_RNDIS_H_ +#define _TUSB_CDC_RNDIS_H_ + +#include "cdc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +#ifdef __CC_ARM +#pragma diag_suppress 66 // Suppress Keil warnings #66-D: enumeration value is out of "int" range +#endif + +/// RNDIS Message Types +typedef enum +{ + RNDIS_MSG_PACKET = 0x00000001UL, ///< The host and device use this to send network data to one another. + + RNDIS_MSG_INITIALIZE = 0x00000002UL, ///< Sent by the host to initialize the device. + RNDIS_MSG_INITIALIZE_CMPLT = 0x80000002UL, ///< Device response to an initialize message. + + RNDIS_MSG_HALT = 0x00000003UL, ///< Sent by the host to halt the device. This does not have a response. It is optional for the device to send this message to the host. + + RNDIS_MSG_QUERY = 0x00000004UL, ///< Sent by the host to send a query OID. + RNDIS_MSG_QUERY_CMPLT = 0x80000004UL, ///< Device response to a query OID. + + RNDIS_MSG_SET = 0x00000005UL, ///< Sent by the host to send a set OID. + RNDIS_MSG_SET_CMPLT = 0x80000005UL, ///< Device response to a set OID. + + RNDIS_MSG_RESET = 0x00000006UL, ///< Sent by the host to perform a soft reset on the device. + RNDIS_MSG_RESET_CMPLT = 0x80000006UL, ///< Device response to reset message. + + RNDIS_MSG_INDICATE_STATUS = 0x00000007UL, ///< Sent by the device to indicate its status or an error when an unrecognized message is received. + + RNDIS_MSG_KEEP_ALIVE = 0x00000008UL, ///< During idle periods, sent every few seconds by the host to check that the device is still responsive. It is optional for the device to send this message to check if the host is active. + RNDIS_MSG_KEEP_ALIVE_CMPLT = 0x80000008UL ///< The device response to a keepalivemessage. The host can respond with this message to a keepalive message from the device when the device implements the optional KeepAliveTimer. +}rndis_msg_type_t; + +/// RNDIS Message Status Values +typedef enum +{ + RNDIS_STATUS_SUCCESS = 0x00000000UL, ///< Success + RNDIS_STATUS_FAILURE = 0xC0000001UL, ///< Unspecified error + RNDIS_STATUS_INVALID_DATA = 0xC0010015UL, ///< Invalid data error + RNDIS_STATUS_NOT_SUPPORTED = 0xC00000BBUL, ///< Unsupported request error + RNDIS_STATUS_MEDIA_CONNECT = 0x4001000BUL, ///< Device is connected to a network medium. + RNDIS_STATUS_MEDIA_DISCONNECT = 0x4001000CUL ///< Device is disconnected from the medium. +}rndis_msg_status_t; + +#ifdef __CC_ARM +#pragma diag_default 66 // return Keil 66 to normal severity +#endif + +//--------------------------------------------------------------------+ +// MESSAGE STRUCTURE +//--------------------------------------------------------------------+ + +//------------- Initialize -------------// +/// \brief Initialize Message +/// \details This message MUST be sent by the host to initialize the device. +typedef struct { + uint32_t type ; ///< Message type, must be \ref RNDIS_MSG_INITIALIZE + uint32_t length ; ///< Message length in bytes, must be 0x18 + uint32_t request_id ; ///< A 32-bit integer value, generated by the host, used to match the host's sent request to the response from the device. + uint32_t major_version ; ///< The major version of the RNDIS Protocol implemented by the host. + uint32_t minor_version ; ///< The minor version of the RNDIS Protocol implemented by the host + uint32_t max_xfer_size ; ///< The maximum size, in bytes, of any single bus data transfer that the host expects to receive from the device. +}rndis_msg_initialize_t; + +/// \brief Initialize Complete Message +/// \details This message MUST be sent by the device in response to an initialize message. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_INITIALIZE_CMPLT + uint32_t length ; ///< Message length in bytes, must be 0x30 + uint32_t request_id ; ///< A 32-bit integer value from \a request_id field of the \ref rndis_msg_initialize_t to which this message is a response. + uint32_t status ; ///< The initialization status of the device, has value from \ref rndis_msg_status_t + uint32_t major_version ; ///< the highest-numbered RNDIS Protocol version supported by the device. + uint32_t minor_version ; ///< the highest-numbered RNDIS Protocol version supported by the device. + uint32_t device_flags ; ///< MUST be set to 0x000000010. Other values are reserved for future use. + uint32_t medium ; ///< is 0x00 for RNDIS_MEDIUM_802_3 + uint32_t max_packet_per_xfer ; ///< The maximum number of concatenated \ref RNDIS_MSG_PACKET messages that the device can handle in a single bus transfer to it. This value MUST be at least 1. + uint32_t max_xfer_size ; ///< The maximum size, in bytes, of any single bus data transfer that the device expects to receive from the host. + uint32_t packet_alignment_factor ; ///< The byte alignment the device expects for each RNDIS message that is part of a multimessage transfer to it. The value is specified as an exponent of 2; for example, the host uses 2<SUP>{PacketAlignmentFactor}</SUP> as the alignment value. + uint32_t reserved[2] ; +} rndis_msg_initialize_cmplt_t; + +//------------- Query -------------// +/// \brief Query Message +/// \details This message MUST be sent by the host to query an OID. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_QUERY + uint32_t length ; ///< Message length in bytes, including the header and the \a oid_buffer + uint32_t request_id ; ///< A 32-bit integer value, generated by the host, used to match the host's sent request to the response from the device. + uint32_t oid ; ///< The integer value of the host operating system-defined identifier, for the parameter of the device being queried for. + uint32_t buffer_length ; ///< The length, in bytes, of the input data required for the OID query. This MUST be set to 0 when there is no input data associated with the OID. + uint32_t buffer_offset ; ///< The offset, in bytes, from the beginning of \a request_id field where the input data for the query is located in the message. This value MUST be set to 0 when there is no input data associated with the OID. + uint32_t reserved ; + uint8_t oid_buffer[] ; ///< Flexible array contains the input data supplied by the host, required for the OID query request processing by the device, as per the host NDIS specification. +} rndis_msg_query_t, rndis_msg_set_t; + +TU_VERIFY_STATIC(sizeof(rndis_msg_query_t) == 28, "Make sure flexible array member does not affect layout"); + +/// \brief Query Complete Message +/// \details This message MUST be sent by the device in response to a query OID message. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_QUERY_CMPLT + uint32_t length ; ///< Message length in bytes, including the header and the \a oid_buffer + uint32_t request_id ; ///< A 32-bit integer value from \a request_id field of the \ref rndis_msg_query_t to which this message is a response. + uint32_t status ; ///< The status of processing for the query request, has value from \ref rndis_msg_status_t. + uint32_t buffer_length ; ///< The length, in bytes, of the data in the response to the query. This MUST be set to 0 when there is no OIDInputBuffer. + uint32_t buffer_offset ; ///< The offset, in bytes, from the beginning of \a request_id field where the response data for the query is located in the message. This MUST be set to 0 when there is no \ref oid_buffer. + uint8_t oid_buffer[] ; ///< Flexible array member contains the response data to the OID query request as specified by the host. +} rndis_msg_query_cmplt_t; + +TU_VERIFY_STATIC(sizeof(rndis_msg_query_cmplt_t) == 24, "Make sure flexible array member does not affect layout"); + +//------------- Reset -------------// +/// \brief Reset Message +/// \details This message MUST be sent by the host to perform a soft reset on the device. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_RESET + uint32_t length ; ///< Message length in bytes, MUST be 0x06 + uint32_t reserved ; +} rndis_msg_reset_t; + +/// \brief Reset Complete Message +/// \details This message MUST be sent by the device in response to a reset message. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_RESET_CMPLT + uint32_t length ; ///< Message length in bytes, MUST be 0x10 + uint32_t status ; ///< The status of processing for the \ref rndis_msg_reset_t, has value from \ref rndis_msg_status_t. + uint32_t addressing_reset ; ///< This field indicates whether the addressing information, which is the multicast address list or packet filter, has been lost during the reset operation. This MUST be set to 0x00000001 if the device requires that the host to resend addressing information or MUST be set to zero otherwise. +} rndis_msg_reset_cmplt_t; + +//typedef struct { +// uint32_t type; +// uint32_t length; +// uint32_t status; +// uint32_t buffer_length; +// uint32_t buffer_offset; +// uint32_t diagnostic_status; // optional +// uint32_t diagnostic_error_offset; // optional +// uint32_t status_buffer[0]; // optional +//} rndis_msg_indicate_status_t; + +/// \brief Keep Alive Message +/// \details This message MUST be sent by the host to check that device is still responsive. It is optional for the device to send this message to check if the host is active +typedef struct { + uint32_t type ; ///< Message Type + uint32_t length ; ///< Message length in bytes, MUST be 0x10 + uint32_t request_id ; +} rndis_msg_keep_alive_t, rndis_msg_halt_t; + +/// \brief Set Complete Message +/// \brief This message MUST be sent in response to a the request message +typedef struct { + uint32_t type ; ///< Message Type + uint32_t length ; ///< Message length in bytes, MUST be 0x10 + uint32_t request_id ; ///< must be the same as requesting message + uint32_t status ; ///< The status of processing for the request message request by the device to which this message is the response. +} rndis_msg_set_cmplt_t, rndis_msg_keep_alive_cmplt_t; + +/// \brief Packet Data Message +/// \brief This message MUST be used by the host and the device to send network data to one another. +typedef struct { + uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_PACKET + uint32_t length ; ///< Message length in bytes, The total length of this RNDIS message including the header, payload, and padding. + uint32_t data_offset ; ///< Specifies the offset, in bytes, from the start of this \a data_offset field of this message to the start of the data. This MUST be an integer multiple of 4. + uint32_t data_length ; ///< Specifies the number of bytes in the payload of this message. + uint32_t out_of_band_data_offet ; ///< Specifies the offset, in bytes, of the first out-of-band data record from the start of the DataOffset field in this message. MUST be an integer multiple of 4 when out-of-band data is present or set to 0 otherwise. When there are multiple out-ofband data records, each subsequent record MUST immediately follow the previous out-of-band data record. + uint32_t out_of_band_data_length ; ///< Specifies, in bytes, the total length of the out-of-band data. + uint32_t num_out_of_band_data_elements ; ///< Specifies the number of out-of-band records in this message. + uint32_t per_packet_info_offset ; ///< Specifies the offset, in bytes, of the start of per-packet-info data record from the start of the \a data_offset field in this message. MUST be an integer multiple of 4 when per-packet-info data record is present or MUST be set to 0 otherwise. When there are multiple per-packet-info data records, each subsequent record MUST immediately follow the previous record. + uint32_t per_packet_info_length ; ///< Specifies, in bytes, the total length of per-packetinformation contained in this message. + uint32_t reserved[2] ; + uint32_t payload[0] ; ///< Network data contained in this message. + + // uint8_t padding[0] + // Additional bytes of zeros added at the end of the message to comply with + // the internal and external padding requirements. Internal padding SHOULD be as per the + // specification of the out-of-band data record and per-packet-info data record. The external + //padding size SHOULD be determined based on the PacketAlignmentFactor field specification + //in REMOTE_NDIS_INITIALIZE_CMPLT message by the device, when multiple + //REMOTE_NDIS_PACKET_MSG messages are bundled together in a single bus-native message. + //In this case, all but the very last REMOTE_NDIS_PACKET_MSG MUST respect the + //PacketAlignmentFactor field. + + // rndis_msg_packet_t [0] : (optional) more packet if multiple packet per bus transaction is supported +} rndis_msg_packet_t; + + +typedef struct { + uint32_t size ; ///< Length, in bytes, of this header and appended data and padding. This value MUST be an integer multiple of 4. + uint32_t type ; ///< MUST be as per host operating system specification. + uint32_t offset ; ///< The byte offset from the beginning of this record to the beginning of data. + uint32_t data[0] ; ///< Flexible array contains data +} rndis_msg_out_of_band_data_t, rndis_msg_per_packet_info_t; + +//--------------------------------------------------------------------+ +// NDIS Object ID +//--------------------------------------------------------------------+ + +/// NDIS Object ID +typedef enum +{ + //------------- General Required OIDs -------------// + RNDIS_OID_GEN_SUPPORTED_LIST = 0x00010101, ///< List of supported OIDs + RNDIS_OID_GEN_HARDWARE_STATUS = 0x00010102, ///< Hardware status + RNDIS_OID_GEN_MEDIA_SUPPORTED = 0x00010103, ///< Media types supported (encoded) + RNDIS_OID_GEN_MEDIA_IN_USE = 0x00010104, ///< Media types in use (encoded) + RNDIS_OID_GEN_MAXIMUM_LOOKAHEAD = 0x00010105, ///< + RNDIS_OID_GEN_MAXIMUM_FRAME_SIZE = 0x00010106, ///< Maximum frame size in bytes + RNDIS_OID_GEN_LINK_SPEED = 0x00010107, ///< Link speed in units of 100 bps + RNDIS_OID_GEN_TRANSMIT_BUFFER_SPACE = 0x00010108, ///< Transmit buffer space + RNDIS_OID_GEN_RECEIVE_BUFFER_SPACE = 0x00010109, ///< Receive buffer space + RNDIS_OID_GEN_TRANSMIT_BLOCK_SIZE = 0x0001010A, ///< Minimum amount of storage, in bytes, that a single packet occupies in the transmit buffer space of the NIC + RNDIS_OID_GEN_RECEIVE_BLOCK_SIZE = 0x0001010B, ///< Amount of storage, in bytes, that a single packet occupies in the receive buffer space of the NIC + RNDIS_OID_GEN_VENDOR_ID = 0x0001010C, ///< Vendor NIC code + RNDIS_OID_GEN_VENDOR_DESCRIPTION = 0x0001010D, ///< Vendor network card description + RNDIS_OID_GEN_CURRENT_PACKET_FILTER = 0x0001010E, ///< Current packet filter (encoded) + RNDIS_OID_GEN_CURRENT_LOOKAHEAD = 0x0001010F, ///< Current lookahead size in bytes + RNDIS_OID_GEN_DRIVER_VERSION = 0x00010110, ///< NDIS version number used by the driver + RNDIS_OID_GEN_MAXIMUM_TOTAL_SIZE = 0x00010111, ///< Maximum total packet length in bytes + RNDIS_OID_GEN_PROTOCOL_OPTIONS = 0x00010112, ///< Optional protocol flags (encoded) + RNDIS_OID_GEN_MAC_OPTIONS = 0x00010113, ///< Optional NIC flags (encoded) + RNDIS_OID_GEN_MEDIA_CONNECT_STATUS = 0x00010114, ///< Whether the NIC is connected to the network + RNDIS_OID_GEN_MAXIMUM_SEND_PACKETS = 0x00010115, ///< The maximum number of send packets the driver can accept per call to its MiniportSendPacketsfunction + + //------------- General Optional OIDs -------------// + RNDIS_OID_GEN_VENDOR_DRIVER_VERSION = 0x00010116, ///< Vendor-assigned version number of the driver + RNDIS_OID_GEN_SUPPORTED_GUIDS = 0x00010117, ///< The custom GUIDs (Globally Unique Identifier) supported by the miniport driver + RNDIS_OID_GEN_NETWORK_LAYER_ADDRESSES = 0x00010118, ///< List of network-layer addresses associated with the binding between a transport and the driver + RNDIS_OID_GEN_TRANSPORT_HEADER_OFFSET = 0x00010119, ///< Size of packets' additional headers + RNDIS_OID_GEN_MEDIA_CAPABILITIES = 0x00010201, ///< + RNDIS_OID_GEN_PHYSICAL_MEDIUM = 0x00010202, ///< Physical media supported by the miniport driver (encoded) + + //------------- 802.3 Objects (Ethernet) -------------// + RNDIS_OID_802_3_PERMANENT_ADDRESS = 0x01010101, ///< Permanent station address + RNDIS_OID_802_3_CURRENT_ADDRESS = 0x01010102, ///< Current station address + RNDIS_OID_802_3_MULTICAST_LIST = 0x01010103, ///< Current multicast address list + RNDIS_OID_802_3_MAXIMUM_LIST_SIZE = 0x01010104, ///< Maximum size of multicast address list +} rndis_oid_type_t; + +/// RNDIS Packet Filter Bits \ref RNDIS_OID_GEN_CURRENT_PACKET_FILTER. +typedef enum +{ + RNDIS_PACKET_TYPE_DIRECTED = 0x00000001, ///< Directed packets. Directed packets contain a destination address equal to the station address of the NIC. + RNDIS_PACKET_TYPE_MULTICAST = 0x00000002, ///< Multicast address packets sent to addresses in the multicast address list. + RNDIS_PACKET_TYPE_ALL_MULTICAST = 0x00000004, ///< All multicast address packets, not just the ones enumerated in the multicast address list. + RNDIS_PACKET_TYPE_BROADCAST = 0x00000008, ///< Broadcast packets. + RNDIS_PACKET_TYPE_SOURCE_ROUTING = 0x00000010, ///< All source routing packets. If the protocol driver sets this bit, the NDIS library attempts to act as a source routing bridge. + RNDIS_PACKET_TYPE_PROMISCUOUS = 0x00000020, ///< Specifies all packets regardless of whether VLAN filtering is enabled or not and whether the VLAN identifier matches or not. + RNDIS_PACKET_TYPE_SMT = 0x00000040, ///< SMT packets that an FDDI NIC receives. + RNDIS_PACKET_TYPE_ALL_LOCAL = 0x00000080, ///< All packets sent by installed protocols and all packets indicated by the NIC that is identified by a given NdisBindingHandle. + RNDIS_PACKET_TYPE_GROUP = 0x00001000, ///< Packets sent to the current group address. + RNDIS_PACKET_TYPE_ALL_FUNCTIONAL = 0x00002000, ///< All functional address packets, not just the ones in the current functional address. + RNDIS_PACKET_TYPE_FUNCTIONAL = 0x00004000, ///< Functional address packets sent to addresses included in the current functional address. + RNDIS_PACKET_TYPE_MAC_FRAME = 0x00008000, ///< NIC driver frames that a Token Ring NIC receives. + RNDIS_PACKET_TYPE_NO_LOCAL = 0x00010000, +} rndis_packet_filter_type_t; + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CDC_RNDIS_H_ */ + +/** @} */ +/** @} */ diff --git a/src/class/cdc/cdc_rndis_host.c b/src/class/cdc/cdc_rndis_host.c new file mode 100644 index 000000000..ae61bf8b5 --- /dev/null +++ b/src/class/cdc/cdc_rndis_host.c @@ -0,0 +1,293 @@ +/**************************************************************************/ +/*! + @file cdc_rndis_host.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (TUSB_OPT_HOST_ENABLED && CFG_TUH_CDC && CFG_TUH_CDC_RNDIS) + +#define _TINY_USB_SOURCE_FILE_ + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "cdc_host.h" +#include "cdc_rndis_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +#define RNDIS_MSG_PAYLOAD_MAX (1024*4) + +CFG_TUSB_MEM_SECTION static uint8_t msg_notification[CFG_TUSB_HOST_DEVICE_MAX][8]; +CFG_TUSB_MEM_SECTION ATTR_ALIGNED(4) static uint8_t msg_payload[RNDIS_MSG_PAYLOAD_MAX]; + +STATIC_VAR rndish_data_t rndish_data[CFG_TUSB_HOST_DEVICE_MAX]; + +// TODO Microsoft requires message length for any get command must be at least 4096 bytes + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +static tusb_error_t rndis_body_subtask(void); +static tusb_error_t send_message_get_response_subtask( uint8_t dev_addr, cdch_data_t *p_cdc, + uint8_t * p_mess, uint32_t mess_length, + uint8_t *p_response ); + +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ +tusb_error_t tusbh_cdc_rndis_get_mac_addr(uint8_t dev_addr, uint8_t mac_address[6]) +{ + TU_ASSERT( tusbh_cdc_rndis_is_mounted(dev_addr), TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED); + TU_VERIFY( mac_address, TUSB_ERROR_INVALID_PARA); + + memcpy(mac_address, rndish_data[dev_addr-1].mac_address, 6); + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// IMPLEMENTATION +//--------------------------------------------------------------------+ + +// To enable the TASK_ASSERT style (quick return on false condition) in a real RTOS, a task must act as a wrapper +// and is used mainly to call subtasks. Within a subtask return statement can be called freely, the task with +// forever loop cannot have any return at all. +OSAL_TASK_FUNCTION(cdch_rndis_task) (void* param;) +{ + OSAL_TASK_BEGIN + rndis_body_subtask(); + OSAL_TASK_END +} + +static tusb_error_t rndis_body_subtask(void) +{ + static uint8_t relative_addr; + + OSAL_SUBTASK_BEGIN + + for (relative_addr = 0; relative_addr < CFG_TUSB_HOST_DEVICE_MAX; relative_addr++) + { + + } + + osal_task_delay(100); + + OSAL_SUBTASK_END +} + +//--------------------------------------------------------------------+ +// RNDIS-CDC Driver API +//--------------------------------------------------------------------+ +void rndish_init(void) +{ + tu_memclr(rndish_data, sizeof(rndish_data_t)*CFG_TUSB_HOST_DEVICE_MAX); + + //------------- Task creation -------------// + + //------------- semaphore creation for notificaiton pipe -------------// + for(uint8_t i=0; i<CFG_TUSB_HOST_DEVICE_MAX; i++) + { + rndish_data[i].sem_notification_hdl = osal_semaphore_create( OSAL_SEM_REF(rndish_data[i].semaphore_notification) ); + } +} + +void rndish_close(uint8_t dev_addr) +{ + osal_semaphore_reset( rndish_data[dev_addr-1].sem_notification_hdl ); +// tu_memclr(&rndish_data[dev_addr-1], sizeof(rndish_data_t)); TODO need to move semaphore & its handle out before memclr +} + + +static rndis_msg_initialize_t const msg_init = +{ + .type = RNDIS_MSG_INITIALIZE, + .length = sizeof(rndis_msg_initialize_t), + .request_id = 1, // TODO should use some magic number + .major_version = 1, + .minor_version = 0, + .max_xfer_size = 0x4000 // TODO mimic windows +}; + +static rndis_msg_query_t const msg_query_permanent_addr = +{ + .type = RNDIS_MSG_QUERY, + .length = sizeof(rndis_msg_query_t)+6, + .request_id = 1, + .oid = RNDIS_OID_802_3_PERMANENT_ADDRESS, + .buffer_length = 6, + .buffer_offset = 20, +}; + +static rndis_msg_set_t const msg_set_packet_filter = +{ + .type = RNDIS_MSG_SET, + .length = sizeof(rndis_msg_set_t)+4, + .request_id = 1, + .oid = RNDIS_OID_GEN_CURRENT_PACKET_FILTER, + .buffer_length = 4, + .buffer_offset = 20, +}; + +tusb_error_t rndish_open_subtask(uint8_t dev_addr, cdch_data_t *p_cdc) +{ + tusb_error_t error; + + OSAL_SUBTASK_BEGIN + + //------------- Message Initialize -------------// + memcpy(msg_payload, &msg_init, sizeof(rndis_msg_initialize_t)); + STASK_INVOKE( + send_message_get_response_subtask( dev_addr, p_cdc, + msg_payload, sizeof(rndis_msg_initialize_t), + msg_payload), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + // TODO currently not support multiple data packets per xfer + rndis_msg_initialize_cmplt_t * const p_init_cmpt = (rndis_msg_initialize_cmplt_t *) msg_payload; + STASK_ASSERT(p_init_cmpt->type == RNDIS_MSG_INITIALIZE_CMPLT && p_init_cmpt->status == RNDIS_STATUS_SUCCESS && + p_init_cmpt->max_packet_per_xfer == 1 && p_init_cmpt->max_xfer_size <= RNDIS_MSG_PAYLOAD_MAX); + rndish_data[dev_addr-1].max_xfer_size = p_init_cmpt->max_xfer_size; + + //------------- Message Query 802.3 Permanent Address -------------// + memcpy(msg_payload, &msg_query_permanent_addr, sizeof(rndis_msg_query_t)); + tu_memclr(msg_payload + sizeof(rndis_msg_query_t), 6); // 6 bytes for MAC address + + STASK_INVOKE( + send_message_get_response_subtask( dev_addr, p_cdc, + msg_payload, sizeof(rndis_msg_query_t) + 6, + msg_payload), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + rndis_msg_query_cmplt_t * const p_query_cmpt = (rndis_msg_query_cmplt_t *) msg_payload; + STASK_ASSERT(p_query_cmpt->type == RNDIS_MSG_QUERY_CMPLT && p_query_cmpt->status == RNDIS_STATUS_SUCCESS); + memcpy(rndish_data[dev_addr-1].mac_address, msg_payload + 8 + p_query_cmpt->buffer_offset, 6); + + //------------- Set OID_GEN_CURRENT_PACKET_FILTER to (DIRECTED | MULTICAST | BROADCAST) -------------// + memcpy(msg_payload, &msg_set_packet_filter, sizeof(rndis_msg_set_t)); + tu_memclr(msg_payload + sizeof(rndis_msg_set_t), 4); // 4 bytes for filter flags + ((rndis_msg_set_t*) msg_payload)->oid_buffer[0] = (RNDIS_PACKET_TYPE_DIRECTED | RNDIS_PACKET_TYPE_MULTICAST | RNDIS_PACKET_TYPE_BROADCAST); + + STASK_INVOKE( + send_message_get_response_subtask( dev_addr, p_cdc, + msg_payload, sizeof(rndis_msg_set_t) + 4, + msg_payload), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + rndis_msg_set_cmplt_t * const p_set_cmpt = (rndis_msg_set_cmplt_t *) msg_payload; + STASK_ASSERT(p_set_cmpt->type == RNDIS_MSG_SET_CMPLT && p_set_cmpt->status == RNDIS_STATUS_SUCCESS); + + tusbh_cdc_rndis_mounted_cb(dev_addr); + + OSAL_SUBTASK_END +} + +void rndish_xfer_isr(cdch_data_t *p_cdc, pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes) +{ + if ( pipehandle_is_equal(pipe_hdl, p_cdc->pipe_notification) ) + { + osal_semaphore_post( rndish_data[pipe_hdl.dev_addr-1].sem_notification_hdl ); + } +} + +//--------------------------------------------------------------------+ +// INTERNAL & HELPER +//--------------------------------------------------------------------+ +static tusb_error_t send_message_get_response_subtask( uint8_t dev_addr, cdch_data_t *p_cdc, + uint8_t * p_mess, uint32_t mess_length, + uint8_t *p_response) +{ + tusb_error_t error; + + OSAL_SUBTASK_BEGIN + + //------------- Send RNDIS Control Message -------------// + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_OUT, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), + CDC_REQUEST_SEND_ENCAPSULATED_COMMAND, 0, p_cdc->interface_number, + mess_length, p_mess), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + //------------- waiting for Response Available notification -------------// + (void) hcd_pipe_xfer(p_cdc->pipe_notification, msg_notification[dev_addr-1], 8, true); + osal_semaphore_wait(rndish_data[dev_addr-1].sem_notification_hdl, OSAL_TIMEOUT_NORMAL, &error); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + STASK_ASSERT(msg_notification[dev_addr-1][0] == 1); + + //------------- Get RNDIS Message Initialize Complete -------------// + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE), + CDC_REQUEST_GET_ENCAPSULATED_RESPONSE, 0, p_cdc->interface_number, + RNDIS_MSG_PAYLOAD_MAX, p_response), + error + ); + if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error); + + OSAL_SUBTASK_END +} + +//static tusb_error_t send_process_msg_initialize_subtask(uint8_t dev_addr, cdch_data_t *p_cdc) +//{ +// tusb_error_t error; +// +// OSAL_SUBTASK_BEGIN +// +// *((rndis_msg_initialize_t*) msg_payload) = (rndis_msg_initialize_t) +// { +// .type = RNDIS_MSG_INITIALIZE, +// .length = sizeof(rndis_msg_initialize_t), +// .request_id = 1, // TODO should use some magic number +// .major_version = 1, +// .minor_version = 0, +// .max_xfer_size = 0x4000 // TODO mimic windows +// }; +// +// +// +// OSAL_SUBTASK_END +//} +#endif diff --git a/src/class/cdc/cdc_rndis_host.h b/src/class/cdc/cdc_rndis_host.h new file mode 100644 index 000000000..3b92d3f23 --- /dev/null +++ b/src/class/cdc/cdc_rndis_host.h @@ -0,0 +1,79 @@ +/**************************************************************************/ +/*! + @file cdc_rndis_host.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup CDC_RNDIS + * \defgroup CDC_RNSID_Host Host + * @{ */ + +#ifndef _TUSB_CDC_RNDIS_HOST_H_ +#define _TUSB_CDC_RNDIS_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" +#include "cdc_rndis.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// RNDIS-CDC Driver API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +typedef struct { + OSAL_SEM_DEF(semaphore_notification); + osal_semaphore_handle_t sem_notification_hdl; // used to wait on notification pipe + uint32_t max_xfer_size; // got from device's msg initialize complete + uint8_t mac_address[6]; +}rndish_data_t; + +void rndish_init(void); +tusb_error_t rndish_open_subtask(uint8_t dev_addr, cdch_data_t *p_cdc) ATTR_WARN_UNUSED_RESULT; +void rndish_xfer_isr(cdch_data_t *p_cdc, pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes); +void rndish_close(uint8_t dev_addr); + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CDC_RNDIS_HOST_H_ */ + +/** @} */ diff --git a/src/class/custom/custom_device.c b/src/class/custom/custom_device.c new file mode 100644 index 000000000..129d405a4 --- /dev/null +++ b/src/class/custom/custom_device.c @@ -0,0 +1,107 @@ +/**************************************************************************/ +/*! + @file custom_device.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_CUSTOM_CLASS) + +#define _TINY_USB_SOURCE_FILE_ + +#include "common/tusb_common.h" +#include "custom_device.h" +#include "device/usbd_pvt.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ + +/*------------------------------------------------------------------*/ +/* VARIABLE DECLARATION + *------------------------------------------------------------------*/ +typedef struct { + uint8_t itf_num; + + uint8_t ep_in; + uint8_t ep_out; + +} cusd_interface_t; + +static cusd_interface_t _cusd_itf; + +/*------------------------------------------------------------------*/ +/* FUNCTION DECLARATION + *------------------------------------------------------------------*/ +void cusd_init(void) +{ + tu_varclr(&_cusd_itf); +} + +bool cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, uint16_t *p_len) +{ + cusd_interface_t* p_itf = &_cusd_itf; + + // Open endpoint pair with usbd helper + tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(p_desc_itf); + TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_itf->ep_out, &p_itf->ep_in) ); + + p_itf->itf_num = p_desc_itf->bInterfaceNumber; + + (*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + + // TODO Prepare for incoming data +// TU_ASSERT( dcd_edpt_xfer(rhport, p_itf->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); + + return true; +} + +bool cusd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) +{ + return false; +} + +bool cusd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) +{ + return true; +} + +void cusd_reset(uint8_t rhport) +{ + +} + +#endif diff --git a/src/class/custom/custom_device.h b/src/class/custom/custom_device.h new file mode 100644 index 000000000..aae06d503 --- /dev/null +++ b/src/class/custom/custom_device.h @@ -0,0 +1,74 @@ +/**************************************************************************/ +/*! + @file custom_device.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#ifndef _TUSB_CUSTOM_DEVICE_H_ +#define _TUSB_CUSTOM_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" + +//--------------------------------------------------------------------+ +// APPLICATION API (Multiple Root Ports) +// Should be used only with MCU that support more than 1 ports +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// APPLICATION API (Single Port) +// Should be used with MCU supporting only 1 USB port for code simplicity +//--------------------------------------------------------------------+ + + +//--------------------------------------------------------------------+ +// APPLICATION CALLBACK API (WEAK is optional) +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// USBD-CLASS DRIVER API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +void cusd_init(void); +bool cusd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); +bool cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request); +bool cusd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request); +bool cusd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); +void cusd_reset(uint8_t rhport); +#endif + + +#endif /* _TUSB_CUSTOM_DEVICE_H_ */ diff --git a/src/class/custom/custom_host.c b/src/class/custom/custom_host.c new file mode 100644 index 000000000..894e641e8 --- /dev/null +++ b/src/class/custom/custom_host.c @@ -0,0 +1,160 @@ +/**************************************************************************/ +/*! + @file custom_host.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if (TUSB_OPT_HOST_ENABLED && CFG_TUSB_HOST_CUSTOM_CLASS) + +#define _TINY_USB_SOURCE_FILE_ + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "custom_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +custom_interface_info_t custom_interface[CFG_TUSB_HOST_DEVICE_MAX]; + +static tusb_error_t cush_validate_paras(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length) +{ + if ( !tusbh_custom_is_mounted(dev_addr, vendor_id, product_id) ) + { + return TUSB_ERROR_DEVICE_NOT_READY; + } + + TU_ASSERT( p_buffer != NULL && length != 0, TUSB_ERROR_INVALID_PARA); + + return TUSB_ERROR_NONE; +} +//--------------------------------------------------------------------+ +// APPLICATION API (need to check parameters) +//--------------------------------------------------------------------+ +tusb_error_t tusbh_custom_read(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length) +{ + TU_ASSERT_ERR( cush_validate_paras(dev_addr, vendor_id, product_id, p_buffer, length) ); + + if ( !hcd_pipe_is_idle(custom_interface[dev_addr-1].pipe_in) ) + { + return TUSB_ERROR_INTERFACE_IS_BUSY; + } + + (void) hcd_pipe_xfer( custom_interface[dev_addr-1].pipe_in, p_buffer, length, true); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tusbh_custom_write(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void const * p_data, uint16_t length) +{ + TU_ASSERT_ERR( cush_validate_paras(dev_addr, vendor_id, product_id, p_data, length) ); + + if ( !hcd_pipe_is_idle(custom_interface[dev_addr-1].pipe_out) ) + { + return TUSB_ERROR_INTERFACE_IS_BUSY; + } + + (void) hcd_pipe_xfer( custom_interface[dev_addr-1].pipe_out, p_data, length, true); + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// USBH-CLASS API +//--------------------------------------------------------------------+ +void cush_init(void) +{ + tu_memclr(&custom_interface, sizeof(custom_interface_info_t) * CFG_TUSB_HOST_DEVICE_MAX); +} + +tusb_error_t cush_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) +{ + // FIXME quick hack to test lpc1k custom class with 2 bulk endpoints + uint8_t const *p_desc = (uint8_t const *) p_interface_desc; + p_desc = tu_desc_next(p_desc); + + //------------- Bulk Endpoints Descriptor -------------// + for(uint32_t i=0; i<2; i++) + { + tusb_desc_endpoint_t const *p_endpoint = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint->bDescriptorType, TUSB_ERROR_INVALID_PARA); + + pipe_handle_t * p_pipe_hdl = ( p_endpoint->bEndpointAddress & TUSB_DIR_IN_MASK ) ? + &custom_interface[dev_addr-1].pipe_in : &custom_interface[dev_addr-1].pipe_out; + *p_pipe_hdl = hcd_edpt_open(dev_addr, p_endpoint, TUSB_CLASS_VENDOR_SPECIFIC); + TU_ASSERT ( pipehandle_is_valid(*p_pipe_hdl), TUSB_ERROR_HCD_OPEN_PIPE_FAILED ); + + p_desc = tu_desc_next(p_desc); + } + + (*p_length) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + return TUSB_ERROR_NONE; +} + +void cush_isr(pipe_handle_t pipe_hdl, xfer_result_t event) +{ + +} + +void cush_close(uint8_t dev_addr) +{ + tusb_error_t err1, err2; + custom_interface_info_t * p_interface = &custom_interface[dev_addr-1]; + + // TODO re-consider to check pipe valid before calling pipe_close + if( pipehandle_is_valid( p_interface->pipe_in ) ) + { + err1 = hcd_pipe_close( p_interface->pipe_in ); + } + + if ( pipehandle_is_valid( p_interface->pipe_out ) ) + { + err2 = hcd_pipe_close( p_interface->pipe_out ); + } + + tu_memclr(p_interface, sizeof(custom_interface_info_t)); + + TU_ASSERT(err1 == TUSB_ERROR_NONE && err2 == TUSB_ERROR_NONE, (void) 0 ); +} + +#endif diff --git a/src/class/custom/custom_host.h b/src/class/custom/custom_host.h new file mode 100644 index 000000000..5f9c25dda --- /dev/null +++ b/src/class/custom/custom_host.h @@ -0,0 +1,87 @@ +/**************************************************************************/ +/*! + @file custom_host.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_class + * \defgroup Group_Custom Custom Class (not supported yet) + * @{ */ + +#ifndef _TUSB_CUSTOM_HOST_H_ +#define _TUSB_CUSTOM_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" + +#ifdef __cplusplus + extern "C" { +#endif + +typedef struct { + pipe_handle_t pipe_in; + pipe_handle_t pipe_out; +}custom_interface_info_t; + +//--------------------------------------------------------------------+ +// USBH-CLASS DRIVER API +//--------------------------------------------------------------------+ +static inline bool tusbh_custom_is_mounted(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id) +{ + (void) vendor_id; // TODO check this later + (void) product_id; +// return (tusbh_device_get_mounted_class_flag(dev_addr) & BIT_(TUSB_CLASS_MAPPED_INDEX_END-1) ) != 0; + return false; +} + +tusb_error_t tusbh_custom_read(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length); +tusb_error_t tusbh_custom_write(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void const * p_data, uint16_t length); + +#ifdef _TINY_USB_SOURCE_FILE_ + +void cush_init(void); +tusb_error_t cush_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) ATTR_WARN_UNUSED_RESULT; +void cush_isr(pipe_handle_t pipe_hdl, xfer_result_t event); +void cush_close(uint8_t dev_addr); + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CUSTOM_HOST_H_ */ + +/** @} */ diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h new file mode 100644 index 000000000..8bfede2da --- /dev/null +++ b/src/class/hid/hid.h @@ -0,0 +1,618 @@ +/**************************************************************************/
+/*!
+ @file hid.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_class
+ * \defgroup ClassDriver_HID Human Interface Device (HID)
+ * @{ */
+
+#ifndef _TUSB_HID_H_
+#define _TUSB_HID_H_
+
+#include "common/tusb_common.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Common Definitions
+//--------------------------------------------------------------------+
+/** \defgroup ClassDriver_HID_Common Common Definitions
+ * @{ */
+
+/// HID Subclass
+typedef enum
+{
+ HID_SUBCLASS_NONE = 0, ///< No Subclass
+ HID_SUBCLASS_BOOT = 1 ///< Boot Interface Subclass
+}hid_subclass_type_t;
+
+/// HID Protocol
+typedef enum
+{
+ HID_PROTOCOL_NONE = 0, ///< None
+ HID_PROTOCOL_KEYBOARD = 1, ///< Keyboard
+ HID_PROTOCOL_MOUSE = 2 ///< Mouse
+}hid_protocol_type_t;
+
+/// HID Descriptor Type
+typedef enum
+{
+ HID_DESC_TYPE_HID = 0x21, ///< HID Descriptor
+ HID_DESC_TYPE_REPORT = 0x22, ///< Report Descriptor
+ HID_DESC_TYPE_PHYSICAL = 0x23 ///< Physical Descriptor
+}hid_descriptor_type_t;
+
+/// HID Request Report Type
+typedef enum
+{
+ HID_REPORT_TYPE_INPUT = 1, ///< Input
+ HID_REPORT_TYPE_OUTPUT, ///< Output
+ HID_REPORT_TYPE_FEATURE ///< Feature
+}hid_report_type_t;
+
+/// HID Class Specific Control Request
+typedef enum
+{
+ HID_REQ_CONTROL_GET_REPORT = 0x01, ///< Get Report
+ HID_REQ_CONTROL_GET_IDLE = 0x02, ///< Get Idle
+ HID_REQ_CONTROL_GET_PROTOCOL = 0x03, ///< Get Protocol
+ HID_REQ_CONTROL_SET_REPORT = 0x09, ///< Set Report
+ HID_REQ_CONTROL_SET_IDLE = 0x0a, ///< Set Idle
+ HID_REQ_CONTROL_SET_PROTOCOL = 0x0b ///< Set Protocol
+}hid_request_type_t;
+
+/// USB HID Descriptor
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength; /**< Numeric expression that is the total size of the HID descriptor */
+ uint8_t bDescriptorType; /**< Constant name specifying type of HID descriptor. */
+
+ uint16_t bcdHID; /**< Numeric expression identifying the HID Class Specification release */
+ uint8_t bCountryCode; /**< Numeric expression identifying country code of the localized hardware. */
+ uint8_t bNumDescriptors; /**< Numeric expression specifying the number of class descriptors */
+
+ uint8_t bReportType; /**< Type of HID class report. */
+ uint16_t wReportLength; /**< the total size of the Report descriptor. */
+} tusb_hid_descriptor_hid_t;
+
+/// HID Country Code
+typedef enum
+{
+ HID_Local_NotSupported = 0 , ///< NotSupported
+ HID_Local_Arabic , ///< Arabic
+ HID_Local_Belgian , ///< Belgian
+ HID_Local_Canadian_Bilingual , ///< Canadian_Bilingual
+ HID_Local_Canadian_French , ///< Canadian_French
+ HID_Local_Czech_Republic , ///< Czech_Republic
+ HID_Local_Danish , ///< Danish
+ HID_Local_Finnish , ///< Finnish
+ HID_Local_French , ///< French
+ HID_Local_German , ///< German
+ HID_Local_Greek , ///< Greek
+ HID_Local_Hebrew , ///< Hebrew
+ HID_Local_Hungary , ///< Hungary
+ HID_Local_International , ///< International
+ HID_Local_Italian , ///< Italian
+ HID_Local_Japan_Katakana , ///< Japan_Katakana
+ HID_Local_Korean , ///< Korean
+ HID_Local_Latin_American , ///< Latin_American
+ HID_Local_Netherlands_Dutch , ///< Netherlands/Dutch
+ HID_Local_Norwegian , ///< Norwegian
+ HID_Local_Persian_Farsi , ///< Persian (Farsi)
+ HID_Local_Poland , ///< Poland
+ HID_Local_Portuguese , ///< Portuguese
+ HID_Local_Russia , ///< Russia
+ HID_Local_Slovakia , ///< Slovakia
+ HID_Local_Spanish , ///< Spanish
+ HID_Local_Swedish , ///< Swedish
+ HID_Local_Swiss_French , ///< Swiss/French
+ HID_Local_Swiss_German , ///< Swiss/German
+ HID_Local_Switzerland , ///< Switzerland
+ HID_Local_Taiwan , ///< Taiwan
+ HID_Local_Turkish_Q , ///< Turkish-Q
+ HID_Local_UK , ///< UK
+ HID_Local_US , ///< US
+ HID_Local_Yugoslavia , ///< Yugoslavia
+ HID_Local_Turkish_F ///< Turkish-F
+} hid_country_code_t;
+
+/** @} */
+
+//--------------------------------------------------------------------+
+// MOUSE
+//--------------------------------------------------------------------+
+/** \addtogroup ClassDriver_HID_Mouse Mouse
+ * @{ */
+
+/// Standard HID Boot Protocol Mouse Report.
+typedef struct ATTR_PACKED
+{
+ uint8_t buttons; /**< buttons mask for currently pressed buttons in the mouse. */
+ int8_t x; /**< Current delta x movement of the mouse. */
+ int8_t y; /**< Current delta y movement on the mouse. */
+ int8_t wheel; /**< Current delta wheel movement on the mouse. */
+// int8_t pan;
+} hid_mouse_report_t;
+
+/// Standard Mouse Buttons Bitmap
+typedef enum
+{
+ MOUSE_BUTTON_LEFT = BIT_(0), ///< Left button
+ MOUSE_BUTTON_RIGHT = BIT_(1), ///< Right button
+ MOUSE_BUTTON_MIDDLE = BIT_(2), ///< Middle button
+ MOUSE_BUTTON_BACKWARD = BIT_(3), ///< Backward button,
+ MOUSE_BUTTON_FORWARD = BIT_(4), ///< Forward button,
+}hid_mouse_button_bm_t;
+
+/// @}
+
+//--------------------------------------------------------------------+
+// Keyboard
+//--------------------------------------------------------------------+
+/** \addtogroup ClassDriver_HID_Keyboard Keyboard
+ * @{ */
+
+/// Standard HID Boot Protocol Keyboard Report.
+typedef struct ATTR_PACKED
+{
+ uint8_t modifier; /**< Keyboard modifier byte, indicating pressed modifier keys (a combination of HID_KEYBOARD_MODIFER_* masks). */
+ uint8_t reserved; /**< Reserved for OEM use, always set to 0. */
+ uint8_t keycode[6]; /**< Key codes of the currently pressed keys. */
+} hid_keyboard_report_t;
+
+/// Keyboard modifier codes bitmap
+typedef enum
+{
+ KEYBOARD_MODIFIER_LEFTCTRL = BIT_(0), ///< Left Control
+ KEYBOARD_MODIFIER_LEFTSHIFT = BIT_(1), ///< Left Shift
+ KEYBOARD_MODIFIER_LEFTALT = BIT_(2), ///< Left Alt
+ KEYBOARD_MODIFIER_LEFTGUI = BIT_(3), ///< Left Window
+ KEYBOARD_MODIFIER_RIGHTCTRL = BIT_(4), ///< Right Control
+ KEYBOARD_MODIFIER_RIGHTSHIFT = BIT_(5), ///< Right Shift
+ KEYBOARD_MODIFIER_RIGHTALT = BIT_(6), ///< Right Alt
+ KEYBOARD_MODIFIER_RIGHTGUI = BIT_(7) ///< Right Window
+}hid_keyboard_modifier_bm_t;
+
+typedef enum
+{
+ KEYBOARD_LED_NUMLOCK = BIT_(0), ///< Num Lock LED
+ KEYBOARD_LED_CAPSLOCK = BIT_(1), ///< Caps Lock LED
+ KEYBOARD_LED_SCROLLLOCK = BIT_(2), ///< Scroll Lock LED
+ KEYBOARD_LED_COMPOSE = BIT_(3), ///< Composition Mode
+ KEYBOARD_LED_KANA = BIT_(4) ///< Kana mode
+}hid_keyboard_led_bm_t;
+
+/// @}
+
+//--------------------------------------------------------------------+
+// HID KEYCODE
+//--------------------------------------------------------------------+
+#define HID_KEY_NONE 0x00
+#define HID_KEY_A 0x04
+#define HID_KEY_B 0x05
+#define HID_KEY_C 0x06
+#define HID_KEY_D 0x07
+#define HID_KEY_E 0x08
+#define HID_KEY_F 0x09
+#define HID_KEY_G 0x0A
+#define HID_KEY_H 0x0B
+#define HID_KEY_I 0x0C
+#define HID_KEY_J 0x0D
+#define HID_KEY_K 0x0E
+#define HID_KEY_L 0x0F
+#define HID_KEY_M 0x10
+#define HID_KEY_N 0x11
+#define HID_KEY_O 0x12
+#define HID_KEY_P 0x13
+#define HID_KEY_Q 0x14
+#define HID_KEY_R 0x15
+#define HID_KEY_S 0x16
+#define HID_KEY_T 0x17
+#define HID_KEY_U 0x18
+#define HID_KEY_V 0x19
+#define HID_KEY_W 0x1A
+#define HID_KEY_X 0x1B
+#define HID_KEY_Y 0x1C
+#define HID_KEY_Z 0x1D
+#define HID_KEY_1 0x1E
+#define HID_KEY_2 0x1F
+#define HID_KEY_3 0x20
+#define HID_KEY_4 0x21
+#define HID_KEY_5 0x22
+#define HID_KEY_6 0x23
+#define HID_KEY_7 0x24
+#define HID_KEY_8 0x25
+#define HID_KEY_9 0x26
+#define HID_KEY_0 0x27
+#define HID_KEY_RETURN 0x28
+#define HID_KEY_ESCAPE 0x29
+#define HID_KEY_BACKSPACE 0x2A
+#define HID_KEY_TAB 0x2B
+#define HID_KEY_SPACE 0x2C
+#define HID_KEY_MINUS 0x2D
+#define HID_KEY_EQUAL 0x2E
+#define HID_KEY_BRACKET_LEFT 0x2F
+#define HID_KEY_BRACKET_RIGHT 0x30
+#define HID_KEY_BACKSLASH 0x31
+#define HID_KEY_EUROPE_1 0x32
+#define HID_KEY_SEMICOLON 0x33
+#define HID_KEY_APOSTROPHE 0x34
+#define HID_KEY_GRAVE 0x35
+#define HID_KEY_COMMA 0x36
+#define HID_KEY_PERIOD 0x37
+#define HID_KEY_SLASH 0x38
+#define HID_KEY_CAPS_LOCK 0x39
+#define HID_KEY_F1 0x3A
+#define HID_KEY_F2 0x3B
+#define HID_KEY_F3 0x3C
+#define HID_KEY_F4 0x3D
+#define HID_KEY_F5 0x3E
+#define HID_KEY_F6 0x3F
+#define HID_KEY_F7 0x40
+#define HID_KEY_F8 0x41
+#define HID_KEY_F9 0x42
+#define HID_KEY_F10 0x43
+#define HID_KEY_F11 0x44
+#define HID_KEY_F12 0x45
+#define HID_KEY_PRINT_SCREEN 0x46
+#define HID_KEY_SCROLL_LOCK 0x47
+#define HID_KEY_PAUSE 0x48
+#define HID_KEY_INSERT 0x49
+#define HID_KEY_HOME 0x4A
+#define HID_KEY_PAGE_UP 0x4B
+#define HID_KEY_DELETE 0x4C
+#define HID_KEY_END 0x4D
+#define HID_KEY_PAGE_DOWN 0x4E
+#define HID_KEY_ARROW_RIGHT 0x4F
+#define HID_KEY_ARROW_LEFT 0x50
+#define HID_KEY_ARROW_DOWN 0x51
+#define HID_KEY_ARROW_UP 0x52
+#define HID_KEY_NUM_LOCK 0x53
+#define HID_KEY_KEYPAD_DIVIDE 0x54
+#define HID_KEY_KEYPAD_MULTIPLY 0x55
+#define HID_KEY_KEYPAD_SUBTRACT 0x56
+#define HID_KEY_KEYPAD_ADD 0x57
+#define HID_KEY_KEYPAD_ENTER 0x58
+#define HID_KEY_KEYPAD_1 0x59
+#define HID_KEY_KEYPAD_2 0x5A
+#define HID_KEY_KEYPAD_3 0x5B
+#define HID_KEY_KEYPAD_4 0x5C
+#define HID_KEY_KEYPAD_5 0x5D
+#define HID_KEY_KEYPAD_6 0x5E
+#define HID_KEY_KEYPAD_7 0x5F
+#define HID_KEY_KEYPAD_8 0x60
+#define HID_KEY_KEYPAD_9 0x61
+#define HID_KEY_KEYPAD_0 0x62
+#define HID_KEY_KEYPAD_DECIMAL 0x63
+#define HID_KEY_EUROPE_2 0x64
+#define HID_KEY_APPLICATION 0x65
+#define HID_KEY_POWER 0x66
+#define HID_KEY_KEYPAD_EQUAL 0x67
+#define HID_KEY_F13 0x68
+#define HID_KEY_F14 0x69
+#define HID_KEY_F15 0x6A
+#define HID_KEY_CONTROL_LEFT 0xE0
+#define HID_KEY_SHIFT_LEFT 0xE1
+#define HID_KEY_ALT_LEFT 0xE2
+#define HID_KEY_GUI_LEFT 0xE3
+#define HID_KEY_CONTROL_RIGHT 0xE4
+#define HID_KEY_SHIFT_RIGHT 0xE5
+#define HID_KEY_ALT_RIGHT 0xE6
+#define HID_KEY_GUI_RIGHT 0xE7
+
+
+//--------------------------------------------------------------------+
+// REPORT DESCRIPTOR
+//--------------------------------------------------------------------+
+//------------- ITEM & TAG -------------//
+#define HID_REPORT_DATA_0(data)
+#define HID_REPORT_DATA_1(data) , data
+#define HID_REPORT_DATA_2(data) , U16_TO_U8S_LE(data)
+#define HID_REPORT_DATA_3(data) , U32_TO_U8S_LE(data)
+
+#define HID_REPORT_ITEM(data, tag, type, size) \
+ (((tag) << 4) | ((type) << 2) | (size)) HID_REPORT_DATA_##size(data)
+
+#define RI_TYPE_MAIN 0
+#define RI_TYPE_GLOBAL 1
+#define RI_TYPE_LOCAL 2
+
+//------------- MAIN ITEMS 6.2.2.4 -------------//
+#define HID_INPUT(x) HID_REPORT_ITEM(x, 8, RI_TYPE_MAIN, 1)
+#define HID_OUTPUT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_MAIN, 1)
+#define HID_COLLECTION(x) HID_REPORT_ITEM(x, 10, RI_TYPE_MAIN, 1)
+#define HID_FEATURE(x) HID_REPORT_ITEM(x, 11, RI_TYPE_MAIN, 1)
+#define HID_COLLECTION_END HID_REPORT_ITEM(x, 12, RI_TYPE_MAIN, 0)
+
+//------------- INPUT, OUTPUT, FEATURE 6.2.2.5 -------------//
+#define HID_DATA (0<<0)
+#define HID_CONSTANT (1<<0)
+
+#define HID_ARRAY (0<<1)
+#define HID_VARIABLE (1<<1)
+
+#define HID_ABSOLUTE (0<<2)
+#define HID_RELATIVE (1<<2)
+
+#define HID_WRAP_NO (0<<3)
+#define HID_WRAP (1<<3)
+
+#define HID_LINEAR (0<<4)
+#define HID_NONLINEAR (1<<4)
+
+#define HID_PREFERRED_STATE (0<<5)
+#define HID_PREFERRED_NO (1<<5)
+
+#define HID_NO_NULL_POSITION (0<<6)
+#define HID_NULL_STATE (1<<6)
+
+#define HID_NON_VOLATILE (0<<7)
+#define HID_VOLATILE (1<<7)
+
+#define HID_BITFIELD (0<<8)
+#define HID_BUFFERED_BYTES (1<<8)
+
+//------------- COLLECTION ITEM 6.2.2.6 -------------//
+enum {
+ HID_COLLECTION_PHYSICAL = 0,
+ HID_COLLECTION_APPLICATION,
+ HID_COLLECTION_LOGICAL,
+ HID_COLLECTION_REPORT,
+ HID_COLLECTION_NAMED_ARRAY,
+ HID_COLLECTION_USAGE_SWITCH,
+ HID_COLLECTION_USAGE_MODIFIER
+};
+
+//------------- GLOBAL ITEMS 6.2.2.7 -------------//
+#define HID_USAGE_PAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, 1)
+#define HID_USAGE_PAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, n)
+
+#define HID_LOGICAL_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, 1)
+#define HID_LOGICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, n)
+
+#define HID_LOGICAL_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, 1)
+#define HID_LOGICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, n)
+
+#define HID_PHYSICAL_MIN(x) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, 1)
+#define HID_PHYSICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, n)
+
+#define HID_PHYSICAL_MAX(x) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, 1)
+#define HID_PHYSICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, n)
+
+#define HID_UNIT_EXPONENT(x) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, 1)
+#define HID_UNIT_EXPONENT_N(x, n) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, n)
+
+#define HID_UNIT(x) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, 1)
+#define HID_UNIT_N(x, n) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, n)
+
+#define HID_REPORT_SIZE(x) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, 1)
+#define HID_REPORT_SIZE_N(x, n) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, n)
+
+#define HID_REPORT_ID(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, 1)
+#define HID_REPORT_ID_N(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, n)
+
+#define HID_REPORT_COUNT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, 1)
+#define HID_REPORT_COUNT_N(x, n) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, n)
+
+#define HID_PUSH HID_REPORT_ITEM(x, 10, RI_TYPE_GLOBAL, 0)
+#define HID_POP HID_REPORT_ITEM(x, 11, RI_TYPE_GLOBAL, 0)
+
+//------------- LOCAL ITEMS 6.2.2.8 -------------//
+#define HID_USAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, 1)
+#define HID_USAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, n)
+
+#define HID_USAGE_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, 1)
+#define HID_USAGE_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, n)
+
+#define HID_USAGE_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, 1)
+#define HID_USAGE_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, n)
+
+//--------------------------------------------------------------------+
+// Usage Table
+//--------------------------------------------------------------------+
+
+/// HID Usage Table - Table 1: Usage Page Summary
+enum {
+ HID_USAGE_PAGE_DESKTOP = 0x01,
+ HID_USAGE_PAGE_SIMULATE = 0x02,
+ HID_USAGE_PAGE_VIRTUAL_REALITY = 0x03,
+ HID_USAGE_PAGE_SPORT = 0x04,
+ HID_USAGE_PAGE_GAME = 0x05,
+ HID_USAGE_PAGE_GENERIC_DEVICE = 0x06,
+ HID_USAGE_PAGE_KEYBOARD = 0x07,
+ HID_USAGE_PAGE_LED = 0x08,
+ HID_USAGE_PAGE_BUTTON = 0x09,
+ HID_USAGE_PAGE_ORDINAL = 0x0a,
+ HID_USAGE_PAGE_TELEPHONY = 0x0b,
+ HID_USAGE_PAGE_CONSUMER = 0x0c,
+ HID_USAGE_PAGE_DIGITIZER = 0x0d,
+ HID_USAGE_PAGE_PID = 0x0f,
+ HID_USAGE_PAGE_UNICODE = 0x10,
+ HID_USAGE_PAGE_ALPHA_DISPLAY = 0x14,
+ HID_USAGE_PAGE_MEDICAL = 0x40,
+ HID_USAGE_PAGE_MONITOR = 0x80, //0x80 - 0x83
+ HID_USAGE_PAGE_POWER = 0x84, // 0x084 - 0x87
+ HID_USAGE_PAGE_BARCODE_SCANNER = 0x8c,
+ HID_USAGE_PAGE_SCALE = 0x8d,
+ HID_USAGE_PAGE_MSR = 0x8e,
+ HID_USAGE_PAGE_CAMERA = 0x90,
+ HID_USAGE_PAGE_ARCADE = 0x91,
+ HID_USAGE_PAGE_VENDOR = 0xFFFF // 0xFF00 - 0xFFFF
+};
+
+/// HID Usage Table - Table 6: Generic Desktop Page
+enum {
+ HID_USAGE_DESKTOP_POINTER = 0x01,
+ HID_USAGE_DESKTOP_MOUSE = 0x02,
+ HID_USAGE_DESKTOP_JOYSTICK = 0x04,
+ HID_USAGE_DESKTOP_GAMEPAD = 0x05,
+ HID_USAGE_DESKTOP_KEYBOARD = 0x06,
+ HID_USAGE_DESKTOP_KEYPAD = 0x07,
+ HID_USAGE_DESKTOP_MULTI_AXIS_CONTROLLER = 0x08,
+ HID_USAGE_DESKTOP_TABLET_PC_SYSTEM = 0x09,
+ HID_USAGE_DESKTOP_X = 0x30,
+ HID_USAGE_DESKTOP_Y = 0x31,
+ HID_USAGE_DESKTOP_Z = 0x32,
+ HID_USAGE_DESKTOP_RX = 0x33,
+ HID_USAGE_DESKTOP_RY = 0x34,
+ HID_USAGE_DESKTOP_RZ = 0x35,
+ HID_USAGE_DESKTOP_SLIDER = 0x36,
+ HID_USAGE_DESKTOP_DIAL = 0x37,
+ HID_USAGE_DESKTOP_WHEEL = 0x38,
+ HID_USAGE_DESKTOP_HAT_SWITCH = 0x39,
+ HID_USAGE_DESKTOP_COUNTED_BUFFER = 0x3a,
+ HID_USAGE_DESKTOP_BYTE_COUNT = 0x3b,
+ HID_USAGE_DESKTOP_MOTION_WAKEUP = 0x3c,
+ HID_USAGE_DESKTOP_START = 0x3d,
+ HID_USAGE_DESKTOP_SELECT = 0x3e,
+ HID_USAGE_DESKTOP_VX = 0x40,
+ HID_USAGE_DESKTOP_VY = 0x41,
+ HID_USAGE_DESKTOP_VZ = 0x42,
+ HID_USAGE_DESKTOP_VBRX = 0x43,
+ HID_USAGE_DESKTOP_VBRY = 0x44,
+ HID_USAGE_DESKTOP_VBRZ = 0x45,
+ HID_USAGE_DESKTOP_VNO = 0x46,
+ HID_USAGE_DESKTOP_FEATURE_NOTIFICATION = 0x47,
+ HID_USAGE_DESKTOP_RESOLUTION_MULTIPLIER = 0x48,
+ HID_USAGE_DESKTOP_SYSTEM_CONTROL = 0x80,
+ HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN = 0x81,
+ HID_USAGE_DESKTOP_SYSTEM_SLEEP = 0x82,
+ HID_USAGE_DESKTOP_SYSTEM_WAKE_UP = 0x83,
+ HID_USAGE_DESKTOP_SYSTEM_CONTEXT_MENU = 0x84,
+ HID_USAGE_DESKTOP_SYSTEM_MAIN_MENU = 0x85,
+ HID_USAGE_DESKTOP_SYSTEM_APP_MENU = 0x86,
+ HID_USAGE_DESKTOP_SYSTEM_MENU_HELP = 0x87,
+ HID_USAGE_DESKTOP_SYSTEM_MENU_EXIT = 0x88,
+ HID_USAGE_DESKTOP_SYSTEM_MENU_SELECT = 0x89,
+ HID_USAGE_DESKTOP_SYSTEM_MENU_RIGHT = 0x8A,
+ HID_USAGE_DESKTOP_SYSTEM_MENU_LEFT = 0x8B,
+ HID_USAGE_DESKTOP_SYSTEM_MENU_UP = 0x8C,
+ HID_USAGE_DESKTOP_SYSTEM_MENU_DOWN = 0x8D,
+ HID_USAGE_DESKTOP_SYSTEM_COLD_RESTART = 0x8E,
+ HID_USAGE_DESKTOP_SYSTEM_WARM_RESTART = 0x8F,
+ HID_USAGE_DESKTOP_DPAD_UP = 0x90,
+ HID_USAGE_DESKTOP_DPAD_DOWN = 0x91,
+ HID_USAGE_DESKTOP_DPAD_RIGHT = 0x92,
+ HID_USAGE_DESKTOP_DPAD_LEFT = 0x93,
+ HID_USAGE_DESKTOP_SYSTEM_DOCK = 0xA0,
+ HID_USAGE_DESKTOP_SYSTEM_UNDOCK = 0xA1,
+ HID_USAGE_DESKTOP_SYSTEM_SETUP = 0xA2,
+ HID_USAGE_DESKTOP_SYSTEM_BREAK = 0xA3,
+ HID_USAGE_DESKTOP_SYSTEM_DEBUGGER_BREAK = 0xA4,
+ HID_USAGE_DESKTOP_APPLICATION_BREAK = 0xA5,
+ HID_USAGE_DESKTOP_APPLICATION_DEBUGGER_BREAK = 0xA6,
+ HID_USAGE_DESKTOP_SYSTEM_SPEAKER_MUTE = 0xA7,
+ HID_USAGE_DESKTOP_SYSTEM_HIBERNATE = 0xA8,
+ HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INVERT = 0xB0,
+ HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INTERNAL = 0xB1,
+ HID_USAGE_DESKTOP_SYSTEM_DISPLAY_EXTERNAL = 0xB2,
+ HID_USAGE_DESKTOP_SYSTEM_DISPLAY_BOTH = 0xB3,
+ HID_USAGE_DESKTOP_SYSTEM_DISPLAY_DUAL = 0xB4,
+ HID_USAGE_DESKTOP_SYSTEM_DISPLAY_TOGGLE_INT_EXT = 0xB5,
+ HID_USAGE_DESKTOP_SYSTEM_DISPLAY_SWAP_PRIMARY_SECONDARY = 0xB6,
+ HID_USAGE_DESKTOP_SYSTEM_DISPLAY_LCD_AUTOSCALE = 0xB7
+};
+
+
+/// HID Usage Table: Consumer Page (0x0C)
+/// Only contains controls that supported by Windows (whole list is too long)
+enum
+{
+ // Generic Control
+ HID_USAGE_CONSUMER_CONTROL = 0x0001,
+
+ // Power Control
+ HID_USAGE_CONSUMER_POWER = 0x0030,
+ HID_USAGE_CONSUMER_RESET = 0x0031,
+ HID_USAGE_CONSUMER_SLEEP = 0x0032,
+
+ // Screen Brightness
+ HID_USAGE_CONSUMER_BRIGHTNESS_INCREMENT = 0x006F,
+ HID_USAGE_CONSUMER_BRIGHTNESS_DECREMENT = 0x0070,
+
+ // These HID usages operate only on mobile systems (battery powered) and
+ // require Windows 8 (build 8302 or greater).
+ HID_USAGE_CONSUMER_WIRELESS_RADIO_CONTROLS = 0x000C,
+ HID_USAGE_CONSUMER_WIRELESS_RADIO_BUTTONS = 0x00C6,
+ HID_USAGE_CONSUMER_WIRELESS_RADIO_LED = 0x00C7,
+ HID_USAGE_CONSUMER_WIRELESS_RADIO_SLIDER_SWITCH = 0x00C8,
+
+ // Media Control
+ HID_USAGE_CONSUMER_PLAY_PAUSE = 0x00CD,
+ HID_USAGE_CONSUMER_SCAN_NEXT = 0x00B5,
+ HID_USAGE_CONSUMER_SCAN_PREVIOUS = 0x00B6,
+ HID_USAGE_CONSUMER_STOP = 0x00B7,
+ HID_USAGE_CONSUMER_VOLUME = 0x00E0,
+ HID_USAGE_CONSUMER_MUTE = 0x00E2,
+ HID_USAGE_CONSUMER_BASS = 0x00E3,
+ HID_USAGE_CONSUMER_TREBLE = 0x00E4,
+ HID_USAGE_CONSUMER_BASS_BOOST = 0x00E5,
+ HID_USAGE_CONSUMER_VOLUME_INCREMENT = 0x00E9,
+ HID_USAGE_CONSUMER_VOLUME_DECREMENT = 0x00EA,
+ HID_USAGE_CONSUMER_BASS_INCREMENT = 0x0152,
+ HID_USAGE_CONSUMER_BASS_DECREMENT = 0x0153,
+ HID_USAGE_CONSUMER_TREBLE_INCREMENT = 0x0154,
+ HID_USAGE_CONSUMER_TREBLE_DECREMENT = 0x0155,
+
+ // Application Launcher
+ HID_USAGE_CONSUMER_AL_CONSUMER_CONTROL_CONFIGURATION = 0x0183,
+ HID_USAGE_CONSUMER_AL_EMAIL_READER = 0x018A,
+ HID_USAGE_CONSUMER_AL_CALCULATOR = 0x0192,
+ HID_USAGE_CONSUMER_AL_LOCAL_BROWSER = 0x0194,
+
+ // Browser/Explorer Specific
+ HID_USAGE_CONSUMER_AC_SEARCH = 0x0221,
+ HID_USAGE_CONSUMER_AC_HOME = 0x0223,
+ HID_USAGE_CONSUMER_AC_BACK = 0x0224,
+ HID_USAGE_CONSUMER_AC_FORWARD = 0x0225,
+ HID_USAGE_CONSUMER_AC_STOP = 0x0226,
+ HID_USAGE_CONSUMER_AC_REFRESH = 0x0227,
+ HID_USAGE_CONSUMER_AC_BOOKMARKS = 0x022A,
+
+ // Mouse Horizontal scroll
+ HID_USAGE_CONSUMER_AC_PAN = 0x0238,
+};
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_HID_H__ */
+
+/// @}
diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c new file mode 100644 index 000000000..bd49c157a --- /dev/null +++ b/src/class/hid/hid_device.c @@ -0,0 +1,660 @@ +/**************************************************************************/
+/*!
+ @file hid_device.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_HID)
+
+#define _TINY_USB_SOURCE_FILE_
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "common/tusb_common.h"
+#include "hid_device.h"
+#include "device/usbd_pvt.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+
+// Max report len is keyboard's one with 8 byte + 1 byte report id
+#define REPORT_BUFSIZE 12
+
+
+#define ITF_IDX_BOOT_KBD 0
+#define ITF_IDX_BOOT_MSE ( ITF_IDX_BOOT_KBD + (CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT) )
+#define ITF_IDX_GENERIC ( ITF_IDX_BOOT_MSE + (CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT) )
+#define ITF_COUNT ( ITF_IDX_GENERIC + 1 )
+
+typedef struct
+{
+ uint8_t itf_num;
+ uint8_t ep_in;
+
+ uint8_t idle_rate; // in unit of 4 ms TODO removed
+ bool boot_protocol;
+
+ uint16_t desc_len;
+ uint8_t const * desc_report;
+
+ CFG_TUSB_MEM_ALIGN uint8_t report_buf[REPORT_BUFSIZE];
+
+ // callbacks
+ uint16_t (*get_report_cb) (uint8_t report_id, hid_report_type_t type, uint8_t* buffer, uint16_t reqlen);
+ void (*set_report_cb) (uint8_t report_id, hid_report_type_t type, uint8_t const* buffer, uint16_t bufsize);
+
+}hidd_interface_t;
+
+typedef struct
+{
+ uint8_t usage; // HID_USAGE_*
+ uint8_t idle_rate; // in unit of 4 ms
+
+ uint8_t report_id;
+ uint8_t report_len;
+
+ hidd_interface_t* itf;
+} hidd_report_t ;
+
+CFG_TUSB_MEM_SECTION static hidd_interface_t _hidd_itf[ITF_COUNT];
+
+
+#if CFG_TUD_HID_KEYBOARD
+static hidd_report_t _kbd_rpt;
+#endif
+
+#if CFG_TUD_HID_MOUSE
+static hidd_report_t _mse_rpt;
+#endif
+
+/*------------- Helpers -------------*/
+
+static inline hidd_interface_t* get_interface_by_itfnum(uint8_t itf_num)
+{
+ for (uint8_t i=0; i < ITF_COUNT; i++ )
+ {
+ if ( itf_num == _hidd_itf[i].itf_num ) return &_hidd_itf[i];
+ }
+
+ return NULL;
+}
+
+
+//--------------------------------------------------------------------+
+// HID GENERIC API
+//--------------------------------------------------------------------+
+bool tud_hid_generic_ready(void)
+{
+ return (_hidd_itf[ITF_IDX_GENERIC].ep_in != 0) && !dcd_edpt_busy(TUD_OPT_RHPORT, _hidd_itf[ITF_IDX_GENERIC].ep_in);
+}
+
+bool tud_hid_generic_report(uint8_t report_id, void const* report, uint8_t len)
+{
+ TU_VERIFY( tud_hid_generic_ready() && (len < REPORT_BUFSIZE) );
+
+ hidd_interface_t * p_hid = &_hidd_itf[ITF_IDX_GENERIC];
+
+ // If report id = 0, skip ID field
+ if (report_id)
+ {
+ p_hid->report_buf[0] = report_id;
+ memcpy(p_hid->report_buf+1, report, len);
+ }else
+ {
+ memcpy(p_hid->report_buf, report, len);
+ }
+
+ // TODO idle rate
+ return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, len + ( report_id ? 1 : 0) );
+}
+
+//--------------------------------------------------------------------+
+// KEYBOARD APPLICATION API
+//--------------------------------------------------------------------+
+#if CFG_TUD_HID_KEYBOARD
+bool tud_hid_keyboard_ready(void)
+{
+ return (_kbd_rpt.itf != NULL) && !dcd_edpt_busy(TUD_OPT_RHPORT, _kbd_rpt.itf->ep_in);
+}
+
+bool tud_hid_keyboard_is_boot_protocol(void)
+{
+ return (_kbd_rpt.itf != NULL) && _kbd_rpt.itf->boot_protocol;
+}
+
+static bool hidd_kbd_report(hid_keyboard_report_t const *p_report)
+{
+ TU_VERIFY( tud_hid_keyboard_ready() );
+
+ hidd_interface_t * p_hid = _kbd_rpt.itf;
+
+ // Idle Rate = 0 : only send report if there is changes, i.e skip duplication
+ // Idle Rate > 0 : skip duplication, but send at least 1 report every idle rate (in unit of 4 ms).
+ // If idle time is less than interrupt polling then use the polling.
+ static tu_timeout_t idle_tm = { 0, 0 };
+
+ if ( (_kbd_rpt.idle_rate == 0) || !tu_timeout_expired(&idle_tm) )
+ {
+ if ( 0 == memcmp(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t)) ) return true;
+ }
+
+ tu_timeout_set(&idle_tm, _kbd_rpt.idle_rate * 4);
+
+ memcpy(p_hid->report_buf, p_report, sizeof(hid_keyboard_report_t));
+ return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_keyboard_report_t));
+}
+
+bool tud_hid_keyboard_keycode(uint8_t modifier, uint8_t keycode[6])
+{
+ hid_keyboard_report_t report = { .modifier = modifier };
+
+ if ( keycode )
+ {
+ memcpy(report.keycode, keycode, 6);
+ }else
+ {
+ tu_memclr(report.keycode, 6);
+ }
+
+ return hidd_kbd_report(&report);
+}
+
+#if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP
+
+bool tud_hid_keyboard_key_press(char ch)
+{
+ uint8_t keycode[6] = { 0 };
+ uint8_t modifier = 0;
+
+ if ( HID_ASCII_TO_KEYCODE[(uint8_t)ch].shift ) modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
+ keycode[0] = HID_ASCII_TO_KEYCODE[(uint8_t)ch].keycode;
+
+ return tud_hid_keyboard_keycode(modifier, keycode);
+}
+
+bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms)
+{
+ // Send each key in string
+ char ch;
+ while( (ch = *str++) != 0 )
+ {
+ char lookahead = *str;
+
+ tud_hid_keyboard_key_press(ch);
+
+ // Blocking delay
+ tu_timeout_wait(interval_ms);
+
+ /* Only need to empty report if the next character is NULL or the same with
+ * the current one, else no need to send */
+ if ( lookahead == ch || lookahead == 0 )
+ {
+ tud_hid_keyboard_key_release();
+ tu_timeout_wait(interval_ms);
+ }
+ }
+
+ return true;
+}
+
+#endif // CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP
+
+#endif // CFG_TUD_HID_KEYBOARD
+
+//--------------------------------------------------------------------+
+// MOUSE APPLICATION API
+//--------------------------------------------------------------------+
+#if CFG_TUD_HID_MOUSE
+
+bool tud_hid_mouse_ready(void)
+{
+ return (_mse_rpt.itf != NULL) && !dcd_edpt_busy(TUD_OPT_RHPORT, _mse_rpt.itf->ep_in);
+}
+
+bool tud_hid_mouse_is_boot_protocol(void)
+{
+ return (_mse_rpt.itf != NULL) && _mse_rpt.itf->boot_protocol;
+}
+
+static bool hidd_mouse_report(hid_mouse_report_t const *p_report)
+{
+ TU_VERIFY( tud_hid_mouse_ready() );
+
+ hidd_interface_t * p_hid = _mse_rpt.itf;
+ memcpy(p_hid->report_buf, p_report, sizeof(hid_mouse_report_t));
+
+ return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, sizeof(hid_mouse_report_t));
+}
+
+bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan)
+{
+ hid_mouse_report_t report =
+ {
+ .buttons = buttons,
+ .x = x,
+ .y = y,
+ .wheel = scroll,
+// .pan = pan
+ };
+
+ return hidd_mouse_report( &report );
+}
+
+bool tud_hid_mouse_move(int8_t x, int8_t y)
+{
+ TU_VERIFY( tud_hid_mouse_ready() );
+
+ hidd_interface_t * p_hid = _mse_rpt.itf;
+ uint8_t prev_buttons = p_hid->report_buf[0];
+
+ return tud_hid_mouse_data(prev_buttons, x, y, 0, 0);
+}
+
+bool tud_hid_mouse_scroll(int8_t vertical, int8_t horizontal)
+{
+ TU_VERIFY( tud_hid_mouse_ready() );
+
+ hidd_interface_t * p_hid = _mse_rpt.itf;
+ uint8_t prev_buttons = p_hid->report_buf[0];
+
+ return tud_hid_mouse_data(prev_buttons, 0, 0, vertical, horizontal);
+}
+
+#endif // CFG_TUD_HID_MOUSE
+
+//--------------------------------------------------------------------+
+// USBD-CLASS API
+//--------------------------------------------------------------------+
+void hidd_init(void)
+{
+ hidd_reset(TUD_OPT_RHPORT);
+}
+
+void hidd_reset(uint8_t rhport)
+{
+ tu_memclr(_hidd_itf, sizeof(_hidd_itf));
+
+ #if CFG_TUD_HID_KEYBOARD
+ tu_varclr(&_kbd_rpt);
+ #endif
+
+ #if CFG_TUD_HID_MOUSE
+ tu_varclr(&_mse_rpt);
+ #endif
+}
+
+bool hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint16_t *p_len)
+{
+ uint8_t const *p_desc = (uint8_t const *) desc_itf;
+
+ // TODO support HID OUT Endpoint
+ TU_ASSERT(desc_itf->bNumEndpoints == 1);
+
+ //------------- HID descriptor -------------//
+ p_desc = tu_desc_next(p_desc);
+ tusb_hid_descriptor_hid_t const *desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc;
+ TU_ASSERT(HID_DESC_TYPE_HID == desc_hid->bDescriptorType);
+
+ //------------- Endpoint Descriptor -------------//
+ p_desc = tu_desc_next(p_desc);
+ tusb_desc_endpoint_t const *desc_edpt = (tusb_desc_endpoint_t const *) p_desc;
+ TU_ASSERT(TUSB_DESC_ENDPOINT == desc_edpt->bDescriptorType);
+
+ hidd_interface_t * p_hid = NULL;
+
+ /*------------- Boot protocol only keyboard & mouse -------------*/
+ if (desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT)
+ {
+ TU_ASSERT(desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD || desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE, ERR_TUD_INVALID_DESCRIPTOR);
+
+ #if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT
+ if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_KEYBOARD)
+ {
+ p_hid = &_hidd_itf[ITF_IDX_BOOT_KBD];
+ p_hid->desc_report = usbd_desc_set->hid_report.boot_keyboard;
+ p_hid->get_report_cb = tud_hid_keyboard_get_report_cb;
+ p_hid->set_report_cb = tud_hid_keyboard_set_report_cb;
+
+ hidd_report_t* report = &_kbd_rpt;
+ report->usage = HID_USAGE_DESKTOP_KEYBOARD;
+ report->report_id = 0;
+ report->report_len = 8;
+ report->itf = p_hid;
+ }
+ #endif
+
+ #if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT
+ if (desc_itf->bInterfaceProtocol == HID_PROTOCOL_MOUSE)
+ {
+ p_hid = &_hidd_itf[ITF_IDX_BOOT_MSE];
+ p_hid->desc_report = usbd_desc_set->hid_report.boot_mouse;
+ p_hid->get_report_cb = tud_hid_mouse_get_report_cb;
+ p_hid->set_report_cb = tud_hid_mouse_set_report_cb;
+
+ hidd_report_t* report = &_mse_rpt;
+ report->usage = HID_USAGE_DESKTOP_MOUSE;
+ report->report_id = 0;
+ report->report_len = 4;
+ report->itf = p_hid;
+ }
+ #endif
+
+ TU_ASSERT(p_hid);
+ p_hid->boot_protocol = true; // default mode is BOOT
+ }
+ /*------------- Generic (multiple report) -------------*/
+ else
+ {
+ // TODO parse report ID for keyboard, mouse
+ p_hid = &_hidd_itf[ITF_IDX_GENERIC];
+
+ p_hid->desc_report = usbd_desc_set->hid_report.generic;
+ p_hid->get_report_cb = tud_hid_generic_get_report_cb;
+ p_hid->set_report_cb = tud_hid_generic_set_report_cb;
+ }
+
+ TU_ASSERT(p_hid->desc_report);
+ TU_ASSERT(dcd_edpt_open(rhport, desc_edpt));
+
+ p_hid->itf_num = desc_itf->bInterfaceNumber;
+ p_hid->ep_in = desc_edpt->bEndpointAddress;
+ p_hid->desc_len = desc_hid->wReportLength;
+
+ *p_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + desc_itf->bNumEndpoints*sizeof(tusb_desc_endpoint_t);
+
+ return true;
+}
+
+// Handle class control request
+// return false to stall control endpoint (e.g unsupported request)
+bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
+{
+ hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex );
+ TU_ASSERT(p_hid);
+
+ if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD)
+ {
+ //------------- STD Request -------------//
+ uint8_t const desc_type = tu_u16_high(p_request->wValue);
+ uint8_t const desc_index = tu_u16_low (p_request->wValue);
+ (void) desc_index;
+
+ if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT)
+ {
+ usbd_control_xfer(rhport, p_request, (void *)p_hid->desc_report, p_hid->desc_len);
+ }else
+ {
+ return false; // stall unsupported request
+ }
+ }
+ else if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS)
+ {
+ //------------- Class Specific Request -------------//
+ switch( p_request->bRequest )
+ {
+ case HID_REQ_CONTROL_GET_REPORT:
+ {
+ // wValue = Report Type | Report ID
+ uint8_t const report_type = tu_u16_high(p_request->wValue);
+ uint8_t const report_id = tu_u16_low(p_request->wValue);
+
+ uint16_t xferlen;
+ if ( p_hid->get_report_cb )
+ {
+ xferlen = p_hid->get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength);
+ }else
+ {
+ // For boot Interface only: re-use report_buf -> report has no change
+ xferlen = p_request->wLength;
+ }
+
+ TU_ASSERT( xferlen > 0 );
+ usbd_control_xfer(rhport, p_request, p_hid->report_buf, xferlen);
+ }
+ break;
+
+ case HID_REQ_CONTROL_SET_REPORT:
+ usbd_control_xfer(rhport, p_request, p_hid->report_buf, p_request->wLength);
+ break;
+
+ case HID_REQ_CONTROL_SET_IDLE:
+ // TODO idle rate of report
+ p_hid->idle_rate = tu_u16_high(p_request->wValue);
+ usbd_control_status(rhport, p_request);
+ break;
+
+ case HID_REQ_CONTROL_GET_IDLE:
+ // TODO idle rate of report
+ usbd_control_xfer(rhport, p_request, &p_hid->idle_rate, 1);
+ break;
+
+ case HID_REQ_CONTROL_GET_PROTOCOL:
+ {
+ uint8_t protocol = 1-p_hid->boot_protocol; // 0 is Boot, 1 is Report protocol
+ usbd_control_xfer(rhport, p_request, &protocol, 1);
+ }
+ break;
+
+ case HID_REQ_CONTROL_SET_PROTOCOL:
+ p_hid->boot_protocol = 1 - p_request->wValue; // 0 is Boot, 1 is Report protocol
+ usbd_control_status(rhport, p_request);
+ break;
+
+ default: return false; // stall unsupported request
+ }
+ }else
+ {
+ return false; // stall unsupported request
+ }
+
+ return true;
+}
+
+// Invoked when class request DATA stage is finished.
+// return false to stall control endpoint (e.g Host send non-sense DATA)
+bool hidd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request)
+{
+ hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex );
+ TU_ASSERT(p_hid);
+
+ if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS &&
+ p_request->bRequest == HID_REQ_CONTROL_SET_REPORT)
+ {
+ // wValue = Report Type | Report ID
+ uint8_t const report_type = tu_u16_high(p_request->wValue);
+ uint8_t const report_id = tu_u16_low(p_request->wValue);
+
+ if ( p_hid->set_report_cb )
+ {
+ p_hid->set_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength);
+ }
+ }
+
+ return true;
+}
+
+bool hidd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
+{
+ // nothing to do
+ return true;
+}
+
+
+/*------------------------------------------------------------------*/
+/* Ascii to Keycode
+ *------------------------------------------------------------------*/
+#if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP
+
+const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128] =
+{
+ {0, 0 }, // 0x00 Null
+ {0, 0 }, // 0x01
+ {0, 0 }, // 0x02
+ {0, 0 }, // 0x03
+ {0, 0 }, // 0x04
+ {0, 0 }, // 0x05
+ {0, 0 }, // 0x06
+ {0, 0 }, // 0x07
+ {0, HID_KEY_BACKSPACE }, // 0x08 Backspace
+ {0, HID_KEY_TAB }, // 0x09 Horizontal Tab
+ {0, HID_KEY_RETURN }, // 0x0A Line Feed
+ {0, 0 }, // 0x0B
+ {0, 0 }, // 0x0C
+ {0, HID_KEY_RETURN }, // 0x0D Carriage return
+ {0, 0 }, // 0x0E
+ {0, 0 }, // 0x0F
+ {0, 0 }, // 0x10
+ {0, 0 }, // 0x11
+ {0, 0 }, // 0x12
+ {0, 0 }, // 0x13
+ {0, 0 }, // 0x14
+ {0, 0 }, // 0x15
+ {0, 0 }, // 0x16
+ {0, 0 }, // 0x17
+ {0, 0 }, // 0x18
+ {0, 0 }, // 0x19
+ {0, 0 }, // 0x1A
+ {0, HID_KEY_ESCAPE }, // 0x1B Escape
+ {0, 0 }, // 0x1C
+ {0, 0 }, // 0x1D
+ {0, 0 }, // 0x1E
+ {0, 0 }, // 0x1F
+
+ {0, HID_KEY_SPACE }, // 0x20
+ {1, HID_KEY_1 }, // 0x21 !
+ {1, HID_KEY_APOSTROPHE }, // 0x22 "
+ {1, HID_KEY_3 }, // 0x23 #
+ {1, HID_KEY_4 }, // 0x24 $
+ {1, HID_KEY_5 }, // 0x25 %
+ {1, HID_KEY_7 }, // 0x26 &
+ {0, HID_KEY_APOSTROPHE }, // 0x27 '
+ {1, HID_KEY_9 }, // 0x28 (
+ {1, HID_KEY_0 }, // 0x29 )
+ {1, HID_KEY_8 }, // 0x2A *
+ {1, HID_KEY_EQUAL }, // 0x2B +
+ {0, HID_KEY_COMMA }, // 0x2C ,
+ {0, HID_KEY_MINUS }, // 0x2D -
+ {0, HID_KEY_PERIOD }, // 0x2E .
+ {0, HID_KEY_SLASH }, // 0x2F /
+ {0, HID_KEY_0 }, // 0x30 0
+ {0, HID_KEY_1 }, // 0x31 1
+ {0, HID_KEY_2 }, // 0x32 2
+ {0, HID_KEY_3 }, // 0x33 3
+ {0, HID_KEY_4 }, // 0x34 4
+ {0, HID_KEY_5 }, // 0x35 5
+ {0, HID_KEY_6 }, // 0x36 6
+ {0, HID_KEY_7 }, // 0x37 7
+ {0, HID_KEY_8 }, // 0x38 8
+ {0, HID_KEY_9 }, // 0x39 9
+ {1, HID_KEY_SEMICOLON }, // 0x3A :
+ {0, HID_KEY_SEMICOLON }, // 0x3B ;
+ {1, HID_KEY_COMMA }, // 0x3C <
+ {0, HID_KEY_EQUAL }, // 0x3D =
+ {1, HID_KEY_PERIOD }, // 0x3E >
+ {1, HID_KEY_SLASH }, // 0x3F ?
+
+ {1, HID_KEY_2 }, // 0x40 @
+ {1, HID_KEY_A }, // 0x41 A
+ {1, HID_KEY_B }, // 0x42 B
+ {1, HID_KEY_C }, // 0x43 C
+ {1, HID_KEY_D }, // 0x44 D
+ {1, HID_KEY_E }, // 0x45 E
+ {1, HID_KEY_F }, // 0x46 F
+ {1, HID_KEY_G }, // 0x47 G
+ {1, HID_KEY_H }, // 0x48 H
+ {1, HID_KEY_I }, // 0x49 I
+ {1, HID_KEY_J }, // 0x4A J
+ {1, HID_KEY_K }, // 0x4B K
+ {1, HID_KEY_L }, // 0x4C L
+ {1, HID_KEY_M }, // 0x4D M
+ {1, HID_KEY_N }, // 0x4E N
+ {1, HID_KEY_O }, // 0x4F O
+ {1, HID_KEY_P }, // 0x50 P
+ {1, HID_KEY_Q }, // 0x51 Q
+ {1, HID_KEY_R }, // 0x52 R
+ {1, HID_KEY_S }, // 0x53 S
+ {1, HID_KEY_T }, // 0x55 T
+ {1, HID_KEY_U }, // 0x55 U
+ {1, HID_KEY_V }, // 0x56 V
+ {1, HID_KEY_W }, // 0x57 W
+ {1, HID_KEY_X }, // 0x58 X
+ {1, HID_KEY_Y }, // 0x59 Y
+ {1, HID_KEY_Z }, // 0x5A Z
+ {0, HID_KEY_BRACKET_LEFT }, // 0x5B [
+ {0, HID_KEY_BACKSLASH }, // 0x5C '\'
+ {0, HID_KEY_BRACKET_RIGHT }, // 0x5D ]
+ {1, HID_KEY_6 }, // 0x5E ^
+ {1, HID_KEY_MINUS }, // 0x5F _
+
+ {0, HID_KEY_GRAVE }, // 0x60 `
+ {0, HID_KEY_A }, // 0x61 a
+ {0, HID_KEY_B }, // 0x62 b
+ {0, HID_KEY_C }, // 0x63 c
+ {0, HID_KEY_D }, // 0x66 d
+ {0, HID_KEY_E }, // 0x65 e
+ {0, HID_KEY_F }, // 0x66 f
+ {0, HID_KEY_G }, // 0x67 g
+ {0, HID_KEY_H }, // 0x68 h
+ {0, HID_KEY_I }, // 0x69 i
+ {0, HID_KEY_J }, // 0x6A j
+ {0, HID_KEY_K }, // 0x6B k
+ {0, HID_KEY_L }, // 0x6C l
+ {0, HID_KEY_M }, // 0x6D m
+ {0, HID_KEY_N }, // 0x6E n
+ {0, HID_KEY_O }, // 0x6F o
+ {0, HID_KEY_P }, // 0x70 p
+ {0, HID_KEY_Q }, // 0x71 q
+ {0, HID_KEY_R }, // 0x72 r
+ {0, HID_KEY_S }, // 0x73 s
+ {0, HID_KEY_T }, // 0x75 t
+ {0, HID_KEY_U }, // 0x75 u
+ {0, HID_KEY_V }, // 0x76 v
+ {0, HID_KEY_W }, // 0x77 w
+ {0, HID_KEY_X }, // 0x78 x
+ {0, HID_KEY_Y }, // 0x79 y
+ {0, HID_KEY_Z }, // 0x7A z
+ {1, HID_KEY_BRACKET_LEFT }, // 0x7B {
+ {1, HID_KEY_BACKSLASH }, // 0x7C |
+ {1, HID_KEY_BRACKET_RIGHT }, // 0x7D }
+ {1, HID_KEY_GRAVE }, // 0x7E ~
+ {0, HID_KEY_DELETE } // 0x7F Delete
+};
+
+#endif
+
+#endif
diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h new file mode 100644 index 000000000..885f33443 --- /dev/null +++ b/src/class/hid/hid_device.h @@ -0,0 +1,393 @@ +/**************************************************************************/
+/*!
+ @file hid_device.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_HID_DEVICE_H_
+#define _TUSB_HID_DEVICE_H_
+
+#include "common/tusb_common.h"
+#include "device/usbd.h"
+#include "hid.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Class Driver Default Configure & Validation
+//--------------------------------------------------------------------+
+#ifndef CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP
+#define CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP 0
+#endif
+
+#if !CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT
+#error CFG_TUD_HID_KEYBOARD must be enabled
+#endif
+
+#if !CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT
+#error CFG_TUD_HID_MOUSE must be enabled
+#endif
+
+
+//--------------------------------------------------------------------+
+// HID GENERIC API
+//--------------------------------------------------------------------+
+bool tud_hid_generic_ready(void);
+bool tud_hid_generic_report(uint8_t report_id, void const* report, uint8_t len);
+
+/*------------- Callbacks (Weak is optional) -------------*/
+uint16_t tud_hid_generic_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen);
+void tud_hid_generic_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize);
+
+//--------------------------------------------------------------------+
+// KEYBOARD API
+//--------------------------------------------------------------------+
+#if CFG_TUD_HID_KEYBOARD
+/** \addtogroup ClassDriver_HID_Keyboard Keyboard
+ * @{ */
+/** \defgroup Keyboard_Device Device
+ * @{ */
+
+/** Check if the interface is ready to use
+ * \returns true if ready, otherwise interface may not be mounted or still busy transferring data
+ * \note Application must not perform any action if the interface is not ready
+ */
+bool tud_hid_keyboard_ready(void);
+bool tud_hid_keyboard_is_boot_protocol(void);
+
+bool tud_hid_keyboard_keycode(uint8_t modifier, uint8_t keycode[6]);
+
+static inline bool tud_hid_keyboard_key_release(void) { return tud_hid_keyboard_keycode(0, NULL); }
+
+#if CFG_TUD_HID_ASCII_TO_KEYCODE_LOOKUP
+bool tud_hid_keyboard_key_press(char ch);
+bool tud_hid_keyboard_key_sequence(const char* str, uint32_t interval_ms);
+
+typedef struct{
+ uint8_t shift;
+ uint8_t keycode;
+}hid_ascii_to_keycode_entry_t;
+extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128];
+#endif
+
+#endif
+
+/*------------- Callbacks (Weak is optional) -------------*/
+
+/** Callback invoked when USB host request \ref HID_REQ_CONTROL_GET_REPORT.
+ * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests
+ * \param[out] buffer data that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \param[in] reqlen number of bytes that host requested
+ * \retval non-zero Actual number of bytes in the response's buffer.
+ * \retval zero indicates the current request is not supported. Tinyusb device stack will reject the request by
+ * sending STALL in the data phase.
+ * \note After this callback, the request is silently executed by the tinyusb stack, thus
+ * the completion of this control request will not be reported to application.
+ * For Keyboard, USB host often uses this to turn on/off the LED for CAPLOCKS, NUMLOCK (\ref hid_keyboard_led_bm_t)
+ */
+ATTR_WEAK uint16_t tud_hid_keyboard_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen);
+
+/** Callback invoked when USB host request \ref HID_REQ_CONTROL_SET_REPORT.
+ * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests
+ * \param[in] buffer containing the report's data
+ * \param[in] bufsize number of bytes in the \a buffer
+ * \note By the time this callback is invoked, the USB control transfer is already completed in the hardware side.
+ * Application are free to handle data at its own will.
+ */
+ATTR_WEAK void tud_hid_keyboard_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize);
+
+
+//ATTR_WEAK void tud_hid_keyboard_set_protocol_cb(bool boot_protocol);
+
+/** @} */
+/** @} */
+
+//--------------------------------------------------------------------+
+// MOUSE API
+//--------------------------------------------------------------------+
+#if CFG_TUD_HID_MOUSE
+/** \addtogroup ClassDriver_HID_Mouse Mouse
+ * @{ */
+/** \defgroup Mouse_Device Device
+ * @{ */
+
+/** \brief Check if the interface is currently busy or not
+ * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to host
+ * \retval false if the interface is not busy meaning the stack successfully transferred data from/to host
+ * \note This function is primarily used for polling/waiting result after \ref tusbd_hid_mouse_send.
+ */
+bool tud_hid_mouse_ready(void);
+bool tud_hid_mouse_is_boot_protocol(void);
+
+bool tud_hid_mouse_data(uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan);
+
+bool tud_hid_mouse_move(int8_t x, int8_t y);
+bool tud_hid_mouse_scroll(int8_t vertical, int8_t horizontal);
+
+static inline bool tud_hid_mouse_button_press(uint8_t buttons)
+{
+ return tud_hid_mouse_data(buttons, 0, 0, 0, 0);
+}
+
+static inline bool tud_hid_mouse_button_release(void)
+{
+ return tud_hid_mouse_data(0, 0, 0, 0, 0);
+}
+
+/*------------- Callbacks (Weak is optional) -------------*/
+
+/**
+ * Callback function that is invoked when USB host request \ref HID_REQ_CONTROL_GET_REPORT.
+ * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests
+ * \param[out] buffer buffer that application need to update, value must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \param[in] reqlen number of bytes that host requested
+ * \retval non-zero Actual number of bytes in the response's buffer.
+ * \retval zero indicates the current request is not supported. Tinyusb device stack will reject the request by
+ * sending STALL in the data phase.
+ * \note After this callback, the request is silently executed by the tinyusb stack, thus
+ * the completion of this control request will not be reported to application
+ */
+ATTR_WEAK uint16_t tud_hid_mouse_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen);
+
+/**
+ * Callback function that is invoked when USB host request \ref HID_REQ_CONTROL_SET_REPORT.
+ * \param[in] report_type specify which report (INPUT, OUTPUT, FEATURE) that host requests
+ * \param[in] buffer buffer containing the report's data
+ * \param[in] bufsize number of bytes in the \a p_report_data
+ * \note By the time this callback is invoked, the USB control transfer is already completed in the hardware side.
+ * Application are free to handle data at its own will.
+ */
+ATTR_WEAK void tud_hid_mouse_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize);
+
+//ATTR_WEAK void tud_hid_mouse_set_protocol_cb(bool boot_protocol);
+
+#endif
+
+
+//--------------------------------------------------------------------+
+// HID Report Descriptor Template
+//--------------------------------------------------------------------+
+/* These template should be used as follow
+ * - Only 1 report : no parameter
+ * uint8_t report_desc[] = { ID_REPORT_DESC_KEYBOARD() };
+ *
+ * - Multiple Reports: "HID_REPORT_ID(ID)," must be passed to template
+ * uint8_t report_desc[] = {
+ * ID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(1) ,) ,
+ * HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(2) ,)
+ * };
+ */
+
+/*------------- Keyboard Descriptor Template -------------*/
+#define HID_REPORT_DESC_KEYBOARD(...) \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\
+ HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
+ /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \
+ __VA_ARGS__ \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\
+ HID_USAGE_MIN ( 224 ) ,\
+ HID_USAGE_MAX ( 231 ) ,\
+ HID_LOGICAL_MIN ( 0 ) ,\
+ HID_LOGICAL_MAX ( 1 ) ,\
+ HID_REPORT_COUNT ( 8 ) ,\
+ HID_REPORT_SIZE ( 1 ) ,\
+ HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
+ /* 8 bit reserved */ \
+ 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 ( 255 ) ,\
+ HID_LOGICAL_MIN ( 0 ) ,\
+ HID_LOGICAL_MAX ( 255 ) ,\
+ 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 */ \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\
+ HID_USAGE_MIN ( 1 ) ,\
+ HID_USAGE_MAX ( 5 ) ,\
+ HID_REPORT_COUNT ( 5 ) ,\
+ HID_REPORT_SIZE ( 1 ) ,\
+ HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
+ /* led padding */ \
+ HID_REPORT_COUNT ( 1 ) ,\
+ HID_REPORT_SIZE ( 3 ) ,\
+ HID_OUTPUT ( HID_CONSTANT ) ,\
+ HID_COLLECTION_END \
+
+/*------------- Mouse Descriptor Template -------------*/
+#define HID_REPORT_DESC_MOUSE(...) \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\
+ HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
+ __VA_ARGS__ \
+ HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\
+ HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\
+ HID_USAGE_MIN ( 1 ) ,\
+ HID_USAGE_MAX ( 3 ) ,\
+ HID_LOGICAL_MIN ( 0 ) ,\
+ HID_LOGICAL_MAX ( 1 ) ,\
+ /* Left, Right, Middle, Backward, Forward mouse buttons */ \
+ HID_REPORT_COUNT ( 3 ) ,\
+ HID_REPORT_SIZE ( 1 ) ,\
+ HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
+ /* 3 bit padding */ \
+ HID_REPORT_COUNT ( 1 ) ,\
+ HID_REPORT_SIZE ( 5 ) ,\
+ HID_INPUT ( HID_CONSTANT ) ,\
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
+ /* X, Y position [-127, 127] */ \
+ HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\
+ HID_LOGICAL_MIN ( 0x81 ) ,\
+ HID_LOGICAL_MAX ( 0x7f ) ,\
+ HID_REPORT_COUNT ( 2 ) ,\
+ HID_REPORT_SIZE ( 8 ) ,\
+ HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\
+ /* Mouse scroll [-127, 127] */ \
+ HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\
+ HID_LOGICAL_MIN ( 0x81 ) ,\
+ HID_LOGICAL_MAX ( 0x7f ) ,\
+ HID_REPORT_COUNT( 1 ) ,\
+ HID_REPORT_SIZE ( 8 ) ,\
+ HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\
+ HID_COLLECTION_END ,\
+ HID_COLLECTION_END \
+
+//------------- Consumer Control Report Template -------------//
+#define HID_REPORT_DESC_CONSUMER(...) \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ) ,\
+ HID_USAGE ( HID_USAGE_CONSUMER_CONTROL ) ,\
+ HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
+ __VA_ARGS__ \
+ HID_LOGICAL_MIN ( 0x00 ) ,\
+ HID_LOGICAL_MAX_N( 0x03FF, 2 ) ,\
+ HID_USAGE_MIN ( 0x00 ) ,\
+ HID_USAGE_MAX_N ( 0x03FF, 2 ) ,\
+ HID_REPORT_COUNT ( 1 ) ,\
+ HID_REPORT_SIZE ( 16 ) ,\
+ HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
+ HID_COLLECTION_END \
+
+//------------- System Control Report Template -------------//
+/* 0x00 - do nothing
+ * 0x01 - Power Off
+ * 0x02 - Standby
+ * 0x04 - Wake Host
+ */
+#define HID_REPORT_DESC_SYSTEM_CONTROL(...) \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_CONTROL ) ,\
+ HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
+ __VA_ARGS__ \
+ /* 2 bit system power control */ \
+ HID_LOGICAL_MIN ( 1 ) ,\
+ HID_LOGICAL_MAX ( 3 ) ,\
+ HID_REPORT_COUNT ( 1 ) ,\
+ HID_REPORT_SIZE ( 2 ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_SLEEP ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_WAKE_UP ) ,\
+ HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
+ /* 6 bit padding */ \
+ HID_REPORT_COUNT ( 1 ) ,\
+ HID_REPORT_SIZE ( 6 ) ,\
+ HID_INPUT ( HID_CONSTANT ) ,\
+ HID_COLLECTION_END \
+
+//------------- Gamepad Report Template -------------//
+// Gamepad with 16 buttons and 2 joysticks
+// | Button Map (2 bytes) | X | Y | Z | Rz
+#define HID_REPORT_DESC_GAMEPAD(...) \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\
+ HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
+ __VA_ARGS__ \
+ /* 16 bit Button Map */ \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\
+ HID_USAGE_MIN ( 1 ) ,\
+ HID_USAGE_MAX ( 16 ) ,\
+ HID_LOGICAL_MIN ( 0 ) ,\
+ HID_LOGICAL_MAX ( 1 ) ,\
+ HID_REPORT_COUNT ( 16 ) ,\
+ HID_REPORT_SIZE ( 1 ) ,\
+ HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
+ /* X, Y, Z, Rz (min -127, max 127 ) */ \
+ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
+ HID_LOGICAL_MIN ( 0x81 ) ,\
+ HID_LOGICAL_MAX ( 0x7f ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_Z ) ,\
+ HID_USAGE ( HID_USAGE_DESKTOP_RZ ) ,\
+ HID_REPORT_COUNT ( 4 ) ,\
+ HID_REPORT_SIZE ( 8 ) ,\
+ HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
+ HID_COLLECTION_END \
+
+
+
+/** @} */
+/** @} */
+
+
+
+//--------------------------------------------------------------------+
+// INTERNAL API
+//--------------------------------------------------------------------+
+#ifdef _TINY_USB_SOURCE_FILE_
+
+void hidd_init(void);
+bool hidd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length);
+bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request);
+bool hidd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request);
+bool hidd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
+void hidd_reset(uint8_t rhport);
+
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_HID_DEVICE_H_ */
+
diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c new file mode 100644 index 000000000..1e44055ec --- /dev/null +++ b/src/class/hid/hid_host.c @@ -0,0 +1,305 @@ +/**************************************************************************/
+/*!
+ @file hid_host.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if (TUSB_OPT_HOST_ENABLED && HOST_CLASS_HID)
+
+#define _TINY_USB_SOURCE_FILE_
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "common/tusb_common.h"
+#include "hid_host.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+
+//--------------------------------------------------------------------+
+// HID Interface common functions
+//--------------------------------------------------------------------+
+static inline bool hidh_interface_open(uint8_t dev_addr, uint8_t interface_number, tusb_desc_endpoint_t const *p_endpoint_desc, hidh_interface_info_t *p_hid)
+{
+ p_hid->pipe_hdl = hcd_edpt_open(dev_addr, p_endpoint_desc, TUSB_CLASS_HID);
+ p_hid->report_size = p_endpoint_desc->wMaxPacketSize.size; // TODO get size from report descriptor
+ p_hid->interface_number = interface_number;
+
+ TU_ASSERT (pipehandle_is_valid(p_hid->pipe_hdl));
+
+ return true;
+}
+
+static inline void hidh_interface_close(hidh_interface_info_t *p_hid)
+{
+ tu_memclr(p_hid, sizeof(hidh_interface_info_t));
+}
+
+// called from public API need to validate parameters
+tusb_error_t hidh_interface_get_report(uint8_t dev_addr, void * report, hidh_interface_info_t *p_hid)
+{
+ //------------- parameters validation -------------//
+ // TODO change to use is configured function
+ TU_ASSERT (TUSB_DEVICE_STATE_CONFIGURED == tuh_device_get_state(dev_addr), TUSB_ERROR_DEVICE_NOT_READY);
+ TU_VERIFY (report, TUSB_ERROR_INVALID_PARA);
+ TU_ASSERT (!hcd_edpt_busy(p_hid->pipe_hdl), TUSB_ERROR_INTERFACE_IS_BUSY);
+
+ TU_ASSERT_ERR( hcd_pipe_xfer(p_hid->pipe_hdl, report, p_hid->report_size, true) ) ;
+
+ return TUSB_ERROR_NONE;
+}
+
+//--------------------------------------------------------------------+
+// KEYBOARD
+//--------------------------------------------------------------------+
+#if CFG_TUH_HID_KEYBOARD
+
+#if 0
+#define EXPAND_KEYCODE_TO_ASCII(keycode, ascii, shift_modified) \
+ [0][keycode] = ascii,\
+ [1][keycode] = shift_modified,\
+
+// TODO size of table should be a macro for application to check boundary
+uint8_t const hid_keycode_to_ascii_tbl[2][128] =
+{
+ HID_KEYCODE_TABLE(EXPAND_KEYCODE_TO_ASCII)
+};
+#endif
+
+static hidh_interface_info_t keyboardh_data[CFG_TUSB_HOST_DEVICE_MAX]; // does not have addr0, index = dev_address-1
+
+//------------- KEYBOARD PUBLIC API (parameter validation required) -------------//
+bool tuh_hid_keyboard_is_mounted(uint8_t dev_addr)
+{
+ return tuh_device_is_configured(dev_addr) && pipehandle_is_valid(keyboardh_data[dev_addr-1].pipe_hdl);
+}
+
+tusb_error_t tuh_hid_keyboard_get_report(uint8_t dev_addr, void* p_report)
+{
+ return hidh_interface_get_report(dev_addr, p_report, &keyboardh_data[dev_addr-1]);
+}
+
+bool tuh_hid_keyboard_is_busy(uint8_t dev_addr)
+{
+ return tuh_hid_keyboard_is_mounted(dev_addr) &&
+ hcd_edpt_busy( keyboardh_data[dev_addr-1].pipe_hdl );
+}
+
+#endif
+
+//--------------------------------------------------------------------+
+// MOUSE
+//--------------------------------------------------------------------+
+#if CFG_TUH_HID_MOUSE
+
+STATIC_VAR hidh_interface_info_t mouseh_data[CFG_TUSB_HOST_DEVICE_MAX]; // does not have addr0, index = dev_address-1
+
+//------------- Public API -------------//
+bool tuh_hid_mouse_is_mounted(uint8_t dev_addr)
+{
+ return tuh_device_is_configured(dev_addr) && pipehandle_is_valid(mouseh_data[dev_addr-1].pipe_hdl);
+}
+
+bool tuh_hid_mouse_is_busy(uint8_t dev_addr)
+{
+ return tuh_hid_mouse_is_mounted(dev_addr) &&
+ hcd_edpt_busy( mouseh_data[dev_addr-1].pipe_hdl );
+}
+
+tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void * report)
+{
+ return hidh_interface_get_report(dev_addr, report, &mouseh_data[dev_addr-1]);
+}
+
+#endif
+
+//--------------------------------------------------------------------+
+// GENERIC
+//--------------------------------------------------------------------+
+#if CFG_TUSB_HOST_HID_GENERIC
+
+//STATIC_ struct {
+// hidh_interface_info_t
+//} generic_data[CFG_TUSB_HOST_DEVICE_MAX];
+
+#endif
+
+//--------------------------------------------------------------------+
+// CLASS-USBH API (don't require to verify parameters)
+//--------------------------------------------------------------------+
+void hidh_init(void)
+{
+#if CFG_TUH_HID_KEYBOARD
+ tu_memclr(&keyboardh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX);
+#endif
+
+#if CFG_TUH_HID_MOUSE
+ tu_memclr(&mouseh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX);
+#endif
+
+#if CFG_TUSB_HOST_HID_GENERIC
+ hidh_generic_init();
+#endif
+}
+
+#if 0
+CFG_TUSB_MEM_SECTION uint8_t report_descriptor[256];
+#endif
+
+bool hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length)
+{
+ uint8_t const *p_desc = (uint8_t const *) p_interface_desc;
+
+ //------------- HID descriptor -------------//
+ p_desc += p_desc[DESC_OFFSET_LEN];
+ tusb_hid_descriptor_hid_t const *p_desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc;
+ TU_ASSERT(HID_DESC_TYPE_HID == p_desc_hid->bDescriptorType, TUSB_ERROR_INVALID_PARA);
+
+ //------------- Endpoint Descriptor -------------//
+ p_desc += p_desc[DESC_OFFSET_LEN];
+ tusb_desc_endpoint_t const * p_endpoint_desc = (tusb_desc_endpoint_t const *) p_desc;
+ TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint_desc->bDescriptorType, TUSB_ERROR_INVALID_PARA);
+
+ //------------- SET IDLE (0) request -------------//
+ tusb_control_request_t request = {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT },
+ .bRequest = HID_REQ_CONTROL_SET_IDLE,
+ .wValue = 0, // idle_rate = 0
+ .wIndex = p_interface_desc->bInterfaceNumber,
+ .wLength = 0
+ };
+ TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) );
+
+#if 0
+ //------------- Get Report Descriptor TODO HID parser -------------//
+ if ( p_desc_hid->bNumDescriptors )
+ {
+ STASK_INVOKE(
+ usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_STANDARD, TUSB_REQ_RCPT_INTERFACE),
+ TUSB_REQ_GET_DESCRIPTOR, (p_desc_hid->bReportType << 8), 0,
+ p_desc_hid->wReportLength, report_descriptor ),
+ error
+ );
+ (void) error; // if error in getting report descriptor --> treating like there is none
+ }
+#endif
+
+ if ( HID_SUBCLASS_BOOT == p_interface_desc->bInterfaceSubClass )
+ {
+ #if CFG_TUH_HID_KEYBOARD
+ if ( HID_PROTOCOL_KEYBOARD == p_interface_desc->bInterfaceProtocol)
+ {
+ TU_ASSERT( hidh_interface_open(dev_addr, p_interface_desc->bInterfaceNumber, p_endpoint_desc, &keyboardh_data[dev_addr-1]) );
+ tuh_hid_keyboard_mounted_cb(dev_addr);
+ } else
+ #endif
+
+ #if CFG_TUH_HID_MOUSE
+ if ( HID_PROTOCOL_MOUSE == p_interface_desc->bInterfaceProtocol)
+ {
+ TU_ASSERT ( hidh_interface_open(dev_addr, p_interface_desc->bInterfaceNumber, p_endpoint_desc, &mouseh_data[dev_addr-1]) );
+ tuh_hid_mouse_mounted_cb(dev_addr);
+ } else
+ #endif
+
+ {
+ // TUSB_ERROR_HIDH_NOT_SUPPORTED_PROTOCOL
+ return false;
+ }
+ }else
+ {
+ // TUSB_ERROR_HIDH_NOT_SUPPORTED_SUBCLASS
+ return false;
+ }
+
+ *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t);
+
+ return true;
+}
+
+void hidh_isr(pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes)
+{
+ (void) xferred_bytes; // TODO may need to use this para later
+
+#if CFG_TUH_HID_KEYBOARD
+ if ( pipehandle_is_equal(pipe_hdl, keyboardh_data[pipe_hdl.dev_addr-1].pipe_hdl) )
+ {
+ tuh_hid_keyboard_isr(pipe_hdl.dev_addr, event);
+ return;
+ }
+#endif
+
+#if CFG_TUH_HID_MOUSE
+ if ( pipehandle_is_equal(pipe_hdl, mouseh_data[pipe_hdl.dev_addr-1].pipe_hdl) )
+ {
+ tuh_hid_mouse_isr(pipe_hdl.dev_addr, event);
+ return;
+ }
+#endif
+
+#if CFG_TUSB_HOST_HID_GENERIC
+
+#endif
+}
+
+void hidh_close(uint8_t dev_addr)
+{
+#if CFG_TUH_HID_KEYBOARD
+ if ( pipehandle_is_valid( keyboardh_data[dev_addr-1].pipe_hdl ) )
+ {
+ hidh_interface_close(&keyboardh_data[dev_addr-1]);
+ tuh_hid_keyboard_unmounted_cb(dev_addr);
+ }
+#endif
+
+#if CFG_TUH_HID_MOUSE
+ if( pipehandle_is_valid( mouseh_data[dev_addr-1].pipe_hdl ) )
+ {
+ hidh_interface_close(&mouseh_data[dev_addr-1]);
+ tuh_hid_mouse_unmounted_cb( dev_addr );
+ }
+#endif
+
+#if CFG_TUSB_HOST_HID_GENERIC
+ hidh_generic_close(dev_addr);
+#endif
+}
+
+
+
+#endif
diff --git a/src/class/hid/hid_host.h b/src/class/hid/hid_host.h new file mode 100644 index 000000000..7336f5ada --- /dev/null +++ b/src/class/hid/hid_host.h @@ -0,0 +1,231 @@ +/**************************************************************************/
+/*!
+ @file hid_host.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \addtogroup ClassDriver_HID
+ * @{ */
+
+#ifndef _TUSB_HID_HOST_H_
+#define _TUSB_HID_HOST_H_
+
+#include "common/tusb_common.h"
+#include "host/usbh.h"
+#include "hid.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// KEYBOARD Application API
+//--------------------------------------------------------------------+
+/** \addtogroup ClassDriver_HID_Keyboard Keyboard
+ * @{ */
+
+/** \defgroup Keyboard_Host Host
+ * The interface API includes status checking function, data transferring function and callback functions
+ * @{ */
+
+extern uint8_t const hid_keycode_to_ascii_tbl[2][128]; // TODO used weak attr if build failed without KEYBOARD enabled
+
+/** \brief Check if device supports Keyboard interface or not
+ * \param[in] dev_addr device address
+ * \retval true if device supports Keyboard interface
+ * \retval false if device does not support Keyboard interface or is not mounted
+ */
+bool tuh_hid_keyboard_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT;
+
+/** \brief Check if the interface is currently busy or not
+ * \param[in] dev_addr device address
+ * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device
+ * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device
+ * \note This function is primarily used for polling/waiting result after \ref tuh_hid_keyboard_get_report.
+ * Alternatively, asynchronous event API can be used
+ */
+bool tuh_hid_keyboard_is_busy(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT;
+
+/** \brief Perform a get report from Keyboard interface
+ * \param[in] dev_addr device address
+ * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \returns \ref tusb_error_t type to indicate success or error condition.
+ * \retval TUSB_ERROR_NONE on success
+ * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
+ * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
+ * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
+ * \note This function is non-blocking and returns immediately. The result of usb transfer will be reported by the interface's callback function
+ */
+tusb_error_t tuh_hid_keyboard_get_report(uint8_t dev_addr, void * p_report) /*ATTR_WARN_UNUSED_RESULT*/;
+
+//------------- Application Callback -------------//
+/** \brief Callback function that is invoked when an transferring event occurred
+ * \param[in] dev_addr Address of device
+ * \param[in] event an value from \ref xfer_result_t
+ * \note event can be one of following
+ * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully.
+ * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error.
+ * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device.
+ * \note Application should schedule the next report by calling \ref tuh_hid_keyboard_get_report within this callback
+ */
+void tuh_hid_keyboard_isr(uint8_t dev_addr, xfer_result_t event);
+
+/** \brief Callback function that will be invoked when a device with Keyboard interface is mounted
+ * \param[in] dev_addr Address of newly mounted device
+ * \note This callback should be used by Application to set-up interface-related data
+ */
+void tuh_hid_keyboard_mounted_cb(uint8_t dev_addr);
+
+/** \brief Callback function that will be invoked when a device with Keyboard interface is unmounted
+ * \param[in] dev_addr Address of newly unmounted device
+ * \note This callback should be used by Application to tear-down interface-related data
+ */
+void tuh_hid_keyboard_unmounted_cb(uint8_t dev_addr);
+
+/** @} */ // Keyboard_Host
+/** @} */ // ClassDriver_HID_Keyboard
+
+//--------------------------------------------------------------------+
+// MOUSE Application API
+//--------------------------------------------------------------------+
+/** \addtogroup ClassDriver_HID_Mouse Mouse
+ * @{ */
+
+/** \defgroup Mouse_Host Host
+ * The interface API includes status checking function, data transferring function and callback functions
+ * @{ */
+
+/** \brief Check if device supports Mouse interface or not
+ * \param[in] dev_addr device address
+ * \retval true if device supports Mouse interface
+ * \retval false if device does not support Mouse interface or is not mounted
+ */
+bool tuh_hid_mouse_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT;
+
+/** \brief Check if the interface is currently busy or not
+ * \param[in] dev_addr device address
+ * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device
+ * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device
+ * \note This function is primarily used for polling/waiting result after \ref tuh_hid_mouse_get_report.
+ * Alternatively, asynchronous event API can be used
+ */
+bool tuh_hid_mouse_is_busy(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT;
+
+/** \brief Perform a get report from Mouse interface
+ * \param[in] dev_addr device address
+ * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \returns \ref tusb_error_t type to indicate success or error condition.
+ * \retval TUSB_ERROR_NONE on success
+ * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
+ * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
+ * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
+ * \note This function is non-blocking and returns immediately. The result of usb transfer will be reported by the interface's callback function
+ */
+tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void* p_report) /*ATTR_WARN_UNUSED_RESULT*/;
+
+//------------- Application Callback -------------//
+/** \brief Callback function that is invoked when an transferring event occurred
+ * \param[in] dev_addr Address of device
+ * \param[in] event an value from \ref xfer_result_t
+ * \note event can be one of following
+ * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully.
+ * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error.
+ * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device.
+ * \note Application should schedule the next report by calling \ref tuh_hid_mouse_get_report within this callback
+ */
+void tuh_hid_mouse_isr(uint8_t dev_addr, xfer_result_t event);
+
+/** \brief Callback function that will be invoked when a device with Mouse interface is mounted
+ * \param[in] dev_addr Address of newly mounted device
+ * \note This callback should be used by Application to set-up interface-related data
+ */
+void tuh_hid_mouse_mounted_cb(uint8_t dev_addr);
+
+/** \brief Callback function that will be invoked when a device with Mouse interface is unmounted
+ * \param[in] dev_addr Address of newly unmounted device
+ * \note This callback should be used by Application to tear-down interface-related data
+ */
+void tuh_hid_mouse_unmounted_cb(uint8_t dev_addr);
+
+/** @} */ // Mouse_Host
+/** @} */ // ClassDriver_HID_Mouse
+
+//--------------------------------------------------------------------+
+// GENERIC Application API
+//--------------------------------------------------------------------+
+/** \addtogroup ClassDriver_HID_Generic Generic (not supported yet)
+ * @{ */
+
+/** \defgroup Generic_Host Host
+ * The interface API includes status checking function, data transferring function and callback functions
+ * @{ */
+
+bool tuh_hid_generic_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT;
+tusb_error_t tuh_hid_generic_get_report(uint8_t dev_addr, void* p_report, bool int_on_complete) ATTR_WARN_UNUSED_RESULT;
+tusb_error_t tuh_hid_generic_set_report(uint8_t dev_addr, void* p_report, bool int_on_complete) ATTR_WARN_UNUSED_RESULT;
+tusb_interface_status_t tuh_hid_generic_get_status(uint8_t dev_addr) ATTR_WARN_UNUSED_RESULT;
+tusb_interface_status_t tuh_hid_generic_set_status(uint8_t dev_addr) ATTR_WARN_UNUSED_RESULT;
+
+//------------- Application Callback -------------//
+void tuh_hid_generic_isr(uint8_t dev_addr, xfer_result_t event);
+
+/** @} */ // Generic_Host
+/** @} */ // ClassDriver_HID_Generic
+
+//--------------------------------------------------------------------+
+// USBH-CLASS DRIVER API
+//--------------------------------------------------------------------+
+#ifdef _TINY_USB_SOURCE_FILE_
+
+typedef struct {
+ pipe_handle_t pipe_hdl;
+ uint16_t report_size;
+ uint8_t interface_number;
+}hidh_interface_info_t;
+
+void hidh_init(void);
+bool hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) ATTR_WARN_UNUSED_RESULT;
+void hidh_isr(pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes);
+void hidh_close(uint8_t dev_addr);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TUSB_HID_HOST_H_ */
+
+/** @} */ // ClassDriver_HID
diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h new file mode 100644 index 000000000..10a73bb1c --- /dev/null +++ b/src/class/msc/msc.h @@ -0,0 +1,402 @@ +/**************************************************************************/
+/*!
+ @file msc.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_class
+ * \defgroup ClassDriver_MSC MassStorage (MSC)
+ * @{ */
+
+/** \defgroup ClassDriver_MSC_Common Common Definitions
+ * @{ */
+
+#ifndef _TUSB_MSC_H_
+#define _TUSB_MSC_H_
+
+#include "common/tusb_common.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Mass Storage Class Constant
+//--------------------------------------------------------------------+
+/// MassStorage Subclass
+typedef enum
+{
+ MSC_SUBCLASS_RBC = 1 , ///< Reduced Block Commands (RBC) T10 Project 1240-D
+ MSC_SUBCLASS_SFF_MMC , ///< SFF-8020i, MMC-2 (ATAPI). Typically used by a CD/DVD device
+ MSC_SUBCLASS_QIC , ///< QIC-157. Typically used by a tape device
+ MSC_SUBCLASS_UFI , ///< UFI. Typically used by Floppy Disk Drive (FDD) device
+ MSC_SUBCLASS_SFF , ///< SFF-8070i. Can be used by Floppy Disk Drive (FDD) device
+ MSC_SUBCLASS_SCSI ///< SCSI transparent command set
+}msc_subclass_type_t;
+
+enum {
+ MSC_CBW_SIGNATURE = 0x43425355, ///< Constant value of 43425355h (little endian)
+ MSC_CSW_SIGNATURE = 0x53425355 ///< Constant value of 53425355h (little endian)
+};
+
+/// \brief MassStorage Protocol.
+/// \details CBI only approved to use with full-speed floopy disk & should not used with highspeed or device other than floopy
+typedef enum
+{
+ MSC_PROTOCOL_CBI = 0 , ///< Control/Bulk/Interrupt protocol (with command completion interrupt)
+ MSC_PROTOCOL_CBI_NO_INTERRUPT = 1 , ///< Control/Bulk/Interrupt protocol (without command completion interrupt)
+ MSC_PROTOCOL_BOT = 0x50 ///< Bulk-Only Transport
+}msc_protocol_type_t;
+
+/// MassStorage Class-Specific Control Request
+typedef enum
+{
+ MSC_REQ_GET_MAX_LUN = 254, ///< The Get Max LUN device request is used to determine the number of logical units supported by the device. Logical Unit Numbers on the device shall be numbered contiguously starting from LUN 0 to a maximum LUN of 15
+ MSC_REQ_RESET = 255 ///< This request is used to reset the mass storage device and its associated interface. This class-specific request shall ready the device for the next CBW from the host.
+}msc_request_type_t;
+
+/// \brief Command Block Status Values
+/// \details Indicates the success or failure of the command. The device shall set this byte to zero if the command completed
+/// successfully. A non-zero value shall indicate a failure during command execution according to the following
+typedef enum
+{
+ MSC_CSW_STATUS_PASSED = 0 , ///< MSC_CSW_STATUS_PASSED
+ MSC_CSW_STATUS_FAILED , ///< MSC_CSW_STATUS_FAILED
+ MSC_CSW_STATUS_PHASE_ERROR ///< MSC_CSW_STATUS_PHASE_ERROR
+}msc_csw_status_t;
+
+/// Command Block Wrapper
+typedef struct ATTR_PACKED
+{
+ uint32_t signature; ///< Signature that helps identify this data packet as a CBW. The signature field shall contain the value 43425355h (little endian), indicating a CBW.
+ uint32_t tag; ///< Tag sent by the host. The device shall echo the contents of this field back to the host in the dCSWTagfield of the associated CSW. The dCSWTagpositively associates a CSW with the corresponding CBW.
+ uint32_t total_bytes; ///< The number of bytes of data that the host expects to transfer on the Bulk-In or Bulk-Out endpoint (as indicated by the Direction bit) during the execution of this command. If this field is zero, the device and the host shall transfer no data between the CBW and the associated CSW, and the device shall ignore the value of the Direction bit in bmCBWFlags.
+ uint8_t dir; ///< Bit 7 of this field define transfer direction \n - 0 : Data-Out from host to the device. \n - 1 : Data-In from the device to the host.
+ uint8_t lun; ///< The device Logical Unit Number (LUN) to which the command block is being sent. For devices that support multiple LUNs, the host shall place into this field the LUN to which this command block is addressed. Otherwise, the host shall set this field to zero.
+ uint8_t cmd_len; ///< The valid length of the CBWCBin bytes. This defines the valid length of the command block. The only legal values are 1 through 16
+ uint8_t command[16]; ///< The command block to be executed by the device. The device shall interpret the first cmd_len bytes in this field as a command block
+}msc_cbw_t;
+
+TU_VERIFY_STATIC(sizeof(msc_cbw_t) == 31, "size is not correct");
+
+/// Command Status Wrapper
+typedef struct ATTR_PACKED
+{
+ uint32_t signature ; ///< Signature that helps identify this data packet as a CSW. The signature field shall contain the value 53425355h (little endian), indicating CSW.
+ uint32_t tag ; ///< The device shall set this field to the value received in the dCBWTag of the associated CBW.
+ uint32_t data_residue ; ///< For Data-Out the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLength, and the actual amount of data processed by the device. For Data-In the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLengthand the actual amount of relevant data sent by the device
+ uint8_t status ; ///< indicates the success or failure of the command. Values from \ref msc_csw_status_t
+}msc_csw_t;
+
+TU_VERIFY_STATIC(sizeof(msc_csw_t) == 13, "size is not correct");
+
+//--------------------------------------------------------------------+
+// SCSI Constant
+//--------------------------------------------------------------------+
+
+/// SCSI Command Operation Code
+typedef enum
+{
+ SCSI_CMD_TEST_UNIT_READY = 0x00, ///< The SCSI Test Unit Ready command is used to determine if a device is ready to transfer data (read/write), i.e. if a disk has spun up, if a tape is loaded and ready etc. The device does not perform a self-test operation.
+ SCSI_CMD_INQUIRY = 0x12, ///< The SCSI Inquiry command is used to obtain basic information from a target device.
+ SCSI_CMD_MODE_SELECT_6 = 0x15, ///< provides a means for the application client to specify medium, logical unit, or peripheral device parameters to the device server. Device servers that implement the MODE SELECT(6) command shall also implement the MODE SENSE(6) command. Application clients should issue MODE SENSE(6) prior to each MODE SELECT(6) to determine supported mode pages, page lengths, and other parameters.
+ SCSI_CMD_MODE_SENSE_6 = 0x1A, ///< provides a means for a device server to report parameters to an application client. It is a complementary command to the MODE SELECT(6) command. Device servers that implement the MODE SENSE(6) command shall also implement the MODE SELECT(6) command.
+ SCSI_CMD_START_STOP_UNIT = 0x1B,
+ SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E,
+ SCSI_CMD_READ_CAPACITY_10 = 0x25, ///< The SCSI Read Capacity command is used to obtain data capacity information from a target device.
+ SCSI_CMD_REQUEST_SENSE = 0x03, ///< The SCSI Request Sense command is part of the SCSI computer protocol standard. This command is used to obtain sense data -- status/error information -- from a target device.
+ SCSI_CMD_READ_FORMAT_CAPACITY = 0x23, ///< The command allows the Host to request a list of the possible format capacities for an installed writable media. This command also has the capability to report the writable capacity for a media when it is installed
+ SCSI_CMD_READ_10 = 0x28, ///< The READ (10) command requests that the device server read the specified logical block(s) and transfer them to the data-in buffer.
+ SCSI_CMD_WRITE_10 = 0x2A, ///< The WRITE (10) command requests thatthe device server transfer the specified logical block(s) from the data-out buffer and write them.
+}scsi_cmd_type_t;
+
+/// SCSI Sense Key
+typedef enum
+{
+ SCSI_SENSE_NONE = 0x00, ///< no specific Sense Key. This would be the case for a successful command
+ SCSI_SENSE_RECOVERED_ERROR = 0x01, ///< ndicates the last command completed successfully with some recovery action performed by the disc drive.
+ SCSI_SENSE_NOT_READY = 0x02, ///< Indicates the logical unit addressed cannot be accessed.
+ SCSI_SENSE_MEDIUM_ERROR = 0x03, ///< Indicates the command terminated with a non-recovered error condition.
+ SCSI_SENSE_HARDWARE_ERROR = 0x04, ///< Indicates the disc drive detected a nonrecoverable hardware failure while performing the command or during a self test.
+ SCSI_SENSE_ILLEGAL_REQUEST = 0x05, ///< Indicates an illegal parameter in the command descriptor block or in the additional parameters
+ SCSI_SENSE_UNIT_ATTENTION = 0x06, ///< Indicates the disc drive may have been reset.
+ SCSI_SENSE_DATA_PROTECT = 0x07, ///< Indicates that a command that reads or writes the medium was attempted on a block that is protected from this operation. The read or write operation is not performed.
+ SCSI_SENSE_FIRMWARE_ERROR = 0x08, ///< Vendor specific sense key.
+ SCSI_SENSE_ABORTED_COMMAND = 0x0b, ///< Indicates the disc drive aborted the command.
+ SCSI_SENSE_EQUAL = 0x0c, ///< Indicates a SEARCH DATA command has satisfied an equal comparison.
+ SCSI_SENSE_VOLUME_OVERFLOW = 0x0d, ///< Indicates a buffered peripheral device has reached the end of medium partition and data remains in the buffer that has not been written to the medium.
+ SCSI_SENSE_MISCOMPARE = 0x0e ///< ndicates that the source data did not match the data read from the medium.
+}scsi_sense_key_type_t;
+
+//--------------------------------------------------------------------+
+// SCSI Primary Command (SPC-4)
+//--------------------------------------------------------------------+
+
+/// SCSI Test Unit Ready Command
+typedef struct ATTR_PACKED
+{
+ uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_TEST_UNIT_READY
+ uint8_t lun ; ///< Logical Unit
+ uint8_t reserved[3] ;
+ uint8_t control ;
+} scsi_test_unit_ready_t;
+
+TU_VERIFY_STATIC(sizeof(scsi_test_unit_ready_t) == 6, "size is not correct");
+
+/// SCSI Inquiry Command
+typedef struct ATTR_PACKED
+{
+ uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_INQUIRY
+ uint8_t reserved1 ;
+ uint8_t page_code ;
+ uint8_t reserved2 ;
+ uint8_t alloc_length ; ///< specifies the maximum number of bytes that USB host has allocated in the Data-In Buffer. An allocation length of zero specifies that no data shall be transferred.
+ uint8_t control ;
+} scsi_inquiry_t, scsi_request_sense_t;
+
+TU_VERIFY_STATIC(sizeof(scsi_inquiry_t) == 6, "size is not correct");
+
+/// SCSI Inquiry Response Data
+typedef struct ATTR_PACKED
+{
+ uint8_t peripheral_device_type : 5;
+ uint8_t peripheral_qualifier : 3;
+
+ uint8_t : 7;
+ uint8_t is_removable : 1;
+
+ uint8_t version;
+
+ uint8_t response_data_format : 4;
+ uint8_t hierarchical_support : 1;
+ uint8_t normal_aca : 1;
+ uint8_t : 2;
+
+ uint8_t additional_length;
+
+ uint8_t protect : 1;
+ uint8_t : 2;
+ uint8_t third_party_copy : 1;
+ uint8_t target_port_group_support : 2;
+ uint8_t access_control_coordinator : 1;
+ uint8_t scc_support : 1;
+
+ uint8_t addr16 : 1;
+ uint8_t : 3;
+ uint8_t multi_port : 1;
+ uint8_t : 1; // vendor specific
+ uint8_t enclosure_service : 1;
+ uint8_t : 1;
+
+ uint8_t : 1; // vendor specific
+ uint8_t cmd_que : 1;
+ uint8_t : 2;
+ uint8_t sync : 1;
+ uint8_t wbus16 : 1;
+ uint8_t : 2;
+
+ uint8_t vendor_id[8] ; ///< 8 bytes of ASCII data identifying the vendor of the product.
+ uint8_t product_id[16]; ///< 16 bytes of ASCII data defined by the vendor.
+ uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor.
+} scsi_inquiry_resp_t;
+
+TU_VERIFY_STATIC(sizeof(scsi_inquiry_resp_t) == 36, "size is not correct");
+
+
+typedef struct ATTR_PACKED
+{
+ uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format
+ uint8_t valid : 1;
+
+ uint8_t reserved;
+
+ uint8_t sense_key : 4;
+ uint8_t : 1;
+ uint8_t ili : 1; ///< Incorrect length indicator
+ uint8_t end_of_medium : 1;
+ uint8_t filemark : 1;
+
+ uint32_t information;
+ uint8_t add_sense_len;
+ uint32_t command_specific_info;
+ uint8_t add_sense_code;
+ uint8_t add_sense_qualifier;
+ uint8_t field_replaceable_unit_code;
+
+ uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout
+
+} scsi_sense_fixed_resp_t;
+
+TU_VERIFY_STATIC(sizeof(scsi_sense_fixed_resp_t) == 18, "size is not correct");
+
+typedef struct ATTR_PACKED
+{
+ uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_MODE_SENSE_6
+
+ uint8_t : 3;
+ uint8_t disable_block_descriptor : 1;
+ uint8_t : 0;
+
+ uint8_t page_code : 6;
+ uint8_t page_control : 2;
+
+ uint8_t subpage_code;
+ uint8_t alloc_length;
+ uint8_t control;
+} scsi_mode_sense6_t;
+
+TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_t) == 6, "size is not correct");
+
+// This is only a Mode parameter header(6).
+typedef struct ATTR_PACKED
+{
+ uint8_t data_len;
+ uint8_t medium_type;
+ bool write_protected : 1;
+ uint8_t reserved : 7;
+ uint8_t block_descriptor_len;
+} scsi_mode_sense6_resp_t;
+
+TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_resp_t) == 4, "size is not correct");
+
+typedef struct ATTR_PACKED
+{
+ uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
+ uint8_t reserved[3];
+ uint8_t prohibit_removal;
+ uint8_t control;
+} scsi_prevent_allow_medium_removal_t;
+
+TU_VERIFY_STATIC( sizeof(scsi_prevent_allow_medium_removal_t) == 6, "size is not correct");
+
+typedef struct ATTR_PACKED
+{
+ uint8_t cmd_code;
+
+ uint8_t immded : 1;
+ uint8_t : 7;
+
+ uint8_t TU_RESERVED;
+
+ uint8_t power_condition_mod : 4;
+ uint8_t : 4;
+
+ uint8_t start : 1;
+ uint8_t load_eject : 1;
+ uint8_t no_flush : 1;
+ uint8_t : 1;
+ uint8_t power_condition : 4;
+
+ uint8_t control;
+} scsi_start_stop_unit_t;
+
+TU_VERIFY_STATIC( sizeof(scsi_start_stop_unit_t) == 6, "size is not correct");
+
+//--------------------------------------------------------------------+
+// SCSI MMC
+//--------------------------------------------------------------------+
+/// SCSI Read Format Capacity: Write Capacity
+typedef struct ATTR_PACKED
+{
+ uint8_t cmd_code;
+ uint8_t reserved[6];
+ uint16_t alloc_length;
+ uint8_t control;
+} scsi_read_format_capacity_t;
+
+TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_t) == 10, "size is not correct");
+
+typedef struct ATTR_PACKED{
+ uint8_t reserved[3];
+ uint8_t list_length; /// must be 8*n, length in bytes of formattable capacity descriptor followed it.
+
+ uint32_t block_num; /// Number of Logical Blocks
+ uint8_t descriptor_type; // 00: reserved, 01 unformatted media , 10 Formatted media, 11 No media present
+
+ uint8_t reserved2;
+ uint16_t block_size_u16;
+
+} scsi_read_format_capacity_data_t;
+
+TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_data_t) == 12, "size is not correct");
+
+//--------------------------------------------------------------------+
+// SCSI Block Command (SBC-3)
+// NOTE: All data in SCSI command are in Big Endian
+//--------------------------------------------------------------------+
+
+/// SCSI Read Capacity 10 Command: Read Capacity
+typedef struct ATTR_PACKED
+{
+ uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_READ_CAPACITY_10
+ uint8_t reserved1 ;
+ uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command
+ uint16_t reserved2 ;
+ uint8_t partial_medium_indicator ;
+ uint8_t control ;
+} scsi_read_capacity10_t;
+
+TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_t) == 10, "size is not correct");
+
+/// SCSI Read Capacity 10 Response Data
+typedef struct {
+ uint32_t last_lba ; ///< The last Logical Block Address of the device
+ uint32_t block_size ; ///< Block size in bytes
+} scsi_read_capacity10_resp_t;
+
+TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_resp_t) == 8, "size is not correct");
+
+/// SCSI Read 10 Command
+typedef struct ATTR_PACKED
+{
+ uint8_t cmd_code ; ///< SCSI OpCode
+ uint8_t reserved ; // has LUN according to wiki
+ uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command
+ uint8_t reserved2 ;
+ uint16_t block_count ; ///< Number of Blocks used by this command
+ uint8_t control ;
+} scsi_read10_t, scsi_write10_t;
+
+TU_VERIFY_STATIC(sizeof(scsi_read10_t) == 10, "size is not correct");
+TU_VERIFY_STATIC(sizeof(scsi_write10_t) == 10, "size is not correct");
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_MSC_H_ */
+
+/// @}
+/// @}
diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c new file mode 100644 index 000000000..d4d115bce --- /dev/null +++ b/src/class/msc/msc_device.c @@ -0,0 +1,605 @@ +/**************************************************************************/
+/*!
+ @file msc_device.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MSC)
+
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#define _TINY_USB_SOURCE_FILE_
+
+#include "common/tusb_common.h"
+#include "msc_device.h"
+#include "device/usbd_pvt.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+enum
+{
+ MSC_STAGE_CMD = 0,
+ MSC_STAGE_DATA,
+ MSC_STAGE_STATUS
+};
+
+typedef struct {
+ CFG_TUSB_MEM_ALIGN msc_cbw_t cbw;
+
+//#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13XX)
+// uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member
+//#endif
+
+ CFG_TUSB_MEM_ALIGN msc_csw_t csw;
+
+ uint8_t itf_num;
+ uint8_t ep_in;
+ uint8_t ep_out;
+
+ // Bulk Only Transfer (BOT) Protocol
+ uint8_t stage;
+ uint32_t total_len;
+ uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage
+
+ // Sense Response Data
+ uint8_t sense_key;
+ uint8_t add_sense_code;
+ uint8_t add_sense_qualifier;
+}mscd_interface_t;
+
+CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf;
+CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t _mscd_buf[CFG_TUD_MSC_BUFSIZE];
+
+//--------------------------------------------------------------------+
+// INTERNAL OBJECT & FUNCTION DECLARATION
+//--------------------------------------------------------------------+
+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 inline uint32_t rdwr10_get_lba(uint8_t const command[])
+{
+ // read10 & write10 has the same format
+ scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command;
+
+ // copy first to prevent mis-aligned access
+ uint32_t lba;
+ memcpy(&lba, &p_rdwr10->lba, 4);
+
+ return __be2n(lba);
+}
+
+static inline uint16_t rdwr10_get_blockcount(uint8_t const command[])
+{
+ // read10 & write10 has the same format
+ scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command;
+
+ // copy first to prevent mis-aligned access
+ uint16_t block_count;
+ memcpy(&block_count, &p_rdwr10->block_count, 2);
+
+ return __be2n_16(block_count);
+}
+
+//--------------------------------------------------------------------+
+// APPLICATION API
+//--------------------------------------------------------------------+
+bool tud_msc_ready(void)
+{
+ return ( _mscd_itf.ep_in != 0 ) && ( _mscd_itf.ep_out != 0 ) ;
+}
+
+bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier)
+{
+ (void) lun;
+
+ _mscd_itf.sense_key = sense_key;
+ _mscd_itf.add_sense_code = add_sense_code;
+ _mscd_itf.add_sense_qualifier = add_sense_qualifier;
+
+ return true;
+}
+
+
+//--------------------------------------------------------------------+
+// USBD-CLASS API
+//--------------------------------------------------------------------+
+void mscd_init(void)
+{
+ tu_memclr(&_mscd_itf, sizeof(mscd_interface_t));
+}
+
+void mscd_reset(uint8_t rhport)
+{
+ (void) rhport;
+ tu_memclr(&_mscd_itf, sizeof(mscd_interface_t));
+}
+
+bool mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_len)
+{
+ // only support SCSI's BOT protocol
+ TU_ASSERT(MSC_SUBCLASS_SCSI == itf_desc->bInterfaceSubClass &&
+ MSC_PROTOCOL_BOT == itf_desc->bInterfaceProtocol);
+
+ mscd_interface_t * p_msc = &_mscd_itf;
+
+ // Open endpoint pair with usbd helper
+ tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next( itf_desc );
+ TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_msc->ep_out, &p_msc->ep_in) );
+
+ p_msc->itf_num = itf_desc->bInterfaceNumber;
+ (*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t);
+
+ // Prepare for Command Block Wrapper
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) );
+
+ return true;
+}
+
+// Handle class control request
+// return false to stall control endpoint (e.g unsupported request)
+bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
+{
+ TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
+
+ switch ( p_request->bRequest )
+ {
+ case MSC_REQ_RESET:
+ // TODO: Actually reset interface.
+ usbd_control_status(rhport, p_request);
+ break;
+
+ case MSC_REQ_GET_MAX_LUN:
+ {
+ // returned MAX LUN is minus 1 by specs
+ uint8_t maxlun = CFG_TUD_MSC_MAXLUN-1;
+ usbd_control_xfer(rhport, p_request, &maxlun, 1);
+ }
+ break;
+
+ default: return false; // stall unsupported request
+ }
+
+ return true;
+}
+
+// Invoked when class request DATA stage is finished.
+// return false to stall control endpoint (e.g Host send non-sense DATA)
+bool mscd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request)
+{
+ (void) rhport;
+ (void) p_request;
+
+ // nothing to do
+ return true;
+}
+
+// return length of response (copied to buffer), -1 if it is not an built-in commands
+int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t bufsize)
+{
+ (void) bufsize; // TODO refractor later
+ int32_t ret;
+
+ switch ( p_cbw->command[0] )
+ {
+ case SCSI_CMD_READ_CAPACITY_10:
+ {
+ scsi_read_capacity10_resp_t read_capa10;
+
+ uint32_t block_count;
+ uint32_t block_size;
+ uint16_t block_size_u16;
+
+ tud_msc_capacity_cb(p_cbw->lun, &block_count, &block_size_u16);
+ block_size = (uint32_t) block_size_u16;
+
+ read_capa10.last_lba = ENDIAN_BE(block_count-1);
+ read_capa10.block_size = ENDIAN_BE(block_size);
+
+ ret = sizeof(read_capa10);
+ memcpy(buffer, &read_capa10, ret);
+ }
+ break;
+
+ case SCSI_CMD_READ_FORMAT_CAPACITY:
+ {
+ scsi_read_format_capacity_data_t read_fmt_capa =
+ {
+ .list_length = 8,
+ .block_num = 0,
+ .descriptor_type = 2, // formatted media
+ .block_size_u16 = 0
+ };
+
+ uint32_t block_count;
+ uint16_t block_size;
+
+ tud_msc_capacity_cb(p_cbw->lun, &block_count, &block_size);
+ read_fmt_capa.block_num = ENDIAN_BE(block_count);
+ read_fmt_capa.block_size_u16 = ENDIAN_BE16(block_size);
+
+ ret = sizeof(read_fmt_capa);
+ memcpy(buffer, &read_fmt_capa, ret);
+ }
+ break;
+
+ case SCSI_CMD_INQUIRY:
+ {
+ scsi_inquiry_resp_t inquiry_rsp =
+ {
+ .is_removable = 1,
+ .version = 2,
+ .response_data_format = 2,
+ .vendor_id = "Adafruit",
+ .product_id = "Feather52840",
+ .product_rev = "1.0"
+ };
+
+ strncpy((char*) inquiry_rsp.vendor_id , CFG_TUD_MSC_VENDOR , sizeof(inquiry_rsp.vendor_id));
+ strncpy((char*) inquiry_rsp.product_id , CFG_TUD_MSC_PRODUCT , sizeof(inquiry_rsp.product_id));
+ strncpy((char*) inquiry_rsp.product_rev, CFG_TUD_MSC_PRODUCT_REV, sizeof(inquiry_rsp.product_rev));
+
+ ret = sizeof(inquiry_rsp);
+ memcpy(buffer, &inquiry_rsp, ret);
+ }
+ break;
+
+ case SCSI_CMD_MODE_SENSE_6:
+ {
+ scsi_mode_sense6_resp_t mode_resp =
+ {
+ .data_len = 3,
+ .medium_type = 0,
+ .write_protected = false,
+ .reserved = 0,
+ .block_descriptor_len = 0 // no block descriptor are included
+ };
+
+ bool writable = true;
+ if (tud_msc_is_writable_cb) {
+ writable = tud_msc_is_writable_cb(p_cbw->lun);
+ }
+ mode_resp.write_protected = !writable;
+
+ ret = sizeof(mode_resp);
+ memcpy(buffer, &mode_resp, ret);
+ }
+ break;
+
+ case SCSI_CMD_REQUEST_SENSE:
+ {
+ scsi_sense_fixed_resp_t sense_rsp =
+ {
+ .response_code = 0x70,
+ .valid = 1
+ };
+
+ 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;
+
+ ret = sizeof(sense_rsp);
+ memcpy(buffer, &sense_rsp, ret);
+
+ // Clear sense data after copy
+ tud_msc_set_sense(p_cbw->lun, 0, 0, 0);
+ }
+ break;
+
+ default: ret = -1; break;
+ }
+
+ return ret;
+}
+
+bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
+{
+ mscd_interface_t* p_msc = &_mscd_itf;
+ msc_cbw_t const * p_cbw = &p_msc->cbw;
+ msc_csw_t * p_csw = &p_msc->csw;
+
+ switch (p_msc->stage)
+ {
+ case MSC_STAGE_CMD:
+ //------------- new CBW received -------------//
+ // 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 );
+
+ p_csw->signature = MSC_CSW_SIGNATURE;
+ p_csw->tag = p_cbw->tag;
+ p_csw->data_residue = 0;
+
+ /*------------- 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])
+ {
+ proc_read10_cmd(rhport, p_msc);
+ }
+ else if (SCSI_CMD_WRITE_10 == p_cbw->command[0])
+ {
+ proc_write10_cmd(rhport, p_msc);
+ }
+ else
+ {
+ // For other SCSI commands
+ // 1. Zero : Invoke app callback, skip DATA and move to STATUS stage
+ // 2. OUT : queue transfer (invoke app callback after done)
+ // 3. IN : invoke app callback to get response
+ if ( p_cbw->total_bytes == 0)
+ {
+ int32_t const cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, NULL, 0);
+
+ p_msc->total_len = 0;
+ p_msc->stage = MSC_STAGE_STATUS;
+
+ 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
+ }
+ else
+ {
+ p_csw->status = MSC_CSW_STATUS_PASSED;
+ }
+ }
+ else if ( !BIT_TEST_(p_cbw->dir, 7) )
+ {
+ // OUT transfer
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->total_len) );
+ }
+ else
+ {
+ // IN Transfer
+ int32_t cb_result;
+
+ // first process if it is a built-in commands
+ cb_result = proc_builtin_scsi(p_cbw, _mscd_buf, sizeof(_mscd_buf));
+
+ // Not an built-in command, invoke user callback
+ if ( cb_result < 0 )
+ {
+ cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len);
+ }
+
+ if ( cb_result > 0 )
+ {
+ p_msc->total_len = (uint32_t) cb_result;
+ p_csw->status = MSC_CSW_STATUS_PASSED;
+
+ TU_ASSERT( p_cbw->total_bytes >= p_msc->total_len ); // cannot return more than host expect
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->total_len) );
+ }else
+ {
+ p_msc->total_len = 0;
+ 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
+ dcd_edpt_stall(rhport, p_msc->ep_in);
+ }
+ }
+ }
+ break;
+
+ case MSC_STAGE_DATA:
+ // OUT transfer, invoke callback if needed
+ if ( !BIT_TEST_(p_cbw->dir, 7) )
+ {
+ if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] )
+ {
+ 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
+ }else
+ {
+ p_csw->status = MSC_CSW_STATUS_PASSED;
+ }
+ }
+ 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_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
+ TU_BREAKPOINT();
+ }
+ }
+ break;
+
+ case MSC_STAGE_STATUS: break; // processed immediately after this switch
+ default : break;
+ }
+
+ if ( p_msc->stage == MSC_STAGE_STATUS )
+ {
+ // Either endpoints is stalled, need to wait until it is cleared by host
+ if ( dcd_edpt_stalled(rhport, p_msc->ep_in) || dcd_edpt_stalled(rhport, p_msc->ep_out) )
+ {
+ // simulate an transfer complete with adjusted parameters --> this driver callback will fired again
+ dcd_event_xfer_complete(rhport, p_msc->ep_out, 0, XFER_RESULT_SUCCESS, false);
+ }
+ else
+ {
+ // Invoke complete callback if defined
+ if ( SCSI_CMD_READ_10 == p_cbw->command[0])
+ {
+ if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun);
+ }
+ else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] )
+ {
+ if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun);
+ }
+ else
+ {
+ if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command);
+ }
+
+ // Move to default CMD stage after sending status
+ p_msc->stage = MSC_STAGE_CMD;
+
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t)) );
+
+ //------------- Queue the next CBW -------------//
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) );
+ }
+ }
+
+ return true;
+}
+
+/*------------------------------------------------------------------*/
+/* SCSI Command Process
+ *------------------------------------------------------------------*/
+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_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);
+
+ // remaining bytes capped at class buffer
+ 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);
+
+ 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;
+
+ tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
+ dcd_edpt_stall(rhport, p_msc->ep_in);
+ }
+ else if ( nbytes == 0 )
+ {
+ // zero means not ready -> simulate an transfer complete so that this driver callback will fired again
+ dcd_event_xfer_complete(rhport, p_msc->ep_in, 0, XFER_RESULT_SUCCESS, false);
+ }
+ else
+ {
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, nbytes), );
+ }
+}
+
+static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc)
+{
+ msc_cbw_t const * p_cbw = &p_msc->cbw;
+
+ // remaining bytes capped at class buffer
+ int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len);
+
+ // Write10 callback will be called later when usb transfer complete
+ TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, nbytes), );
+}
+
+#endif
diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h new file mode 100644 index 000000000..c9e4139e9 --- /dev/null +++ b/src/class/msc/msc_device.h @@ -0,0 +1,186 @@ +/**************************************************************************/
+/*!
+ @file msc_device.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_MSC_DEVICE_H_
+#define _TUSB_MSC_DEVICE_H_
+
+#include "common/tusb_common.h"
+#include "device/usbd.h"
+#include "msc.h"
+
+
+//--------------------------------------------------------------------+
+// Class Driver Configuration
+//--------------------------------------------------------------------+
+TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct");
+
+#ifndef CFG_TUD_MSC_MAXLUN
+ #define CFG_TUD_MSC_MAXLUN 1
+#elif CFG_TUD_MSC_MAXLUN == 0 || CFG_TUD_MSC_MAXLUN > 16
+ #error MSC Device: Incorrect setting of MAX LUN
+#endif
+
+#ifndef CFG_TUD_MSC_BUFSIZE
+ #error CFG_TUD_MSC_BUFSIZE must be defined, value of CFG_TUD_MSC_BLOCK_SZ should work well, the more the better
+#endif
+
+#ifndef CFG_TUD_MSC_VENDOR
+ #error CFG_TUD_MSC_VENDOR 8-byte name must be defined
+#endif
+
+#ifndef CFG_TUD_MSC_PRODUCT
+ #error CFG_TUD_MSC_PRODUCT 16-byte name must be defined
+#endif
+
+#ifndef CFG_TUD_MSC_PRODUCT_REV
+ #error CFG_TUD_MSC_PRODUCT_REV 4-byte string must be defined
+#endif
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/** \addtogroup ClassDriver_MSC
+ * @{
+ * \defgroup MSC_Device Device
+ * @{ */
+
+
+// Check if MSC interface is ready to use
+bool tud_msc_ready(void);
+bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier);
+
+//--------------------------------------------------------------------+
+// APPLICATION CALLBACK (WEAK is optional)
+//--------------------------------------------------------------------+
+/**
+ * Callback invoked when received \ref SCSI_CMD_READ_10 command
+ * \param[in] lun Logical unit number
+ * \param[in] lba Logical Block Address to be read
+ * \param[in] offset Byte offset from LBA
+ * \param[out] buffer Buffer which application need to update with the response data.
+ * \param[in] bufsize Requested bytes
+ *
+ * \return Number of byte read, if it is less than requested bytes by \a \b bufsize. Tinyusb will transfer
+ * this amount first and invoked this again for remaining data.
+ *
+ * \retval zero Indicate application is not ready yet to response e.g disk I/O is not complete.
+ * tinyusb will invoke this callback with the same parameters again some time later.
+ *
+ * \retval negative Indicate error e.g reading disk I/O. tinyusb will \b STALL the corresponding
+ * endpoint and return failed status in command status wrapper phase.
+ */
+int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize);
+
+/**
+ * Callback invoked when received \ref SCSI_CMD_WRITE_10 command
+ * \param[in] lun Logical unit number
+ * \param[in] lba Logical Block Address to be write
+ * \param[in] offset Byte offset from LBA
+ * \param[out] buffer Buffer which holds written data.
+ * \param[in] bufsize Requested bytes
+ *
+ * \return Number of byte written, if it is less than requested bytes by \a \b bufsize. Tinyusb will proceed with
+ * other work and invoked this again with adjusted parameters.
+ *
+ * \retval zero Indicate application is not ready yet e.g disk I/O is not complete.
+ * Tinyusb will invoke this callback with the same parameters again some time later.
+ *
+ * \retval negative Indicate error writing disk I/O. Tinyusb will \b STALL the corresponding
+ * endpoint and return failed status in command status wrapper phase.
+ */
+int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize);
+
+// Invoked to determine the disk size
+void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size);
+
+/**
+ * Callback invoked when received an SCSI command not in built-in list below.
+ * \param[in] lun Logical unit number
+ * \param[in] scsi_cmd SCSI command contents which application must examine to response accordingly
+ * \param[out] buffer Buffer for SCSI Data Stage.
+ * - For INPUT: application must fill this with response.
+ * - For OUTPUT it holds the Data from host
+ * \param[in] bufsize Buffer's length.
+ *
+ * \return Actual bytes processed, can be zero for no-data command.
+ * \retval negative Indicate error e.g unsupported command, tinyusb will \b STALL the corresponding
+ * endpoint and return failed status in command status wrapper phase.
+ *
+ * \note Following command is automatically handled by tinyusb stack, callback should not be worried:
+ * - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, MODE_SENSE6, REQUEST_SENSE
+ * - READ10 and WRITE10 has their own callbacks
+ */
+int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize);
+
+/*------------- Optional callbacks : Could be used by application to free up resources -------------*/
+
+// Invoked when Read10 command is complete
+ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun);
+
+// Invoke when Write10 command is complete
+ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun);
+
+// Invoked when command in tud_msc_scsi_cb is complete
+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
+ATTR_WEAK bool tud_msc_is_writable_cb(uint8_t lun);
+
+/** @} */
+/** @} */
+
+//--------------------------------------------------------------------+
+// USBD-CLASS DRIVER API
+//--------------------------------------------------------------------+
+#ifdef _TINY_USB_SOURCE_FILE_
+
+void mscd_init(void);
+bool mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length);
+bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request);
+bool mscd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request);
+bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
+void mscd_reset(uint8_t rhport);
+
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_MSC_DEVICE_H_ */
diff --git a/src/class/msc/msc_host.c b/src/class/msc/msc_host.c new file mode 100644 index 000000000..86669b279 --- /dev/null +++ b/src/class/msc/msc_host.c @@ -0,0 +1,427 @@ +/**************************************************************************/
+/*!
+ @file msc_host.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if TUSB_OPT_HOST_ENABLED & CFG_TUH_MSC
+
+#define _TINY_USB_SOURCE_FILE_
+
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "common/tusb_common.h"
+#include "msc_host.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+CFG_TUSB_MEM_SECTION static msch_interface_t msch_data[CFG_TUSB_HOST_DEVICE_MAX];
+
+//------------- Initalization Data -------------//
+static osal_semaphore_def_t msch_sem_def;
+static osal_semaphore_t msch_sem_hdl;
+
+// buffer used to read scsi information when mounted, largest response data currently is inquiry
+CFG_TUSB_MEM_SECTION ATTR_ALIGNED(4) static uint8_t msch_buffer[sizeof(scsi_inquiry_resp_t)];
+
+//--------------------------------------------------------------------+
+// INTERNAL OBJECT & FUNCTION DECLARATION
+//--------------------------------------------------------------------+
+
+//--------------------------------------------------------------------+
+// PUBLIC API
+//--------------------------------------------------------------------+
+bool tuh_msc_is_mounted(uint8_t dev_addr)
+{
+ return tuh_device_is_configured(dev_addr) && // is configured can be omitted
+ msch_data[dev_addr-1].is_initialized;
+}
+
+bool tuh_msc_is_busy(uint8_t dev_addr)
+{
+ return msch_data[dev_addr-1].is_initialized &&
+ hcd_edpt_busy(dev_addr, msch_data[dev_addr-1].ep_in);
+}
+
+uint8_t const* tuh_msc_get_vendor_name(uint8_t dev_addr)
+{
+ return msch_data[dev_addr-1].is_initialized ? msch_data[dev_addr-1].vendor_id : NULL;
+}
+
+uint8_t const* tuh_msc_get_product_name(uint8_t dev_addr)
+{
+ return msch_data[dev_addr-1].is_initialized ? msch_data[dev_addr-1].product_id : NULL;
+}
+
+tusb_error_t tuh_msc_get_capacity(uint8_t dev_addr, uint32_t* p_last_lba, uint32_t* p_block_size)
+{
+ if ( !msch_data[dev_addr-1].is_initialized ) return TUSB_ERROR_MSCH_DEVICE_NOT_MOUNTED;
+ TU_ASSERT(p_last_lba != NULL && p_block_size != NULL, TUSB_ERROR_INVALID_PARA);
+
+ (*p_last_lba) = msch_data[dev_addr-1].last_lba;
+ (*p_block_size) = (uint32_t) msch_data[dev_addr-1].block_size;
+
+ return TUSB_ERROR_NONE;
+}
+
+//--------------------------------------------------------------------+
+// PUBLIC API: SCSI COMMAND
+//--------------------------------------------------------------------+
+static inline void msc_cbw_add_signature(msc_cbw_t *p_cbw, uint8_t lun)
+{
+ p_cbw->signature = MSC_CBW_SIGNATURE;
+ p_cbw->tag = 0xCAFECAFE;
+ p_cbw->lun = lun;
+}
+
+static tusb_error_t msch_command_xfer(uint8_t dev_addr, msch_interface_t * p_msch, void* p_buffer)
+{
+ if ( NULL != p_buffer)
+ { // there is data phase
+ if (p_msch->cbw.dir & TUSB_DIR_IN_MASK)
+ {
+ TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t), false), TUSB_ERROR_FAILED );
+ TU_ASSERT( hcd_pipe_queue_xfer(dev_addr, p_msch->ep_in , p_buffer, p_msch->cbw.total_bytes), TUSB_ERROR_FAILED );
+ }else
+ {
+ TU_ASSERT( hcd_pipe_queue_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t)), TUSB_ERROR_FAILED );
+ TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out , p_buffer, p_msch->cbw.total_bytes, false), TUSB_ERROR_FAILED );
+ }
+ }
+
+ TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_in , (uint8_t*) &p_msch->csw, sizeof(msc_csw_t), true), TUSB_ERROR_FAILED);
+
+ return TUSB_ERROR_NONE;
+}
+
+tusb_error_t tusbh_msc_inquiry(uint8_t dev_addr, uint8_t lun, uint8_t *p_data)
+{
+ msch_interface_t* p_msch = &msch_data[dev_addr-1];
+
+ //------------- Command Block Wrapper -------------//
+ msc_cbw_add_signature(&p_msch->cbw, lun);
+ p_msch->cbw.total_bytes = sizeof(scsi_inquiry_resp_t);
+ p_msch->cbw.dir = TUSB_DIR_IN_MASK;
+ p_msch->cbw.cmd_len = sizeof(scsi_inquiry_t);
+
+ //------------- SCSI command -------------//
+ scsi_inquiry_t cmd_inquiry =
+ {
+ .cmd_code = SCSI_CMD_INQUIRY,
+ .alloc_length = sizeof(scsi_inquiry_resp_t)
+ };
+
+ memcpy(p_msch->cbw.command, &cmd_inquiry, p_msch->cbw.cmd_len);
+
+ TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) );
+
+ return TUSB_ERROR_NONE;
+}
+
+tusb_error_t tusbh_msc_read_capacity10(uint8_t dev_addr, uint8_t lun, uint8_t *p_data)
+{
+ msch_interface_t* p_msch = &msch_data[dev_addr-1];
+
+ //------------- Command Block Wrapper -------------//
+ msc_cbw_add_signature(&p_msch->cbw, lun);
+ p_msch->cbw.total_bytes = sizeof(scsi_read_capacity10_resp_t);
+ p_msch->cbw.dir = TUSB_DIR_IN_MASK;
+ p_msch->cbw.cmd_len = sizeof(scsi_read_capacity10_t);
+
+ //------------- SCSI command -------------//
+ scsi_read_capacity10_t cmd_read_capacity10 =
+ {
+ .cmd_code = SCSI_CMD_READ_CAPACITY_10,
+ .lba = 0,
+ .partial_medium_indicator = 0
+ };
+
+ memcpy(p_msch->cbw.command, &cmd_read_capacity10, p_msch->cbw.cmd_len);
+
+ TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) );
+
+ return TUSB_ERROR_NONE;
+}
+
+tusb_error_t tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, uint8_t *p_data)
+{
+ (void) lun; // TODO [MSCH] multiple lun support
+
+ msch_interface_t* p_msch = &msch_data[dev_addr-1];
+
+ //------------- Command Block Wrapper -------------//
+ p_msch->cbw.total_bytes = 18;
+ p_msch->cbw.dir = TUSB_DIR_IN_MASK;
+ p_msch->cbw.cmd_len = sizeof(scsi_request_sense_t);
+
+ //------------- SCSI command -------------//
+ scsi_request_sense_t cmd_request_sense =
+ {
+ .cmd_code = SCSI_CMD_REQUEST_SENSE,
+ .alloc_length = 18
+ };
+
+ memcpy(p_msch->cbw.command, &cmd_request_sense, p_msch->cbw.cmd_len);
+
+ TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) );
+
+ return TUSB_ERROR_NONE;
+}
+
+tusb_error_t tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, msc_csw_t * p_csw)
+{
+ msch_interface_t* p_msch = &msch_data[dev_addr-1];
+
+ //------------- Command Block Wrapper -------------//
+ msc_cbw_add_signature(&p_msch->cbw, lun);
+
+ p_msch->cbw.total_bytes = 0; // Number of bytes
+ p_msch->cbw.dir = TUSB_DIR_OUT;
+ p_msch->cbw.cmd_len = sizeof(scsi_test_unit_ready_t);
+
+ //------------- SCSI command -------------//
+ scsi_test_unit_ready_t cmd_test_unit_ready =
+ {
+ .cmd_code = SCSI_CMD_TEST_UNIT_READY,
+ .lun = lun // according to wiki
+ };
+
+ memcpy(p_msch->cbw.command, &cmd_test_unit_ready, p_msch->cbw.cmd_len);
+
+ // TODO MSCH refractor test uinit ready
+ TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t), false), TUSB_ERROR_FAILED );
+ TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_in , (uint8_t*) p_csw, sizeof(msc_csw_t), true), TUSB_ERROR_FAILED );
+
+ return TUSB_ERROR_NONE;
+}
+
+tusb_error_t tuh_msc_read10(uint8_t dev_addr, uint8_t lun, void * p_buffer, uint32_t lba, uint16_t block_count)
+{
+ msch_interface_t* p_msch = &msch_data[dev_addr-1];
+
+ //------------- Command Block Wrapper -------------//
+ msc_cbw_add_signature(&p_msch->cbw, lun);
+
+ p_msch->cbw.total_bytes = p_msch->block_size*block_count; // Number of bytes
+ p_msch->cbw.dir = TUSB_DIR_IN_MASK;
+ p_msch->cbw.cmd_len = sizeof(scsi_read10_t);
+
+ //------------- SCSI command -------------//
+ scsi_read10_t cmd_read10 =
+ {
+ .cmd_code = SCSI_CMD_READ_10,
+ .lba = __n2be(lba),
+ .block_count = tu_u16_le2be(block_count)
+ };
+
+ memcpy(p_msch->cbw.command, &cmd_read10, p_msch->cbw.cmd_len);
+
+ TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_buffer));
+
+ return TUSB_ERROR_NONE;
+}
+
+tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffer, uint32_t lba, uint16_t block_count)
+{
+ msch_interface_t* p_msch = &msch_data[dev_addr-1];
+
+ //------------- Command Block Wrapper -------------//
+ msc_cbw_add_signature(&p_msch->cbw, lun);
+
+ p_msch->cbw.total_bytes = p_msch->block_size*block_count; // Number of bytes
+ p_msch->cbw.dir = TUSB_DIR_OUT;
+ p_msch->cbw.cmd_len = sizeof(scsi_write10_t);
+
+ //------------- SCSI command -------------//
+ scsi_write10_t cmd_write10 =
+ {
+ .cmd_code = SCSI_CMD_WRITE_10,
+ .lba = __n2be(lba),
+ .block_count = tu_u16_le2be(block_count)
+ };
+
+ memcpy(p_msch->cbw.command, &cmd_write10, p_msch->cbw.cmd_len);
+
+ TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, (void*) p_buffer));
+
+ return TUSB_ERROR_NONE;
+}
+
+//--------------------------------------------------------------------+
+// CLASS-USBH API (don't require to verify parameters)
+//--------------------------------------------------------------------+
+void msch_init(void)
+{
+ tu_memclr(msch_data, sizeof(msch_interface_t)*CFG_TUSB_HOST_DEVICE_MAX);
+ msch_sem_hdl = osal_semaphore_create(&msch_sem_def);
+}
+
+bool msch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length)
+{
+ TU_VERIFY (MSC_SUBCLASS_SCSI == itf_desc->bInterfaceSubClass &&
+ MSC_PROTOCOL_BOT == itf_desc->bInterfaceProtocol);
+
+ msch_interface_t* p_msc = &msch_data[dev_addr-1];
+
+ //------------- Open Data Pipe -------------//
+ tusb_desc_endpoint_t const * ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc);
+
+ for(uint32_t i=0; i<2; i++)
+ {
+ TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType);
+ TU_ASSERT(TUSB_XFER_BULK == ep_desc->bmAttributes.xfer);
+
+ TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc));
+
+ if ( tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN )
+ {
+ p_msc->ep_in = ep_desc->bEndpointAddress;
+ }else
+ {
+ p_msc->ep_out = ep_desc->bEndpointAddress;
+ }
+
+ ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(ep_desc);
+ }
+
+ p_msc->itf_numr = itf_desc->bInterfaceNumber;
+ (*p_length) += sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t);
+
+ //------------- Get Max Lun -------------//
+ tusb_control_request_t request = {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN },
+ .bRequest = MSC_REQ_GET_MAX_LUN,
+ .wValue = 0,
+ .wIndex = p_msc->itf_numr,
+ .wLength = 1
+ };
+ // TODO STALL means zero
+ TU_ASSERT( usbh_control_xfer( dev_addr, &request, msch_buffer ) );
+ p_msc->max_lun = msch_buffer[0];
+
+#if 0
+ //------------- Reset -------------//
+ request = (tusb_control_request_t) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT },
+ .bRequest = MSC_REQ_RESET,
+ .wValue = 0,
+ .wIndex = p_msc->itf_numr,
+ .wLength = 0
+ };
+ TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) );
+#endif
+
+ enum { SCSI_XFER_TIMEOUT = 2000 };
+ //------------- SCSI Inquiry -------------//
+ tusbh_msc_inquiry(dev_addr, 0, msch_buffer);
+ TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT) );
+
+ memcpy(p_msc->vendor_id , ((scsi_inquiry_resp_t*) msch_buffer)->vendor_id , 8);
+ memcpy(p_msc->product_id, ((scsi_inquiry_resp_t*) msch_buffer)->product_id, 16);
+
+ //------------- SCSI Read Capacity 10 -------------//
+ tusbh_msc_read_capacity10(dev_addr, 0, msch_buffer);
+ TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT));
+
+ // NOTE: my toshiba thumb-drive stall the first Read Capacity and require the sequence
+ // Read Capacity --> Stalled --> Clear Stall --> Request Sense --> Read Capacity (2) to work
+ if ( hcd_edpt_stalled(dev_addr, p_msc->ep_in) )
+ {
+ // clear stall TODO abstract clear stall function
+ request = (tusb_control_request_t) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_ENDPOINT, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT },
+ .bRequest = TUSB_REQ_CLEAR_FEATURE,
+ .wValue = 0,
+ .wIndex = p_msc->ep_in,
+ .wLength = 0
+ };
+
+ TU_ASSERT(usbh_control_xfer( dev_addr, &request, NULL ));
+
+ hcd_edpt_clear_stall(dev_addr, p_msc->ep_in);
+ TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT) ); // wait for SCSI status
+
+ //------------- SCSI Request Sense -------------//
+ (void) tuh_msc_request_sense(dev_addr, 0, msch_buffer);
+ TU_ASSERT(osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT));
+
+ //------------- Re-read SCSI Read Capactity -------------//
+ tusbh_msc_read_capacity10(dev_addr, 0, msch_buffer);
+ TU_ASSERT(osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT));
+ }
+
+ p_msc->last_lba = __be2n( ((scsi_read_capacity10_resp_t*)msch_buffer)->last_lba );
+ p_msc->block_size = (uint16_t) __be2n( ((scsi_read_capacity10_resp_t*)msch_buffer)->block_size );
+
+ p_msc->is_initialized = true;
+
+ tuh_msc_mounted_cb(dev_addr);
+
+ return true;
+}
+
+void msch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
+{
+ msch_interface_t* p_msc = &msch_data[dev_addr-1];
+ if ( ep_addr == p_msc->ep_in )
+ {
+ if (p_msc->is_initialized)
+ {
+ tuh_msc_isr(dev_addr, event, xferred_bytes);
+ }else
+ { // still initializing under open subtask
+ osal_semaphore_post(msch_sem_hdl, true);
+ }
+ }
+}
+
+void msch_close(uint8_t dev_addr)
+{
+ tu_memclr(&msch_data[dev_addr-1], sizeof(msch_interface_t));
+ osal_semaphore_reset(msch_sem_hdl);
+
+ tuh_msc_unmounted_cb(dev_addr); // invoke Application Callback
+}
+
+//--------------------------------------------------------------------+
+// INTERNAL & HELPER
+//--------------------------------------------------------------------+
+
+
+#endif
diff --git a/src/class/msc/msc_host.h b/src/class/msc/msc_host.h new file mode 100644 index 000000000..968d221b4 --- /dev/null +++ b/src/class/msc/msc_host.h @@ -0,0 +1,222 @@ +/**************************************************************************/
+/*!
+ @file msc_host.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_MSC_HOST_H_
+#define _TUSB_MSC_HOST_H_
+
+#include "common/tusb_common.h"
+#include "host/usbh.h"
+#include "msc.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/** \addtogroup ClassDriver_MSC
+ * @{
+ * \defgroup MSC_Host Host
+ * The interface API includes status checking function, data transferring function and callback functions
+ * @{ */
+//--------------------------------------------------------------------+
+// MASS STORAGE Application API
+//--------------------------------------------------------------------+
+/** \brief Check if device supports MassStorage interface or not
+ * \param[in] dev_addr device address
+ * \retval true if device supports
+ * \retval false if device does not support or is not mounted
+ */
+bool tuh_msc_is_mounted(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT;
+
+/** \brief Check if the interface is currently busy or not
+ * \param[in] dev_addr device address
+ * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device
+ * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device
+ * \note This function is used to check if previous transfer is complete (success or error), so that the next transfer
+ * can be scheduled. User needs to make sure the corresponding interface is mounted (by \ref tuh_msc_is_mounted)
+ * before calling this function
+ */
+bool tuh_msc_is_busy(uint8_t dev_addr) ATTR_PURE ATTR_WARN_UNUSED_RESULT;
+
+/** \brief Get SCSI vendor's name of MassStorage device
+ * \param[in] dev_addr device address
+ * \return pointer to vendor's name or NULL if specified device does not support MassStorage
+ * \note SCSI vendor's name is 8-byte length field in \ref scsi_inquiry_data_t. During enumeration, the stack has already
+ * retrieved (via SCSI INQUIRY) and store this information internally. There is no need for application to re-send SCSI INQUIRY
+ * command or allocate buffer for this.
+ */
+uint8_t const* tuh_msc_get_vendor_name(uint8_t dev_addr);
+
+/** \brief Get SCSI product's name of MassStorage device
+ * \param[in] dev_addr device address
+ * \return pointer to product's name or NULL if specified device does not support MassStorage
+ * \note SCSI product's name is 16-byte length field in \ref scsi_inquiry_data_t. During enumeration, the stack has already
+ * retrieved (via SCSI INQUIRY) and store this information internally. There is no need for application to re-send SCSI INQUIRY
+ * command or allocate buffer for this.
+ */
+uint8_t const* tuh_msc_get_product_name(uint8_t dev_addr);
+
+/** \brief Get SCSI Capacity of MassStorage device
+ * \param[in] dev_addr device address
+ * \param[out] p_last_lba Last Logical Block Address of device
+ * \param[out] p_block_size Block Size of device in bytes
+ * \retval pointer to product's name or NULL if specified device does not support MassStorage
+ * \note MassStorage's capacity can be computed by last LBA x block size (in bytes). During enumeration, the stack has already
+ * retrieved (via SCSI READ CAPACITY 10) and store this information internally. There is no need for application
+ * to re-send SCSI READ CAPACITY 10 command
+ */
+tusb_error_t tuh_msc_get_capacity(uint8_t dev_addr, uint32_t* p_last_lba, uint32_t* p_block_size);
+
+/** \brief Perform SCSI READ 10 command to read data from MassStorage device
+ * \param[in] dev_addr device address
+ * \param[in] lun Targeted Logical Unit
+ * \param[out] p_buffer Buffer used to store data read from device. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \param[in] lba Starting Logical Block Address to be read
+ * \param[in] block_count Number of Block to be read
+ * \retval TUSB_ERROR_NONE on success
+ * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
+ * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
+ * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
+ * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function
+ */
+tusb_error_t tuh_msc_read10 (uint8_t dev_addr, uint8_t lun, void * p_buffer, uint32_t lba, uint16_t block_count) ATTR_WARN_UNUSED_RESULT;
+
+/** \brief Perform SCSI WRITE 10 command to write data to MassStorage device
+ * \param[in] dev_addr device address
+ * \param[in] lun Targeted Logical Unit
+ * \param[in] p_buffer Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \param[in] lba Starting Logical Block Address to be written
+ * \param[in] block_count Number of Block to be written
+ * \retval TUSB_ERROR_NONE on success
+ * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
+ * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
+ * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
+ * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function
+ */
+tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffer, uint32_t lba, uint16_t block_count) ATTR_WARN_UNUSED_RESULT;
+
+/** \brief Perform SCSI REQUEST SENSE command, used to retrieve sense data from MassStorage device
+ * \param[in] dev_addr device address
+ * \param[in] lun Targeted Logical Unit
+ * \param[in] p_data Buffer to store response's data from device. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
+ * \retval TUSB_ERROR_NONE on success
+ * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
+ * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
+ * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
+ * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function
+ */
+tusb_error_t tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, uint8_t *p_data);
+
+/** \brief Perform SCSI TEST UNIT READY command to test if MassStorage device is ready
+ * \param[in] dev_addr device address
+ * \param[in] lun Targeted Logical Unit
+ * \retval TUSB_ERROR_NONE on success
+ * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
+ * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
+ * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
+ * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function
+ */
+tusb_error_t tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, msc_csw_t * p_csw) ATTR_WARN_UNUSED_RESULT; // TODO to be refractor
+
+//tusb_error_t tusbh_msc_scsi_send(uint8_t dev_addr, uint8_t lun, bool is_direction_in,
+// uint8_t const * p_command, uint8_t cmd_len,
+// uint8_t * p_response, uint32_t resp_len) ATTR_WARN_UNUSED_RESULT;
+
+//------------- Application Callback -------------//
+/** \brief Callback function that will be invoked when a device with MassStorage interface is mounted
+ * \param[in] dev_addr Address of newly mounted device
+ * \note This callback should be used by Application to set-up interface-related data
+ */
+void tuh_msc_mounted_cb(uint8_t dev_addr);
+
+/** \brief Callback function that will be invoked when a device with MassStorage interface is unmounted
+ * \param[in] dev_addr Address of newly unmounted device
+ * \note This callback should be used by Application to tear-down interface-related data
+ */
+void tuh_msc_unmounted_cb(uint8_t dev_addr);
+
+/** \brief Callback function that is invoked when an transferring event occurred
+ * \param[in] dev_addr Address of device
+ * \param[in] event an value from \ref xfer_result_t
+ * \param[in] xferred_bytes Number of bytes transferred via USB bus
+ * \note event can be one of following
+ * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully.
+ * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error.
+ * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device.
+ * \note
+ */
+void tuh_msc_isr(uint8_t dev_addr, xfer_result_t event, uint32_t xferred_bytes);
+
+
+//--------------------------------------------------------------------+
+// USBH-CLASS DRIVER API
+//--------------------------------------------------------------------+
+#ifdef _TINY_USB_SOURCE_FILE_
+
+typedef struct
+{
+ uint8_t itf_numr;
+ uint8_t ep_in;
+ uint8_t ep_out;
+
+ uint8_t max_lun;
+ uint16_t block_size;
+ uint32_t last_lba; // last logical block address
+
+ volatile bool is_initialized;
+ uint8_t vendor_id[8];
+ uint8_t product_id[16];
+
+ msc_cbw_t cbw;
+ msc_csw_t csw;
+}msch_interface_t;
+
+void msch_init(void);
+bool msch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length);
+void msch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
+void msch_close(uint8_t dev_addr);
+
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_MSC_HOST_H_ */
+
+/// @}
+/// @}
diff --git a/src/common/binary.h b/src/common/binary.h new file mode 100644 index 000000000..3ab87e3f8 --- /dev/null +++ b/src/common/binary.h @@ -0,0 +1,132 @@ +/**************************************************************************/
+/*!
+ @file binary.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup Group_Common
+ * \defgroup Group_Binary Binary
+ * @{ */
+
+#ifndef _TUSB_BINARY_H_
+#define _TUSB_BINARY_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#include <stdbool.h>
+#include <stdint.h>
+#include "tusb_compiler.h"
+
+//------------- Bit manipulation -------------//
+#define BIT_(n) (1U << (n)) ///< n-th Bit
+#define BIT_SET_(x, n) ( (x) | BIT_(n) ) ///< set n-th bit of x to 1
+#define BIT_CLR_(x, n) ( (x) & (~BIT_(n)) ) ///< clear n-th bit of x
+#define BIT_TEST_(x, n) ( ((x) & BIT_(n)) ? true : false ) ///< check if n-th bit of x is 1
+
+static inline uint32_t bit_set(uint32_t value, uint8_t n) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint32_t bit_set(uint32_t value, uint8_t n)
+{
+ return value | BIT_(n);
+}
+
+static inline uint32_t bit_clear(uint32_t value, uint8_t n) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint32_t bit_clear(uint32_t value, uint8_t n)
+{
+ return value & (~BIT_(n));
+}
+
+static inline bool bit_test(uint32_t value, uint8_t n) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline bool bit_test(uint32_t value, uint8_t n)
+{
+ return (value & BIT_(n)) ? true : false;
+}
+
+///< create a mask with n-bit lsb set to 1
+static inline uint32_t bit_mask(uint8_t n) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint32_t bit_mask(uint8_t n)
+{
+ return (n < 32) ? ( BIT_(n) - 1 ) : UINT32_MAX;
+}
+
+static inline uint32_t bit_mask_range(uint8_t start, uint32_t end) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint32_t bit_mask_range(uint8_t start, uint32_t end)
+{
+ return bit_mask(end+1) & ~ bit_mask(start);
+}
+
+static inline uint32_t bit_set_range(uint32_t value, uint8_t start, uint8_t end, uint32_t pattern) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint32_t bit_set_range(uint32_t value, uint8_t start, uint8_t end, uint32_t pattern)
+{
+ return ( value & ~bit_mask_range(start, end) ) | (pattern << start);
+}
+
+
+//------------- Binary Constant -------------//
+#if defined(__GNUC__) && !defined(__CC_ARM)
+
+#define BIN8(x) ((uint8_t) (0b##x))
+#define BIN16(b1, b2) ((uint16_t) (0b##b1##b2))
+#define BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4))
+
+#else
+
+// internal macro of B8, B16, B32
+#define _B8__(x) (((x&0x0000000FUL)?1:0) \
+ +((x&0x000000F0UL)?2:0) \
+ +((x&0x00000F00UL)?4:0) \
+ +((x&0x0000F000UL)?8:0) \
+ +((x&0x000F0000UL)?16:0) \
+ +((x&0x00F00000UL)?32:0) \
+ +((x&0x0F000000UL)?64:0) \
+ +((x&0xF0000000UL)?128:0))
+
+#define BIN8(d) ((uint8_t) _B8__(0x##d##UL))
+#define BIN16(dmsb,dlsb) (((uint16_t)BIN8(dmsb)<<8) + BIN8(dlsb))
+#define BIN32(dmsb,db2,db3,dlsb) \
+ (((uint32_t)BIN8(dmsb)<<24) \
+ + ((uint32_t)BIN8(db2)<<16) \
+ + ((uint32_t)BIN8(db3)<<8) \
+ + BIN8(dlsb))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TUSB_BINARY_H_ */
+
+/** @} */
diff --git a/src/common/compiler/tusb_compiler_gcc.h b/src/common/compiler/tusb_compiler_gcc.h new file mode 100644 index 000000000..e40ad9c41 --- /dev/null +++ b/src/common/compiler/tusb_compiler_gcc.h @@ -0,0 +1,135 @@ +/**************************************************************************/ +/*! + @file compiler_gcc.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup Group_Compiler + * \defgroup Group_GCC GNU GCC + * @{ */ + +#ifndef _TUSB_COMPILER_GCC_H_ +#define _TUSB_COMPILER_GCC_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define ALIGN_OF(x) __alignof__(x) + +/// Normally, the compiler places the objects it generates in sections like data or bss & function in text. Sometimes, however, you need additional sections, or you need certain particular variables to appear in special sections, for example to map to special hardware. The section attribute specifies that a variable (or function) lives in a particular section +#define ATTR_SECTION(sec_name) __attribute__ (( section(#sec_name) )) + +/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, an error that includes message is diagnosed. This is useful for compile-time checking +#define ATTR_ERROR(Message) __attribute__ ((error(Message))) + +/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, a warning that includes message is diagnosed. This is useful for compile-time checking +#define ATTR_WARNING(Message) __attribute__ ((warning(Message))) + +/** \defgroup Group_VariableAttr Variable Attributes + * @{ */ + +/// This attribute specifies a minimum alignment for the variable or structure field, measured in bytes +#define ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes))) + +/// The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute +#define ATTR_PACKED __attribute__ ((packed)) +#define ATTR_PREPACKED + +/** @} */ + +/** \defgroup Group_FuncAttr Function Attributes + * @{ */ + +/// Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified +#define ATTR_ALWAYS_INLINE __attribute__ ((always_inline)) + +/// The nonnull attribute specifies that some function parameters should be non-null pointers. f the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. All pointer arguments are marked as non-null +#define ATTR_NON_NULL __attribute__ ((nonull)) + +/// Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure +#define ATTR_PURE __attribute__ ((pure)) + +/// \brief Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory. +/// Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void +#define ATTR_CONST __attribute__ ((const)) + +/// The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses +#define ATTR_DEPRECATED __attribute__ ((deprecated)) + +/// Same as the deprecated attribute with optional message in the warning +#define ATTR_DEPRECATED_MESS(mess) __attribute__ ((deprecated(mess))) + +/// The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions that can be overridden in user code +#define ATTR_WEAK __attribute__ ((weak)) + +/// The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified +#define ATTR_ALIAS(func) __attribute__ ((alias(#func))) + +/// The weakref attribute marks a declaration as a weak reference. It is equivalent with weak + alias attribute, but require function is static +#define ATTR_WEAKREF(func) __attribute__ ((weakref(#func))) + +/// The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug +#define ATTR_WARN_UNUSED_RESULT __attribute__ ((warn_unused_result)) + +/// This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly. +#define ATTR_USED __attribute__ ((used)) + +/// This attribute, attached to a function, means that the function is meant to be possibly unused. GCC does not produce a warning for this function. +#define ATTR_UNUSED __attribute__ ((unused)) + +/** @} */ + +/** \defgroup Group_BuiltinFunc Built-in Functions +* @{ */ + +// TODO mcu specific +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define __n2be(x) __builtin_bswap32(x) ///< built-in function to convert 32-bit from native to Big Endian +#define __be2n(x) __n2be(x) ///< built-in function to convert 32-bit from Big Endian to native + +#define __n2be_16(u16) __builtin_bswap16(u16) +#define __be2n_16(u16) __n2be_16(u16) +#endif + +/** @} */ + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_COMPILER_GCC_H_ */ + +/// @} diff --git a/src/common/compiler/tusb_compiler_iar.h b/src/common/compiler/tusb_compiler_iar.h new file mode 100644 index 000000000..1f8936859 --- /dev/null +++ b/src/common/compiler/tusb_compiler_iar.h @@ -0,0 +1,89 @@ +/**************************************************************************/
+/*!
+ @file compiler_iar.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \file
+ * \brief IAR Compiler
+ */
+
+/** \ingroup Group_Compiler
+ * \defgroup Group_IAR IAR ARM
+ * @{
+ */
+
+#ifndef _TUSB_COMPILER_IAR_H_
+#define _TUSB_COMPILER_IAR_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#define ALIGN_OF(x) __ALIGNOF__(x)
+#define ATTR_PREPACKED __packed
+#define ATTR_PACKED
+//#define ATTR_SECTION(section) _Pragma((#section))
+
+#define ATTR_ALIGNED(bytes) _Pragma(XSTRING_(data_alignment=##bytes))
+
+#ifndef ATTR_ALWAYS_INLINE
+/// Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified
+#define ATTR_ALWAYS_INLINE error
+#endif
+
+#define ATTR_PURE // TODO IAR pure function attribute
+#define ATTR_CONST // TODO IAR const function attribute
+#define ATTR_WEAK __weak
+
+#define ATTR_WARN_UNUSED_RESULT
+#define ATTR_USED
+#define ATTR_UNUSED
+
+// built-in function to convert 32-bit Big-Endian to Little-Endian
+//#if __LITTLE_ENDIAN__
+#define __be2n __REV
+#define __n2be __be2n
+
+#define __n2be_16(u16) ((uint16_t) __REV16(u16))
+#define __be2n_16(u16) __n2be_16(u16)
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_COMPILER_IAR_H_ */
+
+/** @} */
diff --git a/src/common/sys_queue.h b/src/common/sys_queue.h new file mode 100644 index 000000000..443f01b22 --- /dev/null +++ b/src/common/sys_queue.h @@ -0,0 +1,871 @@ +/*- + * SPDX-License-Identifier: BSD-3-Clause + * + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)queue.h 8.5 (Berkeley) 8/20/94 + * $FreeBSD$ + */ + +#ifndef _SYS_QUEUE_H_ +#define _SYS_QUEUE_H_ + +#include <sys/cdefs.h> + +/* + * This file defines four types of data structures: singly-linked lists, + * singly-linked tail queues, lists and tail queues. + * + * A singly-linked list is headed by a single forward pointer. The elements + * are singly linked for minimum space and pointer manipulation overhead at + * the expense of O(n) removal for arbitrary elements. New elements can be + * added to the list after an existing element or at the head of the list. + * Elements being removed from the head of the list should use the explicit + * macro for this purpose for optimum efficiency. A singly-linked list may + * only be traversed in the forward direction. Singly-linked lists are ideal + * for applications with large datasets and few or no removals or for + * implementing a LIFO queue. + * + * A singly-linked tail queue is headed by a pair of pointers, one to the + * head of the list and the other to the tail of the list. The elements are + * singly linked for minimum space and pointer manipulation overhead at the + * expense of O(n) removal for arbitrary elements. New elements can be added + * to the list after an existing element, at the head of the list, or at the + * end of the list. Elements being removed from the head of the tail queue + * should use the explicit macro for this purpose for optimum efficiency. + * A singly-linked tail queue may only be traversed in the forward direction. + * Singly-linked tail queues are ideal for applications with large datasets + * and few or no removals or for implementing a FIFO queue. + * + * A list is headed by a single forward pointer (or an array of forward + * pointers for a hash table header). The elements are doubly linked + * so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before + * or after an existing element or at the head of the list. A list + * may be traversed in either direction. + * + * A tail queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. The elements are doubly + * linked so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before or + * after an existing element, at the head of the list, or at the end of + * the list. A tail queue may be traversed in either direction. + * + * For details on the use of these macros, see the queue(3) manual page. + * + * Below is a summary of implemented functions where: + * + means the macro is available + * - means the macro is not available + * s means the macro is available but is slow (runs in O(n) time) + * + * SLIST LIST STAILQ TAILQ + * _HEAD + + + + + * _CLASS_HEAD + + + + + * _HEAD_INITIALIZER + + + + + * _ENTRY + + + + + * _CLASS_ENTRY + + + + + * _INIT + + + + + * _EMPTY + + + + + * _FIRST + + + + + * _NEXT + + + + + * _PREV - + - + + * _LAST - - + + + * _LAST_FAST - - - + + * _FOREACH + + + + + * _FOREACH_FROM + + + + + * _FOREACH_SAFE + + + + + * _FOREACH_FROM_SAFE + + + + + * _FOREACH_REVERSE - - - + + * _FOREACH_REVERSE_FROM - - - + + * _FOREACH_REVERSE_SAFE - - - + + * _FOREACH_REVERSE_FROM_SAFE - - - + + * _INSERT_HEAD + + + + + * _INSERT_BEFORE - + - + + * _INSERT_AFTER + + + + + * _INSERT_TAIL - - + + + * _CONCAT s s + + + * _REMOVE_AFTER + - + - + * _REMOVE_HEAD + - + - + * _REMOVE s + s + + * _SWAP + + + + + * + */ +#ifdef QUEUE_MACRO_DEBUG +#warn Use QUEUE_MACRO_DEBUG_TRACE and/or QUEUE_MACRO_DEBUG_TRASH +#define QUEUE_MACRO_DEBUG_TRACE +#define QUEUE_MACRO_DEBUG_TRASH +#endif + +#ifdef QUEUE_MACRO_DEBUG_TRACE +/* Store the last 2 places the queue element or head was altered */ +struct qm_trace { + unsigned long lastline; + unsigned long prevline; + const char *lastfile; + const char *prevfile; +}; + +#define TRACEBUF struct qm_trace trace; +#define TRACEBUF_INITIALIZER { __LINE__, 0, __FILE__, NULL } , + +#define QMD_TRACE_HEAD(head) do { \ + (head)->trace.prevline = (head)->trace.lastline; \ + (head)->trace.prevfile = (head)->trace.lastfile; \ + (head)->trace.lastline = __LINE__; \ + (head)->trace.lastfile = __FILE__; \ +} while (0) + +#define QMD_TRACE_ELEM(elem) do { \ + (elem)->trace.prevline = (elem)->trace.lastline; \ + (elem)->trace.prevfile = (elem)->trace.lastfile; \ + (elem)->trace.lastline = __LINE__; \ + (elem)->trace.lastfile = __FILE__; \ +} while (0) + +#else /* !QUEUE_MACRO_DEBUG_TRACE */ +#define QMD_TRACE_ELEM(elem) +#define QMD_TRACE_HEAD(head) +#define TRACEBUF +#define TRACEBUF_INITIALIZER +#endif /* QUEUE_MACRO_DEBUG_TRACE */ + +#ifdef QUEUE_MACRO_DEBUG_TRASH +#define TRASHIT(x) do {(x) = (void *)-1;} while (0) +#define QMD_IS_TRASHED(x) ((x) == (void *)(intptr_t)-1) +#else /* !QUEUE_MACRO_DEBUG_TRASH */ +#define TRASHIT(x) +#define QMD_IS_TRASHED(x) 0 +#endif /* QUEUE_MACRO_DEBUG_TRASH */ + +#if defined(QUEUE_MACRO_DEBUG_TRACE) || defined(QUEUE_MACRO_DEBUG_TRASH) +#define QMD_SAVELINK(name, link) void **name = (void *)&(link) +#else /* !QUEUE_MACRO_DEBUG_TRACE && !QUEUE_MACRO_DEBUG_TRASH */ +#define QMD_SAVELINK(name, link) +#endif /* QUEUE_MACRO_DEBUG_TRACE || QUEUE_MACRO_DEBUG_TRASH */ + +#ifdef __cplusplus +/* + * In C++ there can be structure lists and class lists: + */ +#define QUEUE_TYPEOF(type) type +#else +#define QUEUE_TYPEOF(type) struct type +#endif + +/* + * Singly-linked List declarations. + */ +#define SLIST_HEAD(name, type) \ +struct name { \ + struct type *slh_first; /* first element */ \ +} + +#define SLIST_CLASS_HEAD(name, type) \ +struct name { \ + class type *slh_first; /* first element */ \ +} + +#define SLIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define SLIST_ENTRY(type) \ +struct { \ + struct type *sle_next; /* next element */ \ +} + +#define SLIST_CLASS_ENTRY(type) \ +struct { \ + class type *sle_next; /* next element */ \ +} + +/* + * Singly-linked List functions. + */ +#if (defined(_KERNEL) && defined(INVARIANTS)) +#define QMD_SLIST_CHECK_PREVPTR(prevp, elm) do { \ + if (*(prevp) != (elm)) \ + panic("Bad prevptr *(%p) == %p != %p", \ + (prevp), *(prevp), (elm)); \ +} while (0) +#else +#define QMD_SLIST_CHECK_PREVPTR(prevp, elm) +#endif + +#define SLIST_CONCAT(head1, head2, type, field) do { \ + QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head1); \ + if (curelm == NULL) { \ + if ((SLIST_FIRST(head1) = SLIST_FIRST(head2)) != NULL) \ + SLIST_INIT(head2); \ + } else if (SLIST_FIRST(head2) != NULL) { \ + while (SLIST_NEXT(curelm, field) != NULL) \ + curelm = SLIST_NEXT(curelm, field); \ + SLIST_NEXT(curelm, field) = SLIST_FIRST(head2); \ + SLIST_INIT(head2); \ + } \ +} while (0) + +#define SLIST_EMPTY(head) ((head)->slh_first == NULL) + +#define SLIST_FIRST(head) ((head)->slh_first) + +#define SLIST_FOREACH(var, head, field) \ + for ((var) = SLIST_FIRST((head)); \ + (var); \ + (var) = SLIST_NEXT((var), field)) + +#define SLIST_FOREACH_FROM(var, head, field) \ + for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \ + (var); \ + (var) = SLIST_NEXT((var), field)) + +#define SLIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = SLIST_FIRST((head)); \ + (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define SLIST_FOREACH_FROM_SAFE(var, head, field, tvar) \ + for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \ + (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define SLIST_FOREACH_PREVPTR(var, varp, head, field) \ + for ((varp) = &SLIST_FIRST((head)); \ + ((var) = *(varp)) != NULL; \ + (varp) = &SLIST_NEXT((var), field)) + +#define SLIST_INIT(head) do { \ + SLIST_FIRST((head)) = NULL; \ +} while (0) + +#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ + SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \ + SLIST_NEXT((slistelm), field) = (elm); \ +} while (0) + +#define SLIST_INSERT_HEAD(head, elm, field) do { \ + SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \ + SLIST_FIRST((head)) = (elm); \ +} while (0) + +#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) + +#define SLIST_REMOVE(head, elm, type, field) do { \ + QMD_SAVELINK(oldnext, (elm)->field.sle_next); \ + if (SLIST_FIRST((head)) == (elm)) { \ + SLIST_REMOVE_HEAD((head), field); \ + } \ + else { \ + QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head); \ + while (SLIST_NEXT(curelm, field) != (elm)) \ + curelm = SLIST_NEXT(curelm, field); \ + SLIST_REMOVE_AFTER(curelm, field); \ + } \ + TRASHIT(*oldnext); \ +} while (0) + +#define SLIST_REMOVE_AFTER(elm, field) do { \ + SLIST_NEXT(elm, field) = \ + SLIST_NEXT(SLIST_NEXT(elm, field), field); \ +} while (0) + +#define SLIST_REMOVE_HEAD(head, field) do { \ + SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \ +} while (0) + +#define SLIST_REMOVE_PREVPTR(prevp, elm, field) do { \ + QMD_SLIST_CHECK_PREVPTR(prevp, elm); \ + *(prevp) = SLIST_NEXT(elm, field); \ + TRASHIT((elm)->field.sle_next); \ +} while (0) + +#define SLIST_SWAP(head1, head2, type) do { \ + QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1); \ + SLIST_FIRST(head1) = SLIST_FIRST(head2); \ + SLIST_FIRST(head2) = swap_first; \ +} while (0) + +/* + * Singly-linked Tail queue declarations. + */ +#define STAILQ_HEAD(name, type) \ +struct name { \ + struct type *stqh_first;/* first element */ \ + struct type **stqh_last;/* addr of last next element */ \ +} + +#define STAILQ_CLASS_HEAD(name, type) \ +struct name { \ + class type *stqh_first; /* first element */ \ + class type **stqh_last; /* addr of last next element */ \ +} + +#define STAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).stqh_first } + +#define STAILQ_ENTRY(type) \ +struct { \ + struct type *stqe_next; /* next element */ \ +} + +#define STAILQ_CLASS_ENTRY(type) \ +struct { \ + class type *stqe_next; /* next element */ \ +} + +/* + * Singly-linked Tail queue functions. + */ +#define STAILQ_CONCAT(head1, head2) do { \ + if (!STAILQ_EMPTY((head2))) { \ + *(head1)->stqh_last = (head2)->stqh_first; \ + (head1)->stqh_last = (head2)->stqh_last; \ + STAILQ_INIT((head2)); \ + } \ +} while (0) + +#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) + +#define STAILQ_FIRST(head) ((head)->stqh_first) + +#define STAILQ_FOREACH(var, head, field) \ + for((var) = STAILQ_FIRST((head)); \ + (var); \ + (var) = STAILQ_NEXT((var), field)) + +#define STAILQ_FOREACH_FROM(var, head, field) \ + for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \ + (var); \ + (var) = STAILQ_NEXT((var), field)) + +#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = STAILQ_FIRST((head)); \ + (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \ + for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \ + (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define STAILQ_INIT(head) do { \ + STAILQ_FIRST((head)) = NULL; \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ +} while (0) + +#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) do { \ + if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + STAILQ_NEXT((tqelm), field) = (elm); \ +} while (0) + +#define STAILQ_INSERT_HEAD(head, elm, field) do { \ + if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + STAILQ_FIRST((head)) = (elm); \ +} while (0) + +#define STAILQ_INSERT_TAIL(head, elm, field) do { \ + STAILQ_NEXT((elm), field) = NULL; \ + *(head)->stqh_last = (elm); \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ +} while (0) + +#define STAILQ_LAST(head, type, field) \ + (STAILQ_EMPTY((head)) ? NULL : \ + __containerof((head)->stqh_last, \ + QUEUE_TYPEOF(type), field.stqe_next)) + +#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) + +#define STAILQ_REMOVE(head, elm, type, field) do { \ + QMD_SAVELINK(oldnext, (elm)->field.stqe_next); \ + if (STAILQ_FIRST((head)) == (elm)) { \ + STAILQ_REMOVE_HEAD((head), field); \ + } \ + else { \ + QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head); \ + while (STAILQ_NEXT(curelm, field) != (elm)) \ + curelm = STAILQ_NEXT(curelm, field); \ + STAILQ_REMOVE_AFTER(head, curelm, field); \ + } \ + TRASHIT(*oldnext); \ +} while (0) + +#define STAILQ_REMOVE_AFTER(head, elm, field) do { \ + if ((STAILQ_NEXT(elm, field) = \ + STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ +} while (0) + +#define STAILQ_REMOVE_HEAD(head, field) do { \ + if ((STAILQ_FIRST((head)) = \ + STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ +} while (0) + +#define STAILQ_SWAP(head1, head2, type) do { \ + QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1); \ + QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last; \ + STAILQ_FIRST(head1) = STAILQ_FIRST(head2); \ + (head1)->stqh_last = (head2)->stqh_last; \ + STAILQ_FIRST(head2) = swap_first; \ + (head2)->stqh_last = swap_last; \ + if (STAILQ_EMPTY(head1)) \ + (head1)->stqh_last = &STAILQ_FIRST(head1); \ + if (STAILQ_EMPTY(head2)) \ + (head2)->stqh_last = &STAILQ_FIRST(head2); \ +} while (0) + + +/* + * List declarations. + */ +#define LIST_HEAD(name, type) \ +struct name { \ + struct type *lh_first; /* first element */ \ +} + +#define LIST_CLASS_HEAD(name, type) \ +struct name { \ + class type *lh_first; /* first element */ \ +} + +#define LIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define LIST_ENTRY(type) \ +struct { \ + struct type *le_next; /* next element */ \ + struct type **le_prev; /* address of previous next element */ \ +} + +#define LIST_CLASS_ENTRY(type) \ +struct { \ + class type *le_next; /* next element */ \ + class type **le_prev; /* address of previous next element */ \ +} + +/* + * List functions. + */ + +#if (defined(_KERNEL) && defined(INVARIANTS)) +/* + * QMD_LIST_CHECK_HEAD(LIST_HEAD *head, LIST_ENTRY NAME) + * + * If the list is non-empty, validates that the first element of the list + * points back at 'head.' + */ +#define QMD_LIST_CHECK_HEAD(head, field) do { \ + if (LIST_FIRST((head)) != NULL && \ + LIST_FIRST((head))->field.le_prev != \ + &LIST_FIRST((head))) \ + panic("Bad list head %p first->prev != head", (head)); \ +} while (0) + +/* + * QMD_LIST_CHECK_NEXT(TYPE *elm, LIST_ENTRY NAME) + * + * If an element follows 'elm' in the list, validates that the next element + * points back at 'elm.' + */ +#define QMD_LIST_CHECK_NEXT(elm, field) do { \ + if (LIST_NEXT((elm), field) != NULL && \ + LIST_NEXT((elm), field)->field.le_prev != \ + &((elm)->field.le_next)) \ + panic("Bad link elm %p next->prev != elm", (elm)); \ +} while (0) + +/* + * QMD_LIST_CHECK_PREV(TYPE *elm, LIST_ENTRY NAME) + * + * Validates that the previous element (or head of the list) points to 'elm.' + */ +#define QMD_LIST_CHECK_PREV(elm, field) do { \ + if (*(elm)->field.le_prev != (elm)) \ + panic("Bad link elm %p prev->next != elm", (elm)); \ +} while (0) +#else +#define QMD_LIST_CHECK_HEAD(head, field) +#define QMD_LIST_CHECK_NEXT(elm, field) +#define QMD_LIST_CHECK_PREV(elm, field) +#endif /* (_KERNEL && INVARIANTS) */ + +#define LIST_CONCAT(head1, head2, type, field) do { \ + QUEUE_TYPEOF(type) *curelm = LIST_FIRST(head1); \ + if (curelm == NULL) { \ + if ((LIST_FIRST(head1) = LIST_FIRST(head2)) != NULL) { \ + LIST_FIRST(head2)->field.le_prev = \ + &LIST_FIRST((head1)); \ + LIST_INIT(head2); \ + } \ + } else if (LIST_FIRST(head2) != NULL) { \ + while (LIST_NEXT(curelm, field) != NULL) \ + curelm = LIST_NEXT(curelm, field); \ + LIST_NEXT(curelm, field) = LIST_FIRST(head2); \ + LIST_FIRST(head2)->field.le_prev = &LIST_NEXT(curelm, field); \ + LIST_INIT(head2); \ + } \ +} while (0) + +#define LIST_EMPTY(head) ((head)->lh_first == NULL) + +#define LIST_FIRST(head) ((head)->lh_first) + +#define LIST_FOREACH(var, head, field) \ + for ((var) = LIST_FIRST((head)); \ + (var); \ + (var) = LIST_NEXT((var), field)) + +#define LIST_FOREACH_FROM(var, head, field) \ + for ((var) = ((var) ? (var) : LIST_FIRST((head))); \ + (var); \ + (var) = LIST_NEXT((var), field)) + +#define LIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = LIST_FIRST((head)); \ + (var) && ((tvar) = LIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define LIST_FOREACH_FROM_SAFE(var, head, field, tvar) \ + for ((var) = ((var) ? (var) : LIST_FIRST((head))); \ + (var) && ((tvar) = LIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define LIST_INIT(head) do { \ + LIST_FIRST((head)) = NULL; \ +} while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field) do { \ + QMD_LIST_CHECK_NEXT(listelm, field); \ + if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\ + LIST_NEXT((listelm), field)->field.le_prev = \ + &LIST_NEXT((elm), field); \ + LIST_NEXT((listelm), field) = (elm); \ + (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ +} while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ + QMD_LIST_CHECK_PREV(listelm, field); \ + (elm)->field.le_prev = (listelm)->field.le_prev; \ + LIST_NEXT((elm), field) = (listelm); \ + *(listelm)->field.le_prev = (elm); \ + (listelm)->field.le_prev = &LIST_NEXT((elm), field); \ +} while (0) + +#define LIST_INSERT_HEAD(head, elm, field) do { \ + QMD_LIST_CHECK_HEAD((head), field); \ + if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \ + LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\ + LIST_FIRST((head)) = (elm); \ + (elm)->field.le_prev = &LIST_FIRST((head)); \ +} while (0) + +#define LIST_NEXT(elm, field) ((elm)->field.le_next) + +#define LIST_PREV(elm, head, type, field) \ + ((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL : \ + __containerof((elm)->field.le_prev, \ + QUEUE_TYPEOF(type), field.le_next)) + +#define LIST_REMOVE(elm, field) do { \ + QMD_SAVELINK(oldnext, (elm)->field.le_next); \ + QMD_SAVELINK(oldprev, (elm)->field.le_prev); \ + QMD_LIST_CHECK_NEXT(elm, field); \ + QMD_LIST_CHECK_PREV(elm, field); \ + if (LIST_NEXT((elm), field) != NULL) \ + LIST_NEXT((elm), field)->field.le_prev = \ + (elm)->field.le_prev; \ + *(elm)->field.le_prev = LIST_NEXT((elm), field); \ + TRASHIT(*oldnext); \ + TRASHIT(*oldprev); \ +} while (0) + +#define LIST_SWAP(head1, head2, type, field) do { \ + QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1); \ + LIST_FIRST((head1)) = LIST_FIRST((head2)); \ + LIST_FIRST((head2)) = swap_tmp; \ + if ((swap_tmp = LIST_FIRST((head1))) != NULL) \ + swap_tmp->field.le_prev = &LIST_FIRST((head1)); \ + if ((swap_tmp = LIST_FIRST((head2))) != NULL) \ + swap_tmp->field.le_prev = &LIST_FIRST((head2)); \ +} while (0) + +/* + * Tail queue declarations. + */ +#define TAILQ_HEAD(name, type) \ +struct name { \ + struct type *tqh_first; /* first element */ \ + struct type **tqh_last; /* addr of last next element */ \ + TRACEBUF \ +} + +#define TAILQ_CLASS_HEAD(name, type) \ +struct name { \ + class type *tqh_first; /* first element */ \ + class type **tqh_last; /* addr of last next element */ \ + TRACEBUF \ +} + +#define TAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).tqh_first, TRACEBUF_INITIALIZER } + +#define TAILQ_ENTRY(type) \ +struct { \ + struct type *tqe_next; /* next element */ \ + struct type **tqe_prev; /* address of previous next element */ \ + TRACEBUF \ +} + +#define TAILQ_CLASS_ENTRY(type) \ +struct { \ + class type *tqe_next; /* next element */ \ + class type **tqe_prev; /* address of previous next element */ \ + TRACEBUF \ +} + +/* + * Tail queue functions. + */ +#if (defined(_KERNEL) && defined(INVARIANTS)) +/* + * QMD_TAILQ_CHECK_HEAD(TAILQ_HEAD *head, TAILQ_ENTRY NAME) + * + * If the tailq is non-empty, validates that the first element of the tailq + * points back at 'head.' + */ +#define QMD_TAILQ_CHECK_HEAD(head, field) do { \ + if (!TAILQ_EMPTY(head) && \ + TAILQ_FIRST((head))->field.tqe_prev != \ + &TAILQ_FIRST((head))) \ + panic("Bad tailq head %p first->prev != head", (head)); \ +} while (0) + +/* + * QMD_TAILQ_CHECK_TAIL(TAILQ_HEAD *head, TAILQ_ENTRY NAME) + * + * Validates that the tail of the tailq is a pointer to pointer to NULL. + */ +#define QMD_TAILQ_CHECK_TAIL(head, field) do { \ + if (*(head)->tqh_last != NULL) \ + panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); \ +} while (0) + +/* + * QMD_TAILQ_CHECK_NEXT(TYPE *elm, TAILQ_ENTRY NAME) + * + * If an element follows 'elm' in the tailq, validates that the next element + * points back at 'elm.' + */ +#define QMD_TAILQ_CHECK_NEXT(elm, field) do { \ + if (TAILQ_NEXT((elm), field) != NULL && \ + TAILQ_NEXT((elm), field)->field.tqe_prev != \ + &((elm)->field.tqe_next)) \ + panic("Bad link elm %p next->prev != elm", (elm)); \ +} while (0) + +/* + * QMD_TAILQ_CHECK_PREV(TYPE *elm, TAILQ_ENTRY NAME) + * + * Validates that the previous element (or head of the tailq) points to 'elm.' + */ +#define QMD_TAILQ_CHECK_PREV(elm, field) do { \ + if (*(elm)->field.tqe_prev != (elm)) \ + panic("Bad link elm %p prev->next != elm", (elm)); \ +} while (0) +#else +#define QMD_TAILQ_CHECK_HEAD(head, field) +#define QMD_TAILQ_CHECK_TAIL(head, headname) +#define QMD_TAILQ_CHECK_NEXT(elm, field) +#define QMD_TAILQ_CHECK_PREV(elm, field) +#endif /* (_KERNEL && INVARIANTS) */ + +#define TAILQ_CONCAT(head1, head2, field) do { \ + if (!TAILQ_EMPTY(head2)) { \ + *(head1)->tqh_last = (head2)->tqh_first; \ + (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ + (head1)->tqh_last = (head2)->tqh_last; \ + TAILQ_INIT((head2)); \ + QMD_TRACE_HEAD(head1); \ + QMD_TRACE_HEAD(head2); \ + } \ +} while (0) + +#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) + +#define TAILQ_FIRST(head) ((head)->tqh_first) + +#define TAILQ_FOREACH(var, head, field) \ + for ((var) = TAILQ_FIRST((head)); \ + (var); \ + (var) = TAILQ_NEXT((var), field)) + +#define TAILQ_FOREACH_FROM(var, head, field) \ + for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \ + (var); \ + (var) = TAILQ_NEXT((var), field)) + +#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = TAILQ_FIRST((head)); \ + (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \ + for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \ + (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ + for ((var) = TAILQ_LAST((head), headname); \ + (var); \ + (var) = TAILQ_PREV((var), headname, field)) + +#define TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field) \ + for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \ + (var); \ + (var) = TAILQ_PREV((var), headname, field)) + +#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ + for ((var) = TAILQ_LAST((head), headname); \ + (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ + (var) = (tvar)) + +#define TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \ + for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \ + (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ + (var) = (tvar)) + +#define TAILQ_INIT(head) do { \ + TAILQ_FIRST((head)) = NULL; \ + (head)->tqh_last = &TAILQ_FIRST((head)); \ + QMD_TRACE_HEAD(head); \ +} while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ + QMD_TAILQ_CHECK_NEXT(listelm, field); \ + if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else { \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_HEAD(head); \ + } \ + TAILQ_NEXT((listelm), field) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ + QMD_TRACE_ELEM(&(elm)->field); \ + QMD_TRACE_ELEM(&(listelm)->field); \ +} while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ + QMD_TAILQ_CHECK_PREV(listelm, field); \ + (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ + TAILQ_NEXT((elm), field) = (listelm); \ + *(listelm)->field.tqe_prev = (elm); \ + (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_ELEM(&(elm)->field); \ + QMD_TRACE_ELEM(&(listelm)->field); \ +} while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field) do { \ + QMD_TAILQ_CHECK_HEAD(head, field); \ + if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ + TAILQ_FIRST((head))->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_FIRST((head)) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ + QMD_TRACE_HEAD(head); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field) do { \ + QMD_TAILQ_CHECK_TAIL(head, field); \ + TAILQ_NEXT((elm), field) = NULL; \ + (elm)->field.tqe_prev = (head)->tqh_last; \ + *(head)->tqh_last = (elm); \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_HEAD(head); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + +#define TAILQ_LAST(head, headname) \ + (*(((struct headname *)((head)->tqh_last))->tqh_last)) + +/* + * The FAST function is fast in that it causes no data access other + * then the access to the head. The standard LAST function above + * will cause a data access of both the element you want and + * the previous element. FAST is very useful for instances when + * you may want to prefetch the last data element. + */ +#define TAILQ_LAST_FAST(head, type, field) \ + (TAILQ_EMPTY(head) ? NULL : __containerof((head)->tqh_last, QUEUE_TYPEOF(type), field.tqe_next)) + +#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) + +#define TAILQ_PREV(elm, headname, field) \ + (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) + +#define TAILQ_REMOVE(head, elm, field) do { \ + QMD_SAVELINK(oldnext, (elm)->field.tqe_next); \ + QMD_SAVELINK(oldprev, (elm)->field.tqe_prev); \ + QMD_TAILQ_CHECK_NEXT(elm, field); \ + QMD_TAILQ_CHECK_PREV(elm, field); \ + if ((TAILQ_NEXT((elm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + (elm)->field.tqe_prev; \ + else { \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + QMD_TRACE_HEAD(head); \ + } \ + *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ + TRASHIT(*oldnext); \ + TRASHIT(*oldprev); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + +#define TAILQ_SWAP(head1, head2, type, field) do { \ + QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first; \ + QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last; \ + (head1)->tqh_first = (head2)->tqh_first; \ + (head1)->tqh_last = (head2)->tqh_last; \ + (head2)->tqh_first = swap_first; \ + (head2)->tqh_last = swap_last; \ + if ((swap_first = (head1)->tqh_first) != NULL) \ + swap_first->field.tqe_prev = &(head1)->tqh_first; \ + else \ + (head1)->tqh_last = &(head1)->tqh_first; \ + if ((swap_first = (head2)->tqh_first) != NULL) \ + swap_first->field.tqe_prev = &(head2)->tqh_first; \ + else \ + (head2)->tqh_last = &(head2)->tqh_first; \ +} while (0) + +#endif /* !_SYS_QUEUE_H_ */ diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h new file mode 100644 index 000000000..f4fac96b8 --- /dev/null +++ b/src/common/tusb_common.h @@ -0,0 +1,220 @@ +/**************************************************************************/
+/*!
+ @file tusb_common.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup Group_Common
+ * \defgroup Group_CommonH common.h
+ * @{ */
+
+#ifndef _TUSB_COMMON_H_
+#define _TUSB_COMMON_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// INCLUDES
+//--------------------------------------------------------------------+
+
+//------------- Standard Header -------------//
+#include <stdbool.h>
+#include <stdint.h>
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+
+//------------- TUSB Option Header -------------//
+#include "tusb_option.h"
+
+//------------- Common Header -------------//
+#include "tusb_compiler.h"
+#include "tusb_verify.h"
+#include "binary.h"
+#include "tusb_error.h"
+#include "tusb_timeout.h"
+#include "tusb_types.h"
+
+//--------------------------------------------------------------------+
+// MACROS
+//--------------------------------------------------------------------+
+#define TU_ARRAY_SZIE(_arr) ( sizeof(_arr) / sizeof(_arr[0]) )
+#define TU_MIN(_x, _y) ( (_x) < (_y) ) ? (_x) : (_y) )
+#define TU_MAX(_x, _y) ( (_x) > (_y) ) ? (_x) : (_y) )
+
+#define U16_HIGH_U8(u16) ((uint8_t) (((u16) >> 8) & 0x00ff))
+#define U16_LOW_U8(u16) ((uint8_t) ((u16) & 0x00ff))
+#define U16_TO_U8S_BE(u16) U16_HIGH_U8(u16), U16_LOW_U8(u16)
+#define U16_TO_U8S_LE(u16) U16_LOW_U8(u16), U16_HIGH_U8(u16)
+
+#define U32_B1_U8(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB
+#define U32_B2_U8(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff))
+#define U32_B3_U8(u32) ((uint8_t) (((u32) >> 8) & 0x000000ff))
+#define U32_B4_U8(u32) ((uint8_t) ((u32) & 0x000000ff)) // LSB
+
+#define U32_TO_U8S_BE(u32) U32_B1_U8(u32), U32_B2_U8(u32), U32_B3_U8(u32), U32_B4_U8(u32)
+#define U32_TO_U8S_LE(u32) U32_B4_U8(u32), U32_B3_U8(u32), U32_B2_U8(u32), U32_B1_U8(u32)
+
+//------------- Endian Conversion -------------//
+#define ENDIAN_BE(u32) \
+ (uint32_t) ( (((u32) & 0xFF) << 24) | (((u32) & 0xFF00) << 8) | (((u32) >> 8) & 0xFF00) | (((u32) >> 24) & 0xFF) )
+
+#define ENDIAN_BE16(le16) ((uint16_t) ((U16_LOW_U8(le16) << 8) | U16_HIGH_U8(le16)) )
+
+#ifndef __n2be_16
+#define __n2be_16(u16) ((uint16_t) ((U16_LOW_U8(u16) << 8) | U16_HIGH_U8(u16)) )
+#define __be2n_16(u16) __n2be_16(u16)
+#endif
+
+
+// for declaration of reserved field, make use of _TU_COUNTER_
+#define TU_RESERVED XSTRING_CONCAT_(reserved, _TU_COUNTER_)
+
+/*------------------------------------------------------------------*/
+/* 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 VA_ARGS_NUM_
+
+#define VA_ARGS_NUM_(...) NARG_(_0, ##__VA_ARGS__,_RSEQ_N())
+#define 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
+
+//--------------------------------------------------------------------+
+// INLINE FUNCTION
+//--------------------------------------------------------------------+
+#define tu_memclr(buffer, size) memset((buffer), 0, (size))
+#define tu_varclr(_var) tu_memclr(_var, sizeof(*(_var)))
+
+static inline bool tu_mem_test_zero (void const* buffer, uint32_t size)
+{
+ uint8_t const* p_mem = (uint8_t const*) buffer;
+ for(uint32_t i=0; i<size; i++) if (p_mem[i] != 0) return false;
+ return true;
+}
+
+
+//------------- Conversion -------------//
+static inline uint32_t tu_u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4)
+{
+ return ( ((uint32_t) b1) << 24) + ( ((uint32_t) b2) << 16) + ( ((uint32_t) b3) << 8) + b4;
+}
+
+static inline uint8_t tu_u16_high(uint16_t u16)
+{
+ return (uint8_t) ( ((uint16_t) (u16 >> 8)) & 0x00ff);
+}
+
+static inline uint8_t tu_u16_low(uint16_t u16)
+{
+ return (uint8_t) (u16 & 0x00ff);
+}
+
+static inline uint16_t tu_u16_le2be(uint16_t u16)
+{
+ return ((uint16_t)(tu_u16_low(u16) << 8)) | tu_u16_high(u16);
+}
+
+// Min
+static inline uint8_t tu_min8(uint8_t x, uint8_t y) { return (x < y) ? x : y; }
+static inline uint16_t tu_min16(uint16_t x, uint16_t y) { return (x < y) ? x : y; }
+static inline uint32_t tu_min32(uint32_t x, uint32_t y) { return (x < y) ? x : y; }
+
+// Max
+static inline uint8_t tu_max8(uint8_t x, uint8_t y) { return (x > y) ? x : y; }
+static inline uint16_t tu_max16(uint16_t x, uint16_t y) { return (x > y) ? x : y; }
+static inline uint32_t tu_max32(uint32_t x, uint32_t y) { return (x > y) ? x : y; }
+
+// Align
+static inline uint32_t tu_align32 (uint32_t value) { return (value & 0xFFFFFFE0UL); }
+static inline uint32_t tu_align16 (uint32_t value) { return (value & 0xFFFFFFF0UL); }
+static inline uint32_t tu_align_n (uint32_t alignment, uint32_t value) { return value & ((uint32_t) ~(alignment-1)); }
+static inline uint32_t tu_align4k (uint32_t value) { return (value & 0xFFFFF000UL); }
+
+static inline uint32_t tu_offset4k(uint32_t value) { return (value & 0xFFFUL); }
+
+//------------- Mathematics -------------//
+static inline uint32_t tu_abs(int32_t value)
+{
+ return (value < 0) ? (-value) : value;
+}
+
+/// inclusive range checking
+static inline bool tu_within(uint32_t lower, uint32_t value, uint32_t upper)
+{
+ return (lower <= value) && (value <= upper);
+}
+
+// TODO use clz
+static inline uint8_t tu_log2(uint32_t value)
+{
+ uint8_t result = 0; // log2 of a value is its MSB's position
+
+ while (value >>= 1)
+ {
+ result++;
+ }
+ return result;
+}
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_COMMON_H_ */
+
+/** @} */
diff --git a/src/common/tusb_compiler.h b/src/common/tusb_compiler.h new file mode 100644 index 000000000..933d76043 --- /dev/null +++ b/src/common/tusb_compiler.h @@ -0,0 +1,83 @@ +/**************************************************************************/
+/*!
+ @file compiler.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup Group_Common
+ * \defgroup Group_Compiler Compiler
+ * \brief Group_Compiler brief
+ * @{ */
+
+#ifndef _TUSB_COMPILER_H_
+#define _TUSB_COMPILER_H_
+
+#define STRING_(x) #x ///< stringify without expand
+#define XSTRING_(x) STRING_(x) ///< expand then stringify
+#define STRING_CONCAT_(a, b) a##b ///< concat without expand
+#define XSTRING_CONCAT_(a, b) STRING_CONCAT_(a, b) ///< expand then concat
+
+#if defined __COUNTER__ && __COUNTER__ != __COUNTER__
+ #define _TU_COUNTER_ __COUNTER__
+#else
+ #define _TU_COUNTER_ __LINE__
+#endif
+
+//--------------------------------------------------------------------+
+// Compile-time Assert (use TU_VERIFY_STATIC to avoid name conflict)
+//--------------------------------------------------------------------+
+#if __STDC_VERSION__ >= 201112L
+ #define TU_VERIFY_STATIC _Static_assert
+#else
+ #define TU_VERIFY_STATIC(const_expr, _mess) enum { XSTRING_CONCAT_(_verify_static_, _TU_COUNTER_) = 1/(!!(const_expr)) }
+#endif
+
+// allow debugger to watch any module-wide variables anywhere
+#if CFG_TUSB_DEBUG
+#define STATIC_VAR
+#else
+#define STATIC_VAR static
+#endif
+
+
+#if defined(__GNUC__)
+ #include "compiler/tusb_compiler_gcc.h"
+#elif defined __ICCARM__
+ #include "compiler/tusb_compiler_iar.h"
+#endif
+
+#endif /* _TUSB_COMPILER_H_ */
+
+/// @}
diff --git a/src/common/tusb_error.h b/src/common/tusb_error.h new file mode 100644 index 000000000..677fc44e4 --- /dev/null +++ b/src/common/tusb_error.h @@ -0,0 +1,117 @@ +/**************************************************************************/
+/*!
+ @file tusb_error.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup Group_Common
+ * \defgroup Group_Error Error Codes
+ * @{ */
+
+#ifndef _TUSB_ERRORS_H_
+#define _TUSB_ERRORS_H_
+
+#include "tusb_option.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#define ERROR_ENUM(x) x,
+#define ERROR_STRING(x) #x,
+
+#define ERROR_TABLE(ENTRY) \
+ ENTRY(TUSB_ERROR_NONE )\
+ ENTRY(TUSB_ERROR_INVALID_PARA )\
+ ENTRY(TUSB_ERROR_DEVICE_NOT_READY )\
+ ENTRY(TUSB_ERROR_INTERFACE_IS_BUSY )\
+ ENTRY(TUSB_ERROR_HCD_FAILED )\
+ ENTRY(TUSB_ERROR_HCD_OPEN_PIPE_FAILED )\
+ ENTRY(TUSB_ERROR_USBH_MOUNT_DEVICE_NOT_RESPOND )\
+ ENTRY(TUSB_ERROR_USBH_MOUNT_CONFIG_DESC_TOO_LONG )\
+ ENTRY(TUSB_ERROR_USBH_DESCRIPTOR_CORRUPTED )\
+ ENTRY(TUSB_ERROR_USBH_XFER_STALLED )\
+ ENTRY(TUSB_ERROR_USBH_XFER_FAILED )\
+ ENTRY(TUSB_ERROR_OSAL_TIMEOUT )\
+ ENTRY(TUSB_ERROR_OSAL_WAITING ) /* only used by OSAL_NONE in the subtask */ \
+ ENTRY(TUSB_ERROR_OSAL_TASK_FAILED )\
+ ENTRY(TUSB_ERROR_OSAL_QUEUE_FAILED )\
+ ENTRY(TUSB_ERROR_OSAL_SEMAPHORE_FAILED )\
+ ENTRY(TUSB_ERROR_OSAL_MUTEX_FAILED )\
+ ENTRY(TUSB_ERROR_EHCI_NOT_ENOUGH_QTD )\
+ ENTRY(TUSB_ERROR_HIDD_DESCRIPTOR_INTERFACE )\
+ ENTRY(TUSB_ERROR_HIDH_NOT_SUPPORTED_PROTOCOL )\
+ ENTRY(TUSB_ERROR_HIDH_NOT_SUPPORTED_SUBCLASS )\
+ ENTRY(TUSB_ERROR_CDC_UNSUPPORTED_SUBCLASS )\
+ ENTRY(TUSB_ERROR_CDC_UNSUPPORTED_PROTOCOL )\
+ ENTRY(TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED )\
+ ENTRY(TUSB_ERROR_MSC_UNSUPPORTED_PROTOCOL )\
+ ENTRY(TUSB_ERROR_MSCH_UNKNOWN_SCSI_COMMAND )\
+ ENTRY(TUSB_ERROR_MSCH_DEVICE_NOT_MOUNTED )\
+ ENTRY(TUSB_ERROR_HUB_FEATURE_NOT_SUPPORTED )\
+ ENTRY(TUSB_ERROR_DESCRIPTOR_CORRUPTED )\
+ ENTRY(TUSB_ERROR_DCD_FAILED )\
+ ENTRY(TUSB_ERROR_DCD_CONTROL_REQUEST_NOT_SUPPORT )\
+ ENTRY(TUSB_ERROR_DCD_NOT_ENOUGH_QTD )\
+ ENTRY(TUSB_ERROR_DCD_OPEN_PIPE_FAILED )\
+ ENTRY(TUSB_ERROR_DCD_EDPT_XFER )\
+ ENTRY(TUSB_ERROR_NOT_SUPPORTED_YET )\
+ ENTRY(TUSB_ERROR_USBD_DEVICE_NOT_CONFIGURED )\
+ ENTRY(TUSB_ERROR_NOT_ENOUGH_MEMORY )\
+ ENTRY(TUSB_ERROR_FAILED )\
+ \
+ ENTRY(ERR_TUD_INVALID_DESCRIPTOR) \
+ ENTRY(ERR_TUD_EDPT_OPEN_FAILED) \
+
+
+/// \brief Error Code returned
+typedef enum
+{
+ ERROR_TABLE(ERROR_ENUM)
+ TUSB_ERROR_COUNT
+}tusb_error_t;
+
+#if CFG_TUSB_DEBUG
+/// Enum to String for debugging purposes. Only available if \ref CFG_TUSB_DEBUG > 0
+extern char const* const tusb_strerr[TUSB_ERROR_COUNT];
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_ERRORS_H_ */
+
+/** @} */
diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c new file mode 100644 index 000000000..2acd4b696 --- /dev/null +++ b/src/common/tusb_fifo.c @@ -0,0 +1,280 @@ +/**************************************************************************/
+/*!
+ @file tusb_fifo.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2018, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+ */
+/**************************************************************************/
+
+#include <string.h>
+
+#include "osal/osal.h"
+#include "tusb_fifo.h"
+
+// implement mutex lock and unlock
+#if CFG_FIFO_MUTEX
+
+static void tu_fifo_lock(tu_fifo_t *f)
+{
+ if (f->mutex)
+ {
+ uint32_t err;
+ (void) err;
+ osal_mutex_lock(f->mutex, OSAL_TIMEOUT_WAIT_FOREVER, &err);
+ }
+}
+
+static void tu_fifo_unlock(tu_fifo_t *f)
+{
+ if (f->mutex)
+ {
+ osal_mutex_unlock(f->mutex);
+ }
+}
+
+#else
+
+#define tu_fifo_lock(_ff)
+#define tu_fifo_unlock(_ff)
+
+#endif
+
+bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable)
+{
+ tu_fifo_lock(f);
+
+ f->buffer = (uint8_t*) buffer;
+ f->depth = depth;
+ f->item_size = item_size;
+ f->overwritable = overwritable;
+
+ f->rd_idx = f->wr_idx = f->count = 0;
+
+ tu_fifo_unlock(f);
+
+ return true;
+}
+
+
+/******************************************************************************/
+/*!
+ @brief Read one byte out of the RX buffer.
+
+ This function will return the byte located at the array index of the
+ read pointer, and then increment the read pointer index. If the read
+ pointer exceeds the maximum buffer size, it will roll over to zero.
+
+ @param[in] f
+ Pointer to the FIFO buffer to manipulate
+ @param[in] p_buffer
+ Pointer to the place holder for data read from the buffer
+
+ @returns TRUE if the queue is not empty
+*/
+/******************************************************************************/
+bool tu_fifo_read(tu_fifo_t* f, void * p_buffer)
+{
+ if( tu_fifo_empty(f) ) return false;
+
+ tu_fifo_lock(f);
+
+ memcpy(p_buffer,
+ f->buffer + (f->rd_idx * f->item_size),
+ f->item_size);
+ f->rd_idx = (f->rd_idx + 1) % f->depth;
+ f->count--;
+
+ tu_fifo_unlock(f);
+
+ return true;
+}
+
+/******************************************************************************/
+/*!
+ @brief This function will read n elements into the array index specified by
+ the write pointer and increment the write index. If the write index
+ exceeds the max buffer size, then it will roll over to zero.
+
+ @param[in] f
+ Pointer to the FIFO buffer to manipulate
+ @param[in] p_data
+ The pointer to data location
+ @param[in] count
+ Number of element that buffer can afford
+
+ @returns number of items read from the FIFO
+*/
+/******************************************************************************/
+uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count)
+{
+ if( tu_fifo_empty(f) ) return 0;
+
+ /* Limit up to fifo's count */
+ if ( count > f->count ) count = f->count;
+
+ /* Could copy up to 2 portions marked as 'x' if queue is wrapped around
+ * case 1: ....RxxxxW.......
+ * case 2: xxxxxW....Rxxxxxx
+ */
+// uint16_t index2upper = tu_min16(count, f->count-f->rd_idx);
+
+ uint8_t* p_buf = (uint8_t*) p_buffer;
+ uint16_t len = 0;
+ while( (len < count) && tu_fifo_read(f, p_buf) )
+ {
+ len++;
+ p_buf += f->item_size;
+ }
+
+ return len;
+}
+
+/******************************************************************************/
+/*!
+ @brief Reads one item without removing it from the FIFO
+
+ @param[in] f
+ Pointer to the FIFO buffer to manipulate
+ @param[in] pos
+ Position to read from in the FIFO buffer
+ @param[in] p_buffer
+ Pointer to the place holder for data read from the buffer
+
+ @returns TRUE if the queue is not empty
+*/
+/******************************************************************************/
+bool tu_fifo_peek_at(tu_fifo_t* f, uint16_t pos, void * p_buffer)
+{
+ if ( pos >= f->count ) return false;
+
+ // rd_idx is pos=0
+ uint16_t index = (f->rd_idx + pos) % f->depth;
+ memcpy(p_buffer,
+ f->buffer + (index * f->item_size),
+ f->item_size);
+
+ return true;
+}
+
+/******************************************************************************/
+/*!
+ @brief Write one element into the RX buffer.
+
+ This function will write one element into the array index specified by
+ the write pointer and increment the write index. If the write index
+ exceeds the max buffer size, then it will roll over to zero.
+
+ @param[in] f
+ Pointer to the FIFO buffer to manipulate
+ @param[in] p_data
+ The byte to add to the FIFO
+
+ @returns TRUE if the data was written to the FIFO (overwrittable
+ FIFO will always return TRUE)
+*/
+/******************************************************************************/
+bool tu_fifo_write (tu_fifo_t* f, const void * p_data)
+{
+ if ( tu_fifo_full(f) && !f->overwritable ) return false;
+
+ tu_fifo_lock(f);
+
+ memcpy( f->buffer + (f->wr_idx * f->item_size),
+ p_data,
+ f->item_size);
+
+ f->wr_idx = (f->wr_idx + 1) % f->depth;
+
+ if (tu_fifo_full(f))
+ {
+ f->rd_idx = f->wr_idx; // keep the full state (rd == wr && len = size)
+ }
+ else
+ {
+ f->count++;
+ }
+
+ tu_fifo_unlock(f);
+
+ return true;
+}
+
+/******************************************************************************/
+/*!
+ @brief This function will write n elements into the array index specified by
+ the write pointer and increment the write index. If the write index
+ exceeds the max buffer size, then it will roll over to zero.
+
+ @param[in] f
+ Pointer to the FIFO buffer to manipulate
+ @param[in] p_data
+ The pointer to data to add to the FIFO
+ @param[in] count
+ Number of element
+ @return Number of written elements
+*/
+/******************************************************************************/
+uint16_t tu_fifo_write_n (tu_fifo_t* f, const void * p_data, uint16_t count)
+{
+ if ( count == 0 ) return 0;
+
+ uint8_t const* p_buf = (uint8_t const*) p_data;
+
+ uint16_t len = 0;
+ while( (len < count) && tu_fifo_write(f, p_buf) )
+ {
+ len++;
+ p_buf += f->item_size;
+ }
+
+ return len;
+}
+
+/******************************************************************************/
+/*!
+ @brief Clear the fifo read and write pointers and set length to zero
+
+ @param[in] f
+ Pointer to the FIFO buffer to manipulate
+*/
+/******************************************************************************/
+bool tu_fifo_clear(tu_fifo_t *f)
+{
+ tu_fifo_lock(f);
+
+ f->rd_idx = f->wr_idx = f->count = 0;
+
+ tu_fifo_unlock(f);
+
+ return true;
+}
diff --git a/src/common/tusb_fifo.h b/src/common/tusb_fifo.h new file mode 100644 index 000000000..e88c2ac6d --- /dev/null +++ b/src/common/tusb_fifo.h @@ -0,0 +1,143 @@ +/**************************************************************************/
+/*!
+ @file tusb_fifo.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2018, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup Group_Common
+ * \defgroup group_fifo fifo
+ * @{ */
+
+#ifndef _TUSB_FIFO_H_
+#define _TUSB_FIFO_H_
+
+// mutex is only needed for RTOS
+// for OS None, we don't get preempted
+#define CFG_FIFO_MUTEX (CFG_TUSB_OS != OPT_OS_NONE)
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#if CFG_FIFO_MUTEX
+#define tu_fifo_mutex_t osal_mutex_t
+#endif
+
+
+/** \struct tu_fifo_t
+ * \brief Simple Circular FIFO
+ */
+typedef struct
+{
+ uint8_t* buffer ; ///< buffer pointer
+ uint16_t depth ; ///< max items
+ uint16_t item_size ; ///< size of each item
+ bool overwritable ;
+
+ volatile uint16_t count ; ///< number of items in queue
+ volatile uint16_t wr_idx ; ///< write pointer
+ volatile uint16_t rd_idx ; ///< read pointer
+
+#if CFG_FIFO_MUTEX
+ tu_fifo_mutex_t mutex;
+#endif
+
+} tu_fifo_t;
+
+#define TU_FIFO_DEF(_name, _depth, _type, _overwritable) \
+ uint8_t _name##_buf[_depth*sizeof(_type)]; \
+ tu_fifo_t _name = { \
+ .buffer = _name##_buf, \
+ .depth = _depth, \
+ .item_size = sizeof(_type), \
+ .overwritable = _overwritable, \
+ }
+
+bool tu_fifo_clear(tu_fifo_t *f);
+bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable);
+
+#if CFG_FIFO_MUTEX
+static inline void tu_fifo_config_mutex(tu_fifo_t *f, tu_fifo_mutex_t mutex_hdl)
+{
+ f->mutex = mutex_hdl;
+}
+#endif
+
+bool tu_fifo_write (tu_fifo_t* f, void const * p_data);
+uint16_t tu_fifo_write_n (tu_fifo_t* f, void const * p_data, uint16_t count);
+
+bool tu_fifo_read (tu_fifo_t* f, void * p_buffer);
+uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count);
+
+bool tu_fifo_peek_at (tu_fifo_t* f, uint16_t pos, void * p_buffer);
+
+static inline bool tu_fifo_peek(tu_fifo_t* f, void * p_buffer)
+{
+ return tu_fifo_peek_at(f, 0, p_buffer);
+}
+
+static inline bool tu_fifo_empty(tu_fifo_t* f)
+{
+ return (f->count == 0);
+}
+
+static inline bool tu_fifo_full(tu_fifo_t* f)
+{
+ return (f->count == f->depth);
+}
+
+static inline uint16_t tu_fifo_count(tu_fifo_t* f)
+{
+ return f->count;
+}
+
+static inline uint16_t tu_fifo_remaining(tu_fifo_t* f)
+{
+ return f->depth - f->count;
+}
+
+static inline uint16_t tu_fifo_depth(tu_fifo_t* f)
+{
+ return f->depth;
+}
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_FIFO_H_ */
diff --git a/src/common/tusb_timeout.h b/src/common/tusb_timeout.h new file mode 100644 index 000000000..9d80f5fe7 --- /dev/null +++ b/src/common/tusb_timeout.h @@ -0,0 +1,98 @@ +/**************************************************************************/
+/*!
+ @file tusb_timeout.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup Group_Common Common Files
+ * \defgroup Group_TimeoutTimer timeout timer
+ * @{ */
+
+
+#ifndef _TUSB_TIMEOUT_H_
+#define _TUSB_TIMEOUT_H_
+
+#include "tusb_compiler.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ uint32_t start;
+ uint32_t interval;
+}tu_timeout_t;
+
+extern uint32_t tusb_hal_millis(void);
+
+static inline void tu_timeout_set(tu_timeout_t* tt, uint32_t msec)
+{
+ tt->interval = msec;
+ tt->start = tusb_hal_millis();
+}
+
+static inline bool tu_timeout_expired(tu_timeout_t* tt)
+{
+ return ( tusb_hal_millis() - tt->start ) >= tt->interval;
+}
+
+// For used with periodic event to prevent drift
+static inline void tu_timeout_reset(tu_timeout_t* tt)
+{
+ tt->start += tt->interval;
+}
+
+static inline void tu_timeout_restart(tu_timeout_t* tt)
+{
+ tt->start = tusb_hal_millis();
+}
+
+
+static inline void tu_timeout_wait(uint32_t msec)
+{
+ tu_timeout_t tt;
+ tu_timeout_set(&tt, msec);
+
+ // blocking delay
+ while ( !tu_timeout_expired(&tt) ) { }
+}
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_TIMEOUT_H_ */
+
+/** @} */
diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h new file mode 100644 index 000000000..6f0167898 --- /dev/null +++ b/src/common/tusb_types.h @@ -0,0 +1,428 @@ +/**************************************************************************/
+/*!
+ @file tusb_types.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_usb_definitions
+ * \defgroup USBDef_Type USB Types
+ * @{ */
+
+#ifndef _TUSB_TYPES_H_
+#define _TUSB_TYPES_H_
+
+#include <stdbool.h>
+#include <stdint.h>
+#include "tusb_compiler.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/*------------------------------------------------------------------*/
+/* CONSTANTS
+ *------------------------------------------------------------------*/
+
+/// defined base on EHCI specs value for Endpoint Speed
+typedef enum
+{
+ TUSB_SPEED_FULL = 0,
+ TUSB_SPEED_LOW ,
+ TUSB_SPEED_HIGH
+}tusb_speed_t;
+
+/// defined base on USB Specs Endpoint's bmAttributes
+typedef enum
+{
+ TUSB_XFER_CONTROL = 0 ,
+ TUSB_XFER_ISOCHRONOUS ,
+ TUSB_XFER_BULK ,
+ TUSB_XFER_INTERRUPT
+}tusb_xfer_type_t;
+
+typedef enum
+{
+ TUSB_DIR_OUT = 0,
+ TUSB_DIR_IN = 1,
+
+ TUSB_DIR_IN_MASK = 0x80
+}tusb_dir_t;
+
+
+/// USB Descriptor Types (section 9.4 table 9-5)
+typedef enum
+{
+ TUSB_DESC_DEVICE = 0x01 ,
+ TUSB_DESC_CONFIGURATION = 0x02 ,
+ TUSB_DESC_STRING = 0x03 ,
+ TUSB_DESC_INTERFACE = 0x04 ,
+ TUSB_DESC_ENDPOINT = 0x05 ,
+ TUSB_DESC_DEVICE_QUALIFIER = 0x06 ,
+ TUSB_DESC_OTHER_SPEED_CONFIG = 0x07 ,
+ TUSB_DESC_INTERFACE_POWER = 0x08 ,
+ TUSB_DESC_OTG = 0x09 ,
+ TUSB_DESC_DEBUG = 0x0A ,
+ TUSB_DESC_INTERFACE_ASSOCIATION = 0x0B ,
+ TUSB_DESC_CLASS_SPECIFIC = 0x24
+}tusb_desc_type_t;
+
+typedef enum
+{
+ TUSB_REQ_GET_STATUS =0 , ///< 0
+ TUSB_REQ_CLEAR_FEATURE , ///< 1
+ TUSB_REQ_RESERVED , ///< 2
+ TUSB_REQ_SET_FEATURE , ///< 3
+ TUSB_REQ_RESERVED2 , ///< 4
+ TUSB_REQ_SET_ADDRESS , ///< 5
+ TUSB_REQ_GET_DESCRIPTOR , ///< 6
+ TUSB_REQ_SET_DESCRIPTOR , ///< 7
+ TUSB_REQ_GET_CONFIGURATION , ///< 8
+ TUSB_REQ_SET_CONFIGURATION , ///< 9
+ TUSB_REQ_GET_INTERFACE , ///< 10
+ TUSB_REQ_SET_INTERFACE , ///< 11
+ TUSB_REQ_SYNCH_FRAME ///< 12
+}tusb_request_code_t;
+
+typedef enum
+{
+ TUSB_REQ_TYPE_STANDARD = 0,
+ TUSB_REQ_TYPE_CLASS,
+ TUSB_REQ_TYPE_VENDOR
+} tusb_request_type_t;
+
+typedef enum
+{
+ TUSB_REQ_RCPT_DEVICE =0,
+ TUSB_REQ_RCPT_INTERFACE,
+ TUSB_REQ_RCPT_ENDPOINT,
+ TUSB_REQ_RCPT_OTHER
+} tusb_request_recipient_t;
+
+typedef enum
+{
+ TUSB_CLASS_UNSPECIFIED = 0 , ///< 0
+ TUSB_CLASS_AUDIO = 1 , ///< 1
+ TUSB_CLASS_CDC = 2 , ///< 2
+ TUSB_CLASS_HID = 3 , ///< 3
+ TUSB_CLASS_RESERVED_4 = 4 , ///< 4
+ TUSB_CLASS_PHYSICAL = 5 , ///< 5
+ TUSB_CLASS_IMAGE = 6 , ///< 6
+ TUSB_CLASS_PRINTER = 7 , ///< 7
+ TUSB_CLASS_MSC = 8 , ///< 8
+ TUSB_CLASS_HUB = 9 , ///< 9
+ TUSB_CLASS_CDC_DATA = 10 , ///< 10
+ TUSB_CLASS_SMART_CARD = 11 , ///< 11
+ TUSB_CLASS_RESERVED_12 = 12 , ///< 12
+ TUSB_CLASS_CONTENT_SECURITY = 13 , ///< 13
+ TUSB_CLASS_VIDEO = 14 , ///< 14
+ TUSB_CLASS_PERSONAL_HEALTHCARE = 15 , ///< 15
+ TUSB_CLASS_AUDIO_VIDEO = 16 , ///< 16
+
+ TUSB_CLASS_MAPPED_INDEX_START = 17 , // TODO Map DIAGNOSTIC, WIRELESS_CONTROLLER, MISC, VENDOR_SPECIFIC to this to minimize the array
+
+ TUSB_CLASS_DIAGNOSTIC = 0xDC ,
+ TUSB_CLASS_WIRELESS_CONTROLLER = 0xE0 ,
+ TUSB_CLASS_MISC = 0xEF ,
+ TUSB_CLASS_APPLICATION_SPECIFIC = 0xFE ,
+ TUSB_CLASS_VENDOR_SPECIFIC = 0xFF
+}tusb_class_code_t;
+
+typedef enum
+{
+ MISC_SUBCLASS_COMMON = 2
+}misc_subclass_type_t;
+
+typedef enum
+{
+ MISC_PROTOCOL_IAD = 1
+}misc_protocol_type_t;
+
+enum {
+ TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP = BIT_(5),
+ TUSB_DESC_CONFIG_ATT_SELF_POWER = BIT_(6),
+ TUSB_DESC_CONFIG_ATT_BUS_POWER = BIT_(7)
+};
+
+#define TUSB_DESC_CONFIG_POWER_MA(x) ((x)/2)
+
+/// Device State
+typedef enum
+{
+ TUSB_DEVICE_STATE_UNPLUG = 0 ,
+ TUSB_DEVICE_STATE_CONFIGURED ,
+ TUSB_DEVICE_STATE_SUSPENDED ,
+}tusb_device_state_t;
+
+typedef enum
+{
+ XFER_RESULT_SUCCESS,
+ XFER_RESULT_FAILED,
+ XFER_RESULT_STALLED,
+}xfer_result_t;
+
+enum
+{
+ DESC_OFFSET_LEN = 0,
+ DESC_OFFSET_TYPE = 1
+};
+
+enum
+{
+ INTERFACE_INVALID_NUMBER = 0xff
+};
+
+//--------------------------------------------------------------------+
+// STANDARD DESCRIPTORS
+//--------------------------------------------------------------------+
+
+/// USB Standard Device Descriptor (section 9.6.1, table 9-8)
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< DEVICE Descriptor Type.
+ uint16_t bcdUSB ; ///< BUSB Specification Release Number in Binary-Coded Decimal (i.e., 2.10 is 210H). This field identifies the release of the USB Specification with which the device and its descriptors are compliant.
+
+ uint8_t bDeviceClass ; ///< Class code (assigned by the USB-IF). \li If this field is reset to zero, each interface within a configuration specifies its own class information and the various interfaces operate independently. \li If this field is set to a value between 1 and FEH, the device supports different class specifications on different interfaces and the interfaces may not operate independently. This value identifies the class definition used for the aggregate interfaces. \li If this field is set to FFH, the device class is vendor-specific.
+ uint8_t bDeviceSubClass ; ///< Subclass code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass field. \li If the bDeviceClass field is reset to zero, this field must also be reset to zero. \li If the bDeviceClass field is not set to FFH, all values are reserved for assignment by the USB-IF.
+ uint8_t bDeviceProtocol ; ///< Protocol code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass and the bDeviceSubClass fields. If a device supports class-specific protocols on a device basis as opposed to an interface basis, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use class-specific protocols on a device basis. However, it may use classspecific protocols on an interface basis. \li If this field is set to FFH, the device uses a vendor-specific protocol on a device basis.
+ uint8_t bMaxPacketSize0 ; ///< Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid). For HS devices is fixed to 64.
+
+ uint16_t idVendor ; ///< Vendor ID (assigned by the USB-IF).
+ uint16_t idProduct ; ///< Product ID (assigned by the manufacturer).
+ uint16_t bcdDevice ; ///< Device release number in binary-coded decimal.
+ uint8_t iManufacturer ; ///< Index of string descriptor describing manufacturer.
+ uint8_t iProduct ; ///< Index of string descriptor describing product.
+ uint8_t iSerialNumber ; ///< Index of string descriptor describing the device's serial number.
+
+ uint8_t bNumConfigurations ; ///< Number of possible configurations.
+} tusb_desc_device_t;
+
+/// USB Standard Configuration Descriptor (section 9.6.1 table 9-10) */
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes
+ uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type
+ uint16_t wTotalLength ; ///< Total length of data returned for this configuration. Includes the combined length of all descriptors (configuration, interface, endpoint, and class- or vendor-specific) returned for this configuration.
+
+ uint8_t bNumInterfaces ; ///< Number of interfaces supported by this configuration
+ uint8_t bConfigurationValue ; ///< Value to use as an argument to the SetConfiguration() request to select this configuration.
+ uint8_t iConfiguration ; ///< Index of string descriptor describing this configuration
+ uint8_t bmAttributes ; ///< Configuration characteristics \n D7: Reserved (set to one)\n D6: Self-powered \n D5: Remote Wakeup \n D4...0: Reserved (reset to zero) \n D7 is reserved and must be set to one for historical reasons. \n A device configuration that uses power from the bus and a local source reports a non-zero value in bMaxPower to indicate the amount of bus power required and sets D6. The actual power source at runtime may be determined using the GetStatus(DEVICE) request (see USB 2.0 spec Section 9.4.5). \n If a device configuration supports remote wakeup, D5 is set to one.
+ uint8_t bMaxPower ; ///< Maximum power consumption of the USB device from the bus in this specific configuration when the device is fully operational. Expressed in 2 mA units (i.e., 50 = 100 mA).
+} tusb_desc_configuration_t;
+
+/// USB Standard Interface Descriptor (section 9.6.1 table 9-12)
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes
+ uint8_t bDescriptorType ; ///< INTERFACE Descriptor Type
+
+ uint8_t bInterfaceNumber ; ///< Number of this interface. Zero-based value identifying the index in the array of concurrent interfaces supported by this configuration.
+ uint8_t bAlternateSetting ; ///< Value used to select this alternate setting for the interface identified in the prior field
+ uint8_t bNumEndpoints ; ///< Number of endpoints used by this interface (excluding endpoint zero). If this value is zero, this interface only uses the Default Control Pipe.
+ uint8_t bInterfaceClass ; ///< Class code (assigned by the USB-IF). \li A value of zero is reserved for future standardization. \li If this field is set to FFH, the interface class is vendor-specific. \li All other values are reserved for assignment by the USB-IF.
+ uint8_t bInterfaceSubClass ; ///< Subclass code (assigned by the USB-IF). \n These codes are qualified by the value of the bInterfaceClass field. \li If the bInterfaceClass field is reset to zero, this field must also be reset to zero. \li If the bInterfaceClass field is not set to FFH, all values are reserved for assignment by the USB-IF.
+ uint8_t bInterfaceProtocol ; ///< Protocol code (assigned by the USB). \n These codes are qualified by the value of the bInterfaceClass and the bInterfaceSubClass fields. If an interface supports class-specific requests, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use a class-specific protocol on this interface. \li If this field is set to FFH, the device uses a vendor-specific protocol for this interface.
+ uint8_t iInterface ; ///< Index of string descriptor describing this interface
+} tusb_desc_interface_t;
+
+/// USB Standard Endpoint Descriptor (section 9.6.1 table 9-13)
+typedef struct ATTR_PACKED
+{
+ 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.
+
+ struct ATTR_PACKED {
+ uint8_t xfer : 2;
+ uint8_t sync : 2;
+ uint8_t usage : 2;
+ 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.
+
+ struct ATTR_PACKED {
+ 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 : 0;
+ }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.
+} tusb_desc_endpoint_t;
+
+/// USB Other Speed Configuration Descriptor (section 9.6.1 table 9-11)
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of descriptor
+ uint8_t bDescriptorType ; ///< Other_speed_Configuration Type
+ uint16_t wTotalLength ; ///< Total length of data returned
+
+ 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 bmAttributes ; ///< Same as Configuration descriptor
+ uint8_t bMaxPower ; ///< Same as Configuration descriptor
+} tusb_desc_other_speed_t;
+
+/// USB Device Qualifier Descriptor (section 9.6.1 table 9-9)
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of descriptor
+ uint8_t bDescriptorType ; ///< Device Qualifier Type
+ uint16_t bcdUSB ; ///< USB specification version number (e.g., 0200H for V2.00)
+
+ 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;
+
+/// USB Interface Association Descriptor (IAD ECN)
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of descriptor
+ uint8_t bDescriptorType ; ///< Other_speed_Configuration Type
+
+ uint8_t bFirstInterface ; ///< Index of the first associated interface.
+ uint8_t bInterfaceCount ; ///< Total number of associated interfaces.
+
+ uint8_t bFunctionClass ; ///< Interface class ID.
+ uint8_t bFunctionSubClass ; ///< Interface subclass ID.
+ uint8_t bFunctionProtocol ; ///< Interface protocol ID.
+
+ uint8_t iFunction ; ///< Index of the string descriptor describing the interface association.
+} tusb_desc_interface_assoc_t;
+
+/// USB Header Descriptor
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes
+ uint8_t bDescriptorType ; ///< Descriptor Type
+} tusb_desc_header_t;
+
+typedef struct ATTR_PACKED
+{
+ uint8_t bLength ; ///< Size of this descriptor in bytes
+ uint8_t bDescriptorType ; ///< Descriptor Type
+ uint16_t unicode_string[];
+} tusb_desc_string_t;
+
+
+/*------------------------------------------------------------------*/
+/* Types
+ *------------------------------------------------------------------*/
+typedef struct ATTR_PACKED{
+ union {
+ struct ATTR_PACKED {
+ uint8_t recipient : 5; ///< Recipient type tusb_request_recipient_t.
+ uint8_t type : 2; ///< Request type tusb_request_type_t.
+ uint8_t direction : 1; ///< Direction type. tusb_dir_t
+ } bmRequestType_bit;
+
+ uint8_t bmRequestType;
+ };
+
+ uint8_t bRequest;
+ uint16_t wValue;
+ uint16_t wIndex;
+ uint16_t wLength;
+} tusb_control_request_t;
+
+TU_VERIFY_STATIC( sizeof(tusb_control_request_t) == 8, "mostly compiler option issue");
+
+// TODO move to somewhere suitable
+static inline uint8_t bm_request_type(uint8_t direction, uint8_t type, uint8_t recipient)
+{
+ return ((uint8_t) (direction << 7)) | ((uint8_t) (type << 5)) | (recipient);
+}
+
+//--------------------------------------------------------------------+
+// Endpoint helper
+//--------------------------------------------------------------------+
+
+// Get direction from Endpoint address
+static inline tusb_dir_t tu_edpt_dir(uint8_t addr)
+{
+ return (addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT;
+}
+
+// Get Endpoint number from address
+static inline uint8_t tu_edpt_number(uint8_t addr)
+{
+ return addr & (~TUSB_DIR_IN_MASK);
+}
+
+static inline uint8_t tu_edpt_addr(uint8_t num, uint8_t dir)
+{
+ return num | (dir ? TUSB_DIR_IN_MASK : 0);
+}
+
+//--------------------------------------------------------------------+
+// Descriptor helper
+//--------------------------------------------------------------------+
+static inline uint8_t const * tu_desc_next(void const* desc)
+{
+ uint8_t const* desc8 = (uint8_t const*) desc;
+ return desc8 + desc8[DESC_OFFSET_LEN];
+}
+
+static inline uint8_t tu_desc_type(void const* desc)
+{
+ return ((uint8_t const*) desc)[DESC_OFFSET_TYPE];
+}
+
+static inline uint8_t tu_desc_len(void const* desc)
+{
+ return ((uint8_t const*) desc)[DESC_OFFSET_LEN];
+}
+
+// Length of the string descriptors in bytes with slen characters
+#define TUD_DESC_STRLEN(_slen) (2*(_slen) + 2)
+
+// Header of string descriptors with len + string type
+#define TUD_DESC_STR_HEADER(_slen) ( (uint16_t) ( (TUSB_DESC_STRING << 8 ) | TUD_DESC_STRLEN(_slen)) )
+
+// Convert comma-separated string to descriptor unicode format
+#define TUD_DESC_STRCONV( ... ) (const uint16_t[]) { TUD_DESC_STR_HEADER(VA_ARGS_NUM_(__VA_ARGS__)), __VA_ARGS__ }
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_TYPES_H_ */
+
+/** @} */
diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h new file mode 100644 index 000000000..1cb8443bc --- /dev/null +++ b/src/common/tusb_verify.h @@ -0,0 +1,186 @@ +/**************************************************************************/ +/*! + @file verify.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ +#ifndef TUSB_VERIFY_H_ +#define TUSB_VERIFY_H_ + +#include <stdbool.h> +#include <stdint.h> +#include "tusb_option.h" +#include "tusb_compiler.h" + +/*------------------------------------------------------------------*/ +/* This file use an advanced macro technique to mimic the default parameter + * as C++ for the sake of code simplicity. Beware of a headache macro + * manipulation that you are told to stay away. + * + * e.g + * + * - TU_VERIFY( cond ) will return false if cond is false + * - TU_VERIFY( cond, err) will return err instead if cond is false + *------------------------------------------------------------------*/ + +#ifdef __cplusplus + extern "C" { +#endif + + +//--------------------------------------------------------------------+ +// TU_VERIFY Helper +//--------------------------------------------------------------------+ +#if CFG_TUSB_DEBUG >= 1 + #include <stdio.h> + #define _MESS_ERR(_err) printf("%s: %d: failed, error = %s\n", __func__, __LINE__, tusb_strerr[_err]) + #define _MESS_FAILED() printf("%s: %d: failed\n", __func__, __LINE__) +#else + #define _MESS_ERR(_err) + #define _MESS_FAILED() +#endif + +// Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7 +#if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__) + +#define TU_BREAKPOINT() \ + do {\ + volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \ + if ( (*ARM_CM_DHCSR) & 1UL ) __asm("BKPT #0\n"); /* Only halt mcu if debugger is attached */\ + } while(0) + +#else +#define TU_BREAKPOINT() +#endif + +/*------------------------------------------------------------------*/ +/* Macro Generator + *------------------------------------------------------------------*/ + +// Helper to implement optional parameter for TU_VERIFY Macro family +#define GET_3RD_ARG(arg1, arg2, arg3, ...) arg3 +#define GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4 + +/*------------- Generator for TU_VERIFY and TU_VERIFY_HDLR -------------*/ +#define TU_VERIFY_DEFINE(_cond, _handler, _ret) do { if ( !(_cond) ) { _handler; return _ret; } } while(0) + +/*------------- Generator for TU_VERIFY_ERR and TU_VERIFY_ERR_HDLR -------------*/ +#define TU_VERIFY_ERR_DEF2(_error, _handler) \ + do { \ + uint32_t _err = (uint32_t)(_error); \ + if ( 0 != _err ) { _MESS_ERR(_err); _handler; return _err; }\ + } while(0) + +#define TU_VERIFY_ERR_DEF3(_error, _handler, _ret) \ + do { \ + uint32_t _err = (uint32_t)(_error); \ + if ( 0 != _err ) { _MESS_ERR(_err); _handler; return _ret; }\ + } while(0) + + + + +/*------------------------------------------------------------------*/ +/* TU_VERIFY + * - TU_VERIFY_1ARGS : return false if failed + * - TU_VERIFY_2ARGS : return provided value if failed + *------------------------------------------------------------------*/ +#define TU_VERIFY_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, , false) +#define TU_VERIFY_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, , _ret) + +#define TU_VERIFY(...) GET_3RD_ARG(__VA_ARGS__, TU_VERIFY_2ARGS, TU_VERIFY_1ARGS)(__VA_ARGS__) + + +/*------------------------------------------------------------------*/ +/* TU_VERIFY WITH HANDLER + * - TU_VERIFY_HDLR_2ARGS : execute handler, return false if failed + * - TU_VERIFY_HDLR_3ARGS : execute handler, return provided error if failed + *------------------------------------------------------------------*/ +#define TU_VERIFY_HDLR_2ARGS(_cond, _handler) TU_VERIFY_DEFINE(_cond, _handler, false) +#define TU_VERIFY_HDLR_3ARGS(_cond, _handler, _ret) TU_VERIFY_DEFINE(_cond, _handler, _ret) + +#define TU_VERIFY_HDLR(...) GET_4TH_ARG(__VA_ARGS__, TU_VERIFY_HDLR_3ARGS, TU_VERIFY_HDLR_2ARGS)(__VA_ARGS__) + + +/*------------------------------------------------------------------*/ +/* TU_VERIFY STATUS + * - TU_VERIFY_ERR_1ARGS : return status of condition if failed + * - TU_VERIFY_ERR_2ARGS : return provided status code if failed + *------------------------------------------------------------------*/ +#define TU_VERIFY_ERR_1ARGS(_error) TU_VERIFY_ERR_DEF2(_error, ) +#define TU_VERIFY_ERR_2ARGS(_error, _ret) TU_VERIFY_ERR_DEF3(_error, ,_ret) + +#define TU_VERIFY_ERR(...) GET_3RD_ARG(__VA_ARGS__, TU_VERIFY_ERR_2ARGS, TU_VERIFY_ERR_1ARGS)(__VA_ARGS__) + +/*------------------------------------------------------------------*/ +/* TU_VERIFY STATUS WITH HANDLER + * - TU_VERIFY_ERR_HDLR_2ARGS : execute handler, return status if failed + * - TU_VERIFY_ERR_HDLR_3ARGS : execute handler, return provided error if failed + *------------------------------------------------------------------*/ +#define TU_VERIFY_ERR_HDLR_2ARGS(_error, _handler) TU_VERIFY_ERR_DEF2(_error, _handler) +#define TU_VERIFY_ERR_HDLR_3ARGS(_error, _handler, _ret) TU_VERIFY_ERR_DEF3(_error, _handler, _ret) + +#define TU_VERIFY_ERR_HDLR(...) GET_4TH_ARG(__VA_ARGS__, TU_VERIFY_ERR_HDLR_3ARGS, TU_VERIFY_ERR_HDLR_2ARGS)(__VA_ARGS__) + + + +/*------------------------------------------------------------------*/ +/* ASSERT + * basically TU_VERIFY with TU_BREAKPOINT() as handler + * - 1 arg : return false if failed + * - 2 arg : return error if failed + *------------------------------------------------------------------*/ +#define ASSERT_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), false) +#define ASSERT_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), _ret) + +#define TU_ASSERT(...) GET_3RD_ARG(__VA_ARGS__, ASSERT_2ARGS, ASSERT_1ARGS)(__VA_ARGS__) + +/*------------------------------------------------------------------*/ +/* ASSERT Error + * basically TU_VERIFY Error with TU_BREAKPOINT() as handler + *------------------------------------------------------------------*/ +#define ASERT_ERR_1ARGS(_error) TU_VERIFY_ERR_DEF2(_error, TU_BREAKPOINT()) +#define ASERT_ERR_2ARGS(_error, _ret) TU_VERIFY_ERR_DEF3(_error, TU_BREAKPOINT(), _ret) + +#define TU_ASSERT_ERR(...) GET_3RD_ARG(__VA_ARGS__, ASERT_ERR_2ARGS, ASERT_ERR_1ARGS)(__VA_ARGS__) + +/*------------------------------------------------------------------*/ +/* ASSERT HDLR + *------------------------------------------------------------------*/ + +#ifdef __cplusplus + } +#endif + +#endif /* TUSB_VERIFY_H_ */ diff --git a/src/device/dcd.h b/src/device/dcd.h new file mode 100644 index 000000000..6b1356cbf --- /dev/null +++ b/src/device/dcd.h @@ -0,0 +1,143 @@ +/**************************************************************************/
+/*!
+ @file dcd.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_usbd
+ * \defgroup group_dcd Device Controller Driver (DCD)
+ * @{ */
+
+#ifndef _TUSB_DCD_H_
+#define _TUSB_DCD_H_
+
+#include "common/tusb_common.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+typedef enum
+{
+ DCD_EVENT_BUS_RESET = 1,
+ DCD_EVENT_UNPLUGGED,
+ DCD_EVENT_SOF,
+ DCD_EVENT_SUSPENDED,
+ DCD_EVENT_RESUME,
+
+ DCD_EVENT_SETUP_RECEIVED,
+ DCD_EVENT_XFER_COMPLETE,
+
+ USBD_EVT_FUNC_CALL
+} dcd_eventid_t;
+
+typedef struct ATTR_ALIGNED(4)
+{
+ uint8_t rhport;
+ uint8_t event_id;
+
+ union {
+ // USBD_EVT_SETUP_RECEIVED
+ tusb_control_request_t setup_received;
+
+ // USBD_EVT_XFER_COMPLETE
+ struct {
+ uint8_t ep_addr;
+ uint8_t result;
+ uint32_t len;
+ }xfer_complete;
+
+ // USBD_EVT_FUNC_CALL
+ struct {
+ void (*func) (void*);
+ void* param;
+ }func_call;
+ };
+} dcd_event_t;
+
+TU_VERIFY_STATIC(sizeof(dcd_event_t) <= 12, "size is not correct");
+
+/*------------------------------------------------------------------*/
+/* Device API
+ *------------------------------------------------------------------*/
+bool dcd_init (uint8_t rhport);
+void dcd_int_enable (uint8_t rhport);
+void dcd_int_disable(uint8_t rhport);
+
+void dcd_set_address(uint8_t rhport, uint8_t dev_addr);
+void dcd_set_config (uint8_t rhport, uint8_t config_num);
+
+/*------------------------------------------------------------------*/
+/* Event Function
+ * Called by DCD to notify USBD
+ *------------------------------------------------------------------*/
+void dcd_event_handler(dcd_event_t const * event, bool in_isr);
+
+// helper to send bus signal event
+void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr);
+
+// helper to send setup received
+void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr);
+
+// helper to send transfer complete event
+void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr);
+
+
+/*------------------------------------------------------------------*/
+/* Endpoint API
+ * - open : Configure endpoint's registers
+ * - xfer : Submit a transfer. When complete dcd_event_xfer_complete
+ * must be called to notify the stack
+ * - busy : Check if endpoint transferring is complete (TODO remove)
+ * - stall : stall ep. When control endpoint (addr = 0) is stalled,
+ * both direction (IN & OUT) of control ep must be stalled.
+ * - clear_stall : clear stall
+ * - stalled : check if stalled ( TODO remove )
+ *------------------------------------------------------------------*/
+bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc);
+bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes);
+bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr);
+
+void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr);
+void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr);
+bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr);
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_DCD_H_ */
+
+/// @}
diff --git a/src/device/usbd.c b/src/device/usbd.c new file mode 100644 index 000000000..8c685d5b3 --- /dev/null +++ b/src/device/usbd.c @@ -0,0 +1,665 @@ +/**************************************************************************/
+/*!
+ @file usbd.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+// This top level class manages the bus state and delegates events to class-specific drivers.
+
+#include "tusb_option.h"
+
+#if TUSB_OPT_DEVICE_ENABLED
+
+#define _TINY_USB_SOURCE_FILE_
+
+#include "tusb.h"
+#include "usbd.h"
+#include "device/usbd_pvt.h"
+
+#ifndef CFG_TUD_TASK_QUEUE_SZ
+#define CFG_TUD_TASK_QUEUE_SZ 16
+#endif
+
+#ifndef CFG_TUD_TASK_STACK_SZ
+#define CFG_TUD_TASK_STACK_SZ 150
+#endif
+
+#ifndef CFG_TUD_TASK_PRIO
+#define CFG_TUD_TASK_PRIO 0
+#endif
+
+
+//--------------------------------------------------------------------+
+// Device Data
+//--------------------------------------------------------------------+
+typedef struct {
+ uint8_t config_num;
+
+ uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid)
+ uint8_t ep2drv[8][2]; // map endpoint to driver ( 0xff is invalid )
+
+}usbd_device_t;
+
+static usbd_device_t _usbd_dev;
+
+// Auto descriptor is enabled, descriptor set point to auto generated one
+#if CFG_TUD_DESC_AUTO
+extern tud_desc_set_t const _usbd_auto_desc_set;
+tud_desc_set_t const* usbd_desc_set = &_usbd_auto_desc_set;
+#else
+tud_desc_set_t const* usbd_desc_set = &tud_desc_set;
+#endif
+
+//--------------------------------------------------------------------+
+// Class Driver
+//--------------------------------------------------------------------+
+typedef struct {
+ uint8_t class_code;
+
+ void (* init ) (void);
+ bool (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length);
+ bool (* control_request ) (uint8_t rhport, tusb_control_request_t const * request);
+ bool (* control_request_complete ) (uint8_t rhport, tusb_control_request_t const * request);
+ bool (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, xfer_result_t, uint32_t);
+ void (* sof ) (uint8_t rhport);
+ void (* reset ) (uint8_t);
+} usbd_class_driver_t;
+
+static usbd_class_driver_t const usbd_class_drivers[] =
+{
+ #if CFG_TUD_CDC
+ {
+ .class_code = TUSB_CLASS_CDC,
+ .init = cdcd_init,
+ .open = cdcd_open,
+ .control_request = cdcd_control_request,
+ .control_request_complete = cdcd_control_request_complete,
+ .xfer_cb = cdcd_xfer_cb,
+ .sof = NULL,
+ .reset = cdcd_reset
+ },
+ #endif
+
+ #if CFG_TUD_MSC
+ {
+ .class_code = TUSB_CLASS_MSC,
+ .init = mscd_init,
+ .open = mscd_open,
+ .control_request = mscd_control_request,
+ .control_request_complete = mscd_control_request_complete,
+ .xfer_cb = mscd_xfer_cb,
+ .sof = NULL,
+ .reset = mscd_reset
+ },
+ #endif
+
+
+ #if CFG_TUD_HID
+ {
+ .class_code = TUSB_CLASS_HID,
+ .init = hidd_init,
+ .open = hidd_open,
+ .control_request = hidd_control_request,
+ .control_request_complete = hidd_control_request_complete,
+ .xfer_cb = hidd_xfer_cb,
+ .sof = NULL,
+ .reset = hidd_reset
+ },
+ #endif
+
+ #if CFG_TUD_CUSTOM_CLASS
+ {
+ .class_code = TUSB_CLASS_VENDOR_SPECIFIC,
+ .init = cusd_init,
+ .open = cusd_open,
+ .control_request = cusd_control_request,
+ .control_request_complete = cusd_control_request_complete,
+ .xfer_cb = cusd_xfer_cb,
+ .sof = NULL,
+ .reset = cusd_reset
+ },
+ #endif
+};
+
+enum { USBD_CLASS_DRIVER_COUNT = sizeof(usbd_class_drivers) / sizeof(usbd_class_driver_t) };
+
+
+//--------------------------------------------------------------------+
+// DCD Event
+//--------------------------------------------------------------------+
+OSAL_TASK_DEF(_usbd_task_def, "usbd", usbd_task, CFG_TUD_TASK_PRIO, CFG_TUD_TASK_STACK_SZ);
+
+// Event queue
+// role device/host is used by OS NONE for mutex (disable usb isr) only
+OSAL_QUEUE_DEF(OPT_MODE_DEVICE, _usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t);
+static osal_queue_t _usbd_q;
+
+//--------------------------------------------------------------------+
+// Prototypes
+//--------------------------------------------------------------------+
+static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id);
+static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request);
+static bool process_set_config(uint8_t rhport);
+static void const* get_descriptor(tusb_control_request_t const * p_request, uint16_t* desc_len);
+
+void usbd_control_reset (uint8_t rhport);
+bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
+void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) );
+
+//--------------------------------------------------------------------+
+// APPLICATION API
+//--------------------------------------------------------------------+
+bool tud_mounted(void)
+{
+ return _usbd_dev.config_num > 0;
+}
+
+//--------------------------------------------------------------------+
+// USBD Task
+//--------------------------------------------------------------------+
+bool usbd_init (void)
+{
+ // Init device queue & task
+ _usbd_q = osal_queue_create(&_usbd_qdef);
+ TU_ASSERT(_usbd_q != NULL);
+
+ osal_task_create(&_usbd_task_def);
+
+ // Init class drivers
+ for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) usbd_class_drivers[i].init();
+
+ // Init device controller driver
+ TU_ASSERT(dcd_init(TUD_OPT_RHPORT));
+ dcd_int_enable(TUD_OPT_RHPORT);
+
+ return true;
+}
+
+static void usbd_reset(uint8_t rhport)
+{
+ tu_varclr(&_usbd_dev);
+ memset(_usbd_dev.itf2drv, 0xff, sizeof(_usbd_dev.itf2drv)); // invalid mapping
+ memset(_usbd_dev.ep2drv , 0xff, sizeof(_usbd_dev.ep2drv )); // invalid mapping
+
+ usbd_control_reset(rhport);
+
+ for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++)
+ {
+ if ( usbd_class_drivers[i].reset ) usbd_class_drivers[i].reset( rhport );
+ }
+}
+
+// Main device task implementation
+static void usbd_task_body(void)
+{
+ // Loop until there is no more events in the queue
+ while (1)
+ {
+ dcd_event_t event;
+
+ if ( !osal_queue_receive(_usbd_q, &event) ) return;
+
+ switch ( event.event_id )
+ {
+ case DCD_EVENT_SETUP_RECEIVED:
+ // Process control request, if failed control endpoint is stalled
+ if ( !process_control_request(event.rhport, &event.setup_received) )
+ {
+ usbd_control_stall(event.rhport);
+ }
+ break;
+
+ case DCD_EVENT_XFER_COMPLETE:
+ {
+ // Invoke the class callback associated with the endpoint address
+ uint8_t const ep_addr = event.xfer_complete.ep_addr;
+
+ if ( 0 == tu_edpt_number(ep_addr) )
+ {
+ // control transfer DATA stage callback
+ usbd_control_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len);
+ }
+ else
+ {
+ uint8_t const drv_id = _usbd_dev.ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)];
+ TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT,);
+
+ usbd_class_drivers[drv_id].xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len);
+ }
+ }
+ break;
+
+ case DCD_EVENT_BUS_RESET:
+ usbd_reset(event.rhport);
+ // TODO remove since if task is too slow, we could clear the event of the new attached
+ osal_queue_reset(_usbd_q);
+ break;
+
+ case DCD_EVENT_UNPLUGGED:
+ usbd_reset(event.rhport);
+ // TODO remove since if task is too slow, we could clear the event of the new attached
+ osal_queue_reset(_usbd_q);
+
+ // invoke callback
+ if (tud_umount_cb) tud_umount_cb();
+ break;
+
+ case DCD_EVENT_SOF:
+ for ( uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++ )
+ {
+ if ( usbd_class_drivers[i].sof )
+ {
+ usbd_class_drivers[i].sof(event.rhport);
+ }
+ }
+ break;
+
+ case USBD_EVT_FUNC_CALL:
+ if ( event.func_call.func ) event.func_call.func(event.func_call.param);
+ break;
+
+ default:
+ TU_BREAKPOINT();
+ break;
+ }
+ }
+}
+
+/* USB device task
+ * Thread that handles all device events. With an real RTOS, the task must be a forever loop and never return.
+ * For coding convenience with no RTOS, we use wrapped sub-function for processing to easily return at any time.
+ */
+void usbd_task( void* param)
+{
+ (void) param;
+
+#if CFG_TUSB_OS != OPT_OS_NONE
+ while (1) {
+#endif
+
+ usbd_task_body();
+
+#if CFG_TUSB_OS != OPT_OS_NONE
+ }
+#endif
+}
+
+//--------------------------------------------------------------------+
+// Control Request Parser & Handling
+//--------------------------------------------------------------------+
+
+// This handles the actual request and its response.
+// return false will cause its caller to stall control endpoint
+static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
+{
+ usbd_control_set_complete_callback(NULL);
+
+ if ( TUSB_REQ_RCPT_DEVICE == p_request->bmRequestType_bit.recipient &&
+ TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type )
+ {
+ //------------- Standard Device Requests e.g in enumeration -------------//
+ void* data_buf = NULL;
+ uint16_t data_len = 0;
+
+ switch ( p_request->bRequest )
+ {
+ case TUSB_REQ_SET_ADDRESS:
+ // response with status first before changing device address
+ usbd_control_status(rhport, p_request);
+ dcd_set_address(rhport, (uint8_t) p_request->wValue);
+ return true; // skip the rest
+ break;
+
+ case TUSB_REQ_GET_CONFIGURATION:
+ data_buf = &_usbd_dev.config_num;
+ data_len = 1;
+ break;
+
+ case TUSB_REQ_SET_CONFIGURATION:
+ {
+ uint8_t const config = (uint8_t) p_request->wValue;
+
+ dcd_set_config(rhport, config);
+ _usbd_dev.config_num = config;
+
+ TU_ASSERT( TUSB_ERROR_NONE == process_set_config(rhport) );
+ }
+ break;
+
+ case TUSB_REQ_GET_DESCRIPTOR:
+ data_buf = (void*) get_descriptor(p_request, &data_len);
+ if ( data_buf == NULL || data_len == 0 ) return false;
+ break;
+
+ default:
+ TU_BREAKPOINT();
+ return false;
+ }
+
+ usbd_control_xfer(rhport, p_request, data_buf, data_len);
+ }
+ else if ( TUSB_REQ_RCPT_INTERFACE == p_request->bmRequestType_bit.recipient )
+ {
+ //------------- Class/Interface Specific Request -------------//
+ uint8_t const itf = tu_u16_low(p_request->wIndex);
+ uint8_t const drvid = _usbd_dev.itf2drv[ itf ];
+
+ TU_VERIFY(drvid < USBD_CLASS_DRIVER_COUNT);
+
+ usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_request_complete );
+
+ // control endpoint will be stalled if driver return false
+ return usbd_class_drivers[drvid].control_request(rhport, p_request);
+ }
+ else if ( p_request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_ENDPOINT &&
+ p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD )
+ {
+ //------------- Endpoint Request -------------//
+ switch ( p_request->bRequest )
+ {
+ case TUSB_REQ_GET_STATUS:
+ {
+ uint16_t status = dcd_edpt_stalled(rhport, tu_u16_low(p_request->wIndex)) ? 0x0001 : 0x0000;
+ usbd_control_xfer(rhport, p_request, &status, 2);
+ }
+ break;
+
+ case TUSB_REQ_CLEAR_FEATURE:
+ // only endpoint feature is halted/stalled
+ dcd_edpt_clear_stall(rhport, tu_u16_low(p_request->wIndex));
+ usbd_control_status(rhport, p_request);
+ break;
+
+ case TUSB_REQ_SET_FEATURE:
+ // only endpoint feature is halted/stalled
+ dcd_edpt_stall(rhport, tu_u16_low(p_request->wIndex));
+ usbd_control_status(rhport, p_request);
+ break;
+
+ default:
+ TU_BREAKPOINT();
+ return false;
+ }
+ }
+ else
+ {
+ //------------- Unsupported Request -------------//
+ TU_BREAKPOINT();
+ return false;
+ }
+
+ return true;
+}
+
+// Process Set Configure Request
+// This function parse configuration descriptor & open drivers accordingly
+static bool process_set_config(uint8_t rhport)
+{
+ uint8_t const * desc_cfg = (uint8_t const *) usbd_desc_set->config;
+ TU_ASSERT(desc_cfg != NULL);
+
+ uint8_t const * p_desc = desc_cfg + sizeof(tusb_desc_configuration_t);
+ uint16_t const cfg_len = ((tusb_desc_configuration_t*)desc_cfg)->wTotalLength;
+
+ while( p_desc < desc_cfg + cfg_len )
+ {
+ // Each interface always starts with Interface or Association descriptor
+ if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) )
+ {
+ p_desc = tu_desc_next(p_desc); // ignore Interface Association
+ }else
+ {
+ TU_ASSERT( TUSB_DESC_INTERFACE == tu_desc_type(p_desc) );
+
+ tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc;
+
+ // Check if class is supported
+ uint8_t drv_id;
+ for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++)
+ {
+ if ( usbd_class_drivers[drv_id].class_code == desc_itf->bInterfaceClass ) break;
+ }
+ TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT );
+
+ // Interface number must not be used already TODO alternate interface
+ TU_ASSERT( 0xff == _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] );
+ _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] = drv_id;
+
+ uint16_t itf_len=0;
+ TU_ASSERT( usbd_class_drivers[drv_id].open( rhport, desc_itf, &itf_len ) );
+ TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) );
+
+ mark_interface_endpoint(_usbd_dev.ep2drv, p_desc, itf_len, drv_id);
+
+ p_desc += itf_len; // next interface
+ }
+ }
+
+ // invoke callback
+ if (tud_mount_cb) tud_mount_cb();
+
+ return TUSB_ERROR_NONE;
+}
+
+// Helper marking endpoint of interface belongs to class driver
+static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id)
+{
+ uint16_t len = 0;
+
+ while( len < desc_len )
+ {
+ if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
+ {
+ uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress;
+
+ ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)] = driver_id;
+ }
+
+ len += tu_desc_len(p_desc);
+ p_desc = tu_desc_next(p_desc);
+ }
+}
+
+// return descriptor's buffer and update desc_len
+static void const* get_descriptor(tusb_control_request_t const * p_request, uint16_t* desc_len)
+{
+ tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue);
+ uint8_t const desc_index = tu_u16_low( p_request->wValue );
+
+ uint8_t const * desc_data = NULL;
+ uint16_t len = 0;
+
+ *desc_len = 0;
+
+ switch(desc_type)
+ {
+ case TUSB_DESC_DEVICE:
+ desc_data = (uint8_t const *) usbd_desc_set->device;
+ len = sizeof(tusb_desc_device_t);
+ break;
+
+ case TUSB_DESC_CONFIGURATION:
+ desc_data = (uint8_t const *) usbd_desc_set->config;
+ len = ((tusb_desc_configuration_t const*) desc_data)->wTotalLength;
+ break;
+
+ case TUSB_DESC_STRING:
+ // String Descriptor always uses the desc set from user
+ if ( desc_index < tud_desc_set.string_count )
+ {
+ desc_data = tud_desc_set.string_arr[desc_index];
+ TU_VERIFY( desc_data != NULL, NULL );
+
+ len = desc_data[0]; // first byte of descriptor is its size
+ }else
+ {
+ // out of range
+ /* The 0xEE index string is a Microsoft USB extension.
+ * It can be used to tell Windows what driver it should use for the device !!!
+ */
+ return NULL;
+ }
+ break;
+
+ case TUSB_DESC_DEVICE_QUALIFIER:
+ // TODO If not highspeed capable stall this request otherwise
+ // return the descriptor that could work in highspeed
+ return NULL;
+ break;
+
+ default: return NULL;
+ }
+
+ *desc_len = len;
+ return desc_data;
+}
+
+//--------------------------------------------------------------------+
+// DCD Event Handler
+//--------------------------------------------------------------------+
+void dcd_event_handler(dcd_event_t const * event, bool in_isr)
+{
+ switch (event->event_id)
+ {
+ case DCD_EVENT_BUS_RESET:
+ case DCD_EVENT_UNPLUGGED:
+ osal_queue_send(_usbd_q, event, in_isr);
+ break;
+
+ case DCD_EVENT_SOF:
+ // nothing to do now
+ break;
+
+ case DCD_EVENT_SUSPENDED:
+ // TODO support suspended
+ break;
+
+ case DCD_EVENT_RESUME:
+ // TODO support resume
+ break;
+
+ case DCD_EVENT_SETUP_RECEIVED:
+ osal_queue_send(_usbd_q, event, in_isr);
+ break;
+
+ case DCD_EVENT_XFER_COMPLETE:
+ // skip zero-length control status complete event, should dcd notifies us.
+ if ( 0 == tu_edpt_number(event->xfer_complete.ep_addr) && event->xfer_complete.len == 0) break;
+
+ osal_queue_send(_usbd_q, event, in_isr);
+ TU_ASSERT(event->xfer_complete.result == XFER_RESULT_SUCCESS,);
+ break;
+
+ // Not an DCD event, just a convenient way to defer ISR function should we need
+ case USBD_EVT_FUNC_CALL:
+ osal_queue_send(_usbd_q, event, in_isr);
+ break;
+
+ default: break;
+ }
+}
+
+// helper to send bus signal event
+void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr)
+{
+ dcd_event_t event = { .rhport = rhport, .event_id = eid, };
+ dcd_event_handler(&event, in_isr);
+}
+
+// helper to send setup received
+void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr)
+{
+ dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SETUP_RECEIVED };
+ memcpy(&event.setup_received, setup, 8);
+
+ dcd_event_handler(&event, in_isr);
+}
+
+// helper to send transfer complete event
+void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr)
+{
+ dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_XFER_COMPLETE };
+
+ event.xfer_complete.ep_addr = ep_addr;
+ event.xfer_complete.len = xferred_bytes;
+ event.xfer_complete.result = result;
+
+ dcd_event_handler(&event, in_isr);
+}
+
+//--------------------------------------------------------------------+
+// Helper
+//--------------------------------------------------------------------+
+
+// Helper to parse an pair of endpoint descriptors (IN & OUT)
+bool usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* ep_desc, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in)
+{
+ for(int i=0; i<2; i++)
+ {
+ TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType &&
+ xfer_type == ep_desc->bmAttributes.xfer );
+
+ TU_ASSERT(dcd_edpt_open(rhport, ep_desc));
+
+ if ( tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN )
+ {
+ (*ep_in) = ep_desc->bEndpointAddress;
+ }else
+ {
+ (*ep_out) = ep_desc->bEndpointAddress;
+ }
+
+ ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(ep_desc);
+ }
+
+ return true;
+}
+
+// Helper to defer an isr function
+void usbd_defer_func(osal_task_func_t func, void* param, bool in_isr)
+{
+ dcd_event_t event =
+ {
+ .rhport = 0,
+ .event_id = USBD_EVT_FUNC_CALL,
+ };
+
+ event.func_call.func = func;
+ event.func_call.param = param;
+
+ dcd_event_handler(&event, in_isr);
+}
+
+#endif
diff --git a/src/device/usbd.h b/src/device/usbd.h new file mode 100644 index 000000000..f9e0d8f4d --- /dev/null +++ b/src/device/usbd.h @@ -0,0 +1,103 @@ +/**************************************************************************/
+/*!
+ @file usbd.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_usbd
+ * @{ */
+
+#ifndef _TUSB_USBD_H_
+#define _TUSB_USBD_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include <common/tusb_common.h>
+#include "osal/osal.h"
+#include "device/dcd.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+
+/// \brief Descriptor pointer collector to all the needed.
+typedef struct {
+ void const * device; ///< pointer to device descriptor \ref tusb_desc_device_t
+ void const * config; ///< pointer to the whole configuration descriptor, starting by \ref tusb_desc_configuration_t
+
+ uint8_t const** string_arr; ///< a array of pointers to string descriptors
+ uint16_t string_count;
+
+ struct {
+ uint8_t const* generic;
+ uint8_t const* boot_keyboard;
+ uint8_t const* boot_mouse;
+ } hid_report;
+
+}tud_desc_set_t;
+
+
+// Must be defined by application
+extern tud_desc_set_t tud_desc_set;
+
+//--------------------------------------------------------------------+
+// APPLICATION API
+//--------------------------------------------------------------------+
+bool tud_mounted(void);
+
+//--------------------------------------------------------------------+
+// APPLICATION CALLBACK (WEAK is optional)
+//--------------------------------------------------------------------+
+
+/** Callback invoked when device is mounted (configured) */
+ATTR_WEAK void tud_mount_cb(void);
+
+/** Callback invoked when device is unmounted (bus reset/unplugged) */
+ATTR_WEAK void tud_umount_cb(void);
+
+//void tud_device_suspended_cb(void);
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_USBD_H_ */
+
+/** @} */
diff --git a/src/device/usbd_auto_desc.c b/src/device/usbd_auto_desc.c new file mode 100644 index 000000000..028d1b433 --- /dev/null +++ b/src/device/usbd_auto_desc.c @@ -0,0 +1,660 @@ +/**************************************************************************/ +/*! + @file usbd_auto_desc.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUD_DESC_AUTO + +#include "tusb.h" + +//--------------------------------------------------------------------+ +// Auto Description Default Configure & Validation +//--------------------------------------------------------------------+ + +// If HID Generic interface is generated +#define AUTO_DESC_HID_GENERIC (CFG_TUD_HID && ((CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT) || \ + (CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT)) ) +/*------------- VID/PID -------------*/ +#ifndef CFG_TUD_DESC_VID +#define CFG_TUD_DESC_VID 0xCAFE +#endif + +#ifndef CFG_TUD_DESC_PID + +/* A combination of interfaces must have a unique product id, since PC will save device driver after the first plug. + * Same VID/PID with different interface e.g MSC (first), then CDC (later) will possibly cause system error on PC. + * + * Auto ProductID layout's Bitmap: + * [MSB] HID Generic | Boot Mouse | Boot Keyboard | MSC | CDC [LSB] + */ +#define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) +#define CFG_TUD_DESC_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | _PID_MAP(HID, 2) | \ + _PID_MAP(HID_KEYBOARD, 2) | _PID_MAP(HID_MOUSE, 3) | (AUTO_DESC_HID_GENERIC << 4) ) +#endif + +//--------------------------------------------------------------------+ +// Interface & Endpoint mapping +//--------------------------------------------------------------------+ + +/*------------- Interface Numbering -------------*/ +/* The order as follows: CDC, MSC, Boot Keyboard, Boot Mouse, HID Generic + * If an interface is not enabled, the later will take its place */ + +enum +{ +#if CFG_TUD_CDC + ITF_NUM_CDC, + ITF_NUM_CDC_DATA, +#endif + +#if CFG_TUD_MSC + ITF_NUM_MSC, +#endif + +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT + ITF_NUM_HID_BOOT_KBD, +#endif + +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT + ITF_NUM_HID_BOOT_MSE, +#endif + +#if AUTO_DESC_HID_GENERIC + ITF_NUM_HID_GEN, +#endif + + ITF_NUM_TOTAL +}; + +enum +{ + ITF_STR_LANGUAGE = 0 , + ITF_STR_MANUFACTURER , + ITF_STR_PRODUCT , + ITF_STR_SERIAL , + +#if CFG_TUD_CDC + ITF_STR_CDC , +#endif + +#if CFG_TUD_MSC + ITF_STR_MSC , +#endif + +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT + ITF_STR_HID_BOOT_KBD, +#endif + +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT + ITF_STR_HID_BOOT_MSE, +#endif + +#if AUTO_DESC_HID_GENERIC + ITF_STR_HID_GEN, +#endif +}; + +/*------------- Endpoint Numbering & Size -------------*/ +#define _EP_IN(x) (0x80 | (x)) +#define _EP_OUT(x) (x) + +// CDC +#ifdef CFG_TUD_DESC_CDC_EPNUM_NOTIF + #define EP_CDC_NOTIF _EP_IN (CFG_TUD_DESC_CDC_EPNUM_NOTIF) +#else + #define EP_CDC_NOTIF _EP_IN ( ITF_NUM_CDC+1 ) +#endif +#define EP_CDC_NOTIF_SIZE 8 + +#ifdef CFG_TUD_DESC_CDC_EPNUM + #define EP_CDC_OUT _EP_OUT( CFG_TUD_DESC_CDC_EPNUM ) + #define EP_CDC_IN _EP_IN ( CFG_TUD_DESC_CDC_EPNUM ) +#else + #define EP_CDC_OUT _EP_OUT( ITF_NUM_CDC+2 ) + #define EP_CDC_IN _EP_IN ( ITF_NUM_CDC+2 ) +#endif + +// Mass Storage +#ifdef CFG_TUD_DESC_MSC_EPNUM + #define EP_MSC_OUT _EP_OUT( CFG_TUD_DESC_MSC_EPNUM ) + #define EP_MSC_IN _EP_IN ( CFG_TUD_DESC_MSC_EPNUM ) +#else + #define EP_MSC_OUT _EP_OUT( ITF_NUM_MSC+1 ) + #define EP_MSC_IN _EP_IN ( ITF_NUM_MSC+1 ) +#endif + +#if TUD_OPT_HIGH_SPEED +#define EP_MSC_SIZE 512 +#else +#define EP_MSC_SIZE 64 +#endif + + +// HID Keyboard with boot protocol +#ifdef CFG_TUD_DESC_HID_KEYBOARD_EPNUM + #define EP_HID_KBD_BOOT _EP_IN ( CFG_TUD_DESC_HID_KEYBOARD_EPNUM ) +#else + #define EP_HID_KBD_BOOT _EP_IN ( ITF_NUM_HID_BOOT_KBD+1 ) +#endif +#define EP_HID_KBD_BOOT_SZ 8 + +// HID Mouse with boot protocol +#ifdef CFG_TUD_DESC_HID_MOUSE_EPNUM + #define EP_HID_MSE_BOOT _EP_IN ( CFG_TUD_DESC_HID_MOUSE_EPNUM ) +#else + #define EP_HID_MSE_BOOT _EP_IN ( ITF_NUM_HID_BOOT_MSE+1 ) +#endif +#define EP_HID_MSE_BOOT_SZ 8 + +// HID composite = keyboard + mouse + gamepad + etc ... +#define EP_HID_GEN _EP_IN ( ITF_NUM_HID_GEN+1 ) +#define EP_HID_GEN_SIZE 16 + + +//--------------------------------------------------------------------+ +// Auto generated HID Report Descriptors +//--------------------------------------------------------------------+ + + +/*------------- Boot Protocol Report Descriptor -------------*/ +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT +uint8_t const _desc_auto_hid_boot_kbd_report[] = { HID_REPORT_DESC_KEYBOARD() }; +#endif + +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT +uint8_t const _desc_auto_hid_boot_mse_report[] = { HID_REPORT_DESC_MOUSE() }; +#endif + + +/*------------- Generic (composite) Descriptor -------------*/ +#if AUTO_DESC_HID_GENERIC + +// Report ID: 0 if there is only 1 report +// starting from 1 if there is multiple reports +#define _REPORT_ID_KBD + +// TODO report ID +uint8_t const _desc_auto_hid_generic_report[] = +{ +#if CFG_TUD_HID_KEYBOARD && !CFG_TUD_HID_KEYBOARD_BOOT + HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(1), ), +#endif + +#if CFG_TUD_HID_MOUSE && !CFG_TUD_HID_MOUSE_BOOT + HID_REPORT_DESC_MOUSE( HID_REPORT_ID(2), ) +#endif + +}; + +#endif // hid generic + + +/*------------------------------------------------------------------*/ +/* Auto generated Device & Configuration descriptor + *------------------------------------------------------------------*/ + +// For highspeed device but currently in full speed mode +//tusb_desc_device_qualifier_t _device_qual = +//{ +// .bLength = sizeof(tusb_desc_device_qualifier_t), +// .bDescriptorType = TUSB_DESC_DEVICE_QUALIFIER, +// .bcdUSB = 0x0200, +// .bDeviceClass = +//}; + +/*------------- Device Descriptor -------------*/ +tusb_desc_device_t const _desc_auto_device = +{ + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = 0x0200, + + #if CFG_TUD_CDC + // Use Interface Association Descriptor (IAD) for CDC + // As required by USB Specs IAD's subclass must be common class (2) and protocol must be IAD (1) + .bDeviceClass = TUSB_CLASS_MISC, + .bDeviceSubClass = MISC_SUBCLASS_COMMON, + .bDeviceProtocol = MISC_PROTOCOL_IAD, + #else + .bDeviceClass = 0x00, + .bDeviceSubClass = 0x00, + .bDeviceProtocol = 0x00, + #endif + + .bMaxPacketSize0 = CFG_TUD_ENDOINT0_SIZE, + + .idVendor = CFG_TUD_DESC_VID, + .idProduct = CFG_TUD_DESC_PID, + .bcdDevice = 0x0100, + + .iManufacturer = 0x01, + .iProduct = 0x02, + .iSerialNumber = 0x03, + + .bNumConfigurations = 0x01 // TODO multiple configurations +}; + + +/*------------- Configuration Descriptor -------------*/ +typedef struct ATTR_PACKED +{ + tusb_desc_configuration_t config; + + //------------- CDC -------------// +#if CFG_TUD_CDC + struct ATTR_PACKED + { + tusb_desc_interface_assoc_t iad; + + //CDC Control Interface + tusb_desc_interface_t comm_itf; + cdc_desc_func_header_t header; + cdc_desc_func_call_management_t call; + cdc_desc_func_acm_t acm; + cdc_desc_func_union_t union_func; + tusb_desc_endpoint_t ep_notif; + + //CDC Data Interface + tusb_desc_interface_t data_itf; + tusb_desc_endpoint_t ep_out; + tusb_desc_endpoint_t ep_in; + }cdc; +#endif + + //------------- Mass Storage -------------// +#if CFG_TUD_MSC + struct ATTR_PACKED + { + tusb_desc_interface_t itf; + tusb_desc_endpoint_t ep_out; + tusb_desc_endpoint_t ep_in; + } msc; +#endif + + //------------- HID -------------// +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT + struct ATTR_PACKED + { + tusb_desc_interface_t itf; + tusb_hid_descriptor_hid_t hid_desc; + tusb_desc_endpoint_t ep_in; + } hid_kbd_boot; +#endif + +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT + struct ATTR_PACKED + { + tusb_desc_interface_t itf; + tusb_hid_descriptor_hid_t hid_desc; + tusb_desc_endpoint_t ep_in; + } hid_mse_boot; +#endif + +#if AUTO_DESC_HID_GENERIC + + struct ATTR_PACKED + { + tusb_desc_interface_t itf; + tusb_hid_descriptor_hid_t hid_desc; + tusb_desc_endpoint_t ep_in; + + #if 0 // CFG_TUD_HID_KEYBOARD + tusb_desc_endpoint_t ep_out; + #endif + } hid_generic; + +#endif + +} desc_auto_cfg_t; + +desc_auto_cfg_t const _desc_auto_config_struct = +{ + .config = + { + .bLength = sizeof(tusb_desc_configuration_t), + .bDescriptorType = TUSB_DESC_CONFIGURATION, + + .wTotalLength = sizeof(desc_auto_cfg_t), + .bNumInterfaces = ITF_NUM_TOTAL, + + .bConfigurationValue = 1, + .iConfiguration = 0x00, + .bmAttributes = TUSB_DESC_CONFIG_ATT_BUS_POWER, + .bMaxPower = TUSB_DESC_CONFIG_POWER_MA(100) + }, + +#if CFG_TUD_CDC + // IAD points to CDC Interfaces + .cdc = + { + .iad = + { + .bLength = sizeof(tusb_desc_interface_assoc_t), + .bDescriptorType = TUSB_DESC_INTERFACE_ASSOCIATION, + + .bFirstInterface = ITF_NUM_CDC, + .bInterfaceCount = 2, + + .bFunctionClass = TUSB_CLASS_CDC, + .bFunctionSubClass = CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, + .bFunctionProtocol = CDC_COMM_PROTOCOL_ATCOMMAND, + .iFunction = 0 + }, + + //------------- CDC Communication Interface -------------// + .comm_itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_CDC, + .bAlternateSetting = 0, + .bNumEndpoints = 1, + .bInterfaceClass = TUSB_CLASS_CDC, + .bInterfaceSubClass = CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, + .bInterfaceProtocol = CDC_COMM_PROTOCOL_ATCOMMAND, + .iInterface = 4 + }, + + .header = + { + .bLength = sizeof(cdc_desc_func_header_t), + .bDescriptorType = TUSB_DESC_CLASS_SPECIFIC, + .bDescriptorSubType = CDC_FUNC_DESC_HEADER, + .bcdCDC = 0x0120 + }, + + .call = + { + .bLength = sizeof(cdc_desc_func_call_management_t), + .bDescriptorType = TUSB_DESC_CLASS_SPECIFIC, + .bDescriptorSubType = CDC_FUNC_DESC_CALL_MANAGEMENT, + .bmCapabilities = { 0 }, + .bDataInterface = ITF_NUM_CDC+1, + }, + + .acm = + { + .bLength = sizeof(cdc_desc_func_acm_t), + .bDescriptorType = TUSB_DESC_CLASS_SPECIFIC, + .bDescriptorSubType = CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, + .bmCapabilities = { // 0x02 + .support_line_request = 1, + } + }, + + .union_func = + { + .bLength = sizeof(cdc_desc_func_union_t), // plus number of + .bDescriptorType = TUSB_DESC_CLASS_SPECIFIC, + .bDescriptorSubType = CDC_FUNC_DESC_UNION, + .bControlInterface = ITF_NUM_CDC, + .bSubordinateInterface = ITF_NUM_CDC+1, + }, + + .ep_notif = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_CDC_NOTIF, + .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, + .wMaxPacketSize = { .size = EP_CDC_NOTIF_SIZE }, + .bInterval = 0x10 + }, + + //------------- CDC Data Interface -------------// + .data_itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_CDC+1, + .bAlternateSetting = 0x00, + .bNumEndpoints = 2, + .bInterfaceClass = TUSB_CLASS_CDC_DATA, + .bInterfaceSubClass = 0, + .bInterfaceProtocol = 0, + .iInterface = 0x00 + }, + + .ep_out = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_CDC_OUT, + .bmAttributes = { .xfer = TUSB_XFER_BULK }, + .wMaxPacketSize = { .size = CFG_TUD_CDC_EPSIZE }, + .bInterval = 0 + }, + + .ep_in = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_CDC_IN, + .bmAttributes = { .xfer = TUSB_XFER_BULK }, + .wMaxPacketSize = { .size = CFG_TUD_CDC_EPSIZE }, + .bInterval = 0 + }, + }, +#endif // cdc + +#if CFG_TUD_MSC + //------------- Mass Storage-------------// + .msc = + { + .itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_MSC, + .bAlternateSetting = 0x00, + .bNumEndpoints = 2, + .bInterfaceClass = TUSB_CLASS_MSC, + .bInterfaceSubClass = MSC_SUBCLASS_SCSI, + .bInterfaceProtocol = MSC_PROTOCOL_BOT, + .iInterface = 4 + CFG_TUD_CDC + }, + + .ep_out = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_MSC_OUT, + .bmAttributes = { .xfer = TUSB_XFER_BULK }, + .wMaxPacketSize = { .size = EP_MSC_SIZE}, + .bInterval = 1 + }, + + .ep_in = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_MSC_IN, + .bmAttributes = { .xfer = TUSB_XFER_BULK }, + .wMaxPacketSize = { .size = EP_MSC_SIZE}, + .bInterval = 1 + } + }, +#endif // msc + +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT + .hid_kbd_boot = + { + .itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_HID_BOOT_KBD, + .bAlternateSetting = 0x00, + .bNumEndpoints = 1, + .bInterfaceClass = TUSB_CLASS_HID, + .bInterfaceSubClass = HID_SUBCLASS_BOOT, + .bInterfaceProtocol = HID_PROTOCOL_KEYBOARD, + .iInterface = 0 //4 + CFG_TUD_CDC + CFG_TUD_MSC + }, + + .hid_desc = + { + .bLength = sizeof(tusb_hid_descriptor_hid_t), + .bDescriptorType = HID_DESC_TYPE_HID, + .bcdHID = 0x0111, + .bCountryCode = HID_Local_NotSupported, + .bNumDescriptors = 1, + .bReportType = HID_DESC_TYPE_REPORT, + .wReportLength = sizeof(_desc_auto_hid_boot_kbd_report) + }, + + .ep_in = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_HID_KBD_BOOT, + .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, + .wMaxPacketSize = { .size = EP_HID_KBD_BOOT_SZ }, + .bInterval = 0x0A + } + }, +#endif // boot keyboard + + //------------- HID Mouse -------------// +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT + .hid_mse_boot = + { + .itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_HID_BOOT_MSE, + .bAlternateSetting = 0x00, + .bNumEndpoints = 1, + .bInterfaceClass = TUSB_CLASS_HID, + .bInterfaceSubClass = HID_SUBCLASS_BOOT, + .bInterfaceProtocol = HID_PROTOCOL_MOUSE, + .iInterface = 0 // 4 + CFG_TUD_CDC + CFG_TUD_MSC + CFG_TUD_HID_KEYBOARD + }, + + .hid_desc = + { + .bLength = sizeof(tusb_hid_descriptor_hid_t), + .bDescriptorType = HID_DESC_TYPE_HID, + .bcdHID = 0x0111, + .bCountryCode = HID_Local_NotSupported, + .bNumDescriptors = 1, + .bReportType = HID_DESC_TYPE_REPORT, + .wReportLength = sizeof(_desc_auto_hid_boot_mse_report) + }, + + .ep_in = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_HID_MSE_BOOT, + .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, + .wMaxPacketSize = { .size = EP_HID_MSE_BOOT_SZ }, + .bInterval = 0x0A + }, + }, + +#endif // boot mouse + +#if AUTO_DESC_HID_GENERIC + //------------- HID Generic Multiple report -------------// + .hid_generic = + { + .itf = + { + .bLength = sizeof(tusb_desc_interface_t), + .bDescriptorType = TUSB_DESC_INTERFACE, + .bInterfaceNumber = ITF_NUM_HID_GEN, + .bAlternateSetting = 0x00, + .bNumEndpoints = 1, + .bInterfaceClass = TUSB_CLASS_HID, + .bInterfaceSubClass = 0, + .bInterfaceProtocol = 0, + .iInterface = 0, // 4 + CFG_TUD_CDC + CFG_TUD_MSC, + }, + + .hid_desc = + { + .bLength = sizeof(tusb_hid_descriptor_hid_t), + .bDescriptorType = HID_DESC_TYPE_HID, + .bcdHID = 0x0111, + .bCountryCode = HID_Local_NotSupported, + .bNumDescriptors = 1, + .bReportType = HID_DESC_TYPE_REPORT, + .wReportLength = sizeof(_desc_auto_hid_generic_report) + }, + + .ep_in = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = EP_HID_GEN, + .bmAttributes = { .xfer = TUSB_XFER_INTERRUPT }, + .wMaxPacketSize = { .size = EP_HID_GEN_SIZE }, + .bInterval = 0x0A + } + } +#endif // hid generic +}; + +uint8_t const * const _desc_auto_config = (uint8_t const*) &_desc_auto_config_struct; + +tud_desc_set_t const _usbd_auto_desc_set = +{ + .device = &_desc_auto_device, + .config = &_desc_auto_config_struct, + + .hid_report = + { +#if AUTO_DESC_HID_GENERIC + .generic = _desc_auto_hid_generic_report, +#else + .generic = NULL, +#endif + +#if CFG_TUD_HID_KEYBOARD && CFG_TUD_HID_KEYBOARD_BOOT + .boot_keyboard = _desc_auto_hid_boot_kbd_report, +#endif + +#if CFG_TUD_HID_MOUSE && CFG_TUD_HID_MOUSE_BOOT + .boot_mouse = _desc_auto_hid_boot_mse_report +#endif + } +}; + +#endif diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c new file mode 100644 index 000000000..ae7e894b7 --- /dev/null +++ b/src/device/usbd_control.c @@ -0,0 +1,173 @@ +/**************************************************************************/
+/*!
+ @file usbd_control.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if TUSB_OPT_DEVICE_ENABLED
+
+#define _TINY_USB_SOURCE_FILE_
+
+#include "tusb.h"
+#include "device/usbd_pvt.h"
+
+enum
+{
+ EDPT_CTRL_OUT = 0x00,
+ EDPT_CTRL_IN = 0x80
+};
+
+typedef struct
+{
+ tusb_control_request_t request;
+
+ void* buffer;
+ uint16_t total_len;
+ uint16_t total_transferred;
+
+ bool (*complete_cb) (uint8_t, tusb_control_request_t const *);
+} usbd_control_xfer_t;
+
+static usbd_control_xfer_t _control_state;
+
+CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t _usbd_ctrl_buf[CFG_TUD_ENDOINT0_SIZE];
+
+void usbd_control_reset (uint8_t rhport)
+{
+ (void) rhport;
+ tu_varclr(&_control_state);
+}
+
+void usbd_control_stall(uint8_t rhport)
+{
+ dcd_edpt_stall(rhport, 0);
+}
+
+bool usbd_control_status(uint8_t rhport, tusb_control_request_t const * request)
+{
+ // status direction is reversed to one in the setup packet
+ return dcd_edpt_xfer(rhport, request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN, NULL, 0);
+}
+
+// Each transaction is up to endpoint0's max packet size
+static bool start_control_data_xact(uint8_t rhport)
+{
+ uint16_t const xact_len = tu_min16(_control_state.total_len - _control_state.total_transferred, CFG_TUD_ENDOINT0_SIZE);
+
+ uint8_t ep_addr = EDPT_CTRL_OUT;
+
+ if ( _control_state.request.bmRequestType_bit.direction == TUSB_DIR_IN )
+ {
+ ep_addr = EDPT_CTRL_IN;
+ memcpy(_usbd_ctrl_buf, _control_state.buffer, xact_len);
+ }
+
+ return dcd_edpt_xfer(rhport, ep_addr, _usbd_ctrl_buf, xact_len);
+}
+
+// TODO may find a better way
+void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) )
+{
+ _control_state.complete_cb = fp;
+}
+
+bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len)
+{
+ _control_state.request = (*request);
+ _control_state.buffer = buffer;
+ _control_state.total_len = tu_min16(len, request->wLength);
+ _control_state.total_transferred = 0;
+
+ if ( buffer != NULL && len )
+ {
+ // Data stage
+ TU_ASSERT( start_control_data_xact(rhport) );
+ }else
+ {
+ // Status stage
+ TU_ASSERT( usbd_control_status(rhport, request) );
+ }
+
+ return true;
+}
+
+// callback when a transaction complete on DATA stage of control endpoint
+bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
+{
+ (void) result;
+ (void) ep_addr;
+
+ if ( _control_state.request.bmRequestType_bit.direction == TUSB_DIR_OUT )
+ {
+ memcpy(_control_state.buffer, _usbd_ctrl_buf, xferred_bytes);
+ }
+
+ _control_state.total_transferred += xferred_bytes;
+ _control_state.buffer += xferred_bytes;
+
+ if ( _control_state.total_len == _control_state.total_transferred || xferred_bytes < CFG_TUD_ENDOINT0_SIZE )
+ {
+ // DATA stage is complete
+ bool is_ok = true;
+
+ // invoke complete callback if set
+ // callback can still stall control in status phase e.g out data does not make sense
+ if ( _control_state.complete_cb )
+ {
+ is_ok = _control_state.complete_cb(rhport, &_control_state.request);
+ }
+
+ if ( is_ok )
+ {
+ // Send status
+ TU_ASSERT( usbd_control_status(rhport, &_control_state.request) );
+ }else
+ {
+ // stall due to callback
+ usbd_control_stall(rhport);
+ }
+ }
+ else
+ {
+ // More data to transfer
+ TU_ASSERT( start_control_data_xact(rhport) );
+ }
+
+ return true;
+}
+
+#endif
diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h new file mode 100644 index 000000000..798a871b1 --- /dev/null +++ b/src/device/usbd_pvt.h @@ -0,0 +1,82 @@ +/**************************************************************************/ +/*! + @file usbd_pvt.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ +#ifndef USBD_PVT_H_ +#define USBD_PVT_H_ + +#include "osal/osal.h" +#include "common/tusb_fifo.h" + +#ifdef __cplusplus + extern "C" { +#endif + +// Either point to tud_desc_set or usbd_auto_desc_set depending on CFG_TUD_DESC_AUTO +extern tud_desc_set_t const* usbd_desc_set; + +//--------------------------------------------------------------------+ +// INTERNAL API for stack management +//--------------------------------------------------------------------+ +bool usbd_init (void); +void usbd_task (void* param); + + +// Carry out Data and Status stage of control transfer +// - If len = 0, it is equivalent to sending status only +// - If len > wLength : it will be truncated +bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len); + +// Send STATUS (zero length) packet +bool usbd_control_status(uint8_t rhport, tusb_control_request_t const * request); + +// Stall control endpoint until new setup packet arrived +void usbd_control_stall(uint8_t rhport); + +/*------------------------------------------------------------------*/ +/* Helper + *------------------------------------------------------------------*/ +// helper to parse an pair of In and Out endpoint descriptors. They must be consecutive +bool usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_desc_ep, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in); + +void usbd_defer_func( osal_task_func_t func, void* param, bool in_isr ); + + +#ifdef __cplusplus + } +#endif + +#endif /* USBD_PVT_H_ */ diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c new file mode 100644 index 000000000..b46c9bc64 --- /dev/null +++ b/src/host/ehci/ehci.c @@ -0,0 +1,868 @@ +/**************************************************************************/
+/*!
+ @file ehci.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "common/tusb_common.h"
+
+#if TUSB_OPT_HOST_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX)
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "osal/osal.h"
+
+#include "../hcd.h"
+#include "../usbh_hcd.h"
+#include "ehci.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+
+//--------------------------------------------------------------------+
+// INTERNAL OBJECT & FUNCTION DECLARATION
+//--------------------------------------------------------------------+
+// Periodic frame list must be 4K alignment
+CFG_TUSB_MEM_SECTION ATTR_ALIGNED(4096) static ehci_data_t ehci_data;
+
+// EHCI portable
+uint32_t hcd_ehci_register_addr(uint8_t rhport);
+
+//--------------------------------------------------------------------+
+// PROTOTYPE
+//--------------------------------------------------------------------+
+static inline ehci_link_t* get_period_head(uint8_t rhport, uint8_t interval_ms)
+{
+ (void) rhport;
+ return (ehci_link_t*) &ehci_data.period_head_arr[ tu_log2( tu_min8(EHCI_FRAMELIST_SIZE, interval_ms) ) ];
+}
+
+static inline ehci_qhd_t* qhd_control(uint8_t dev_addr)
+{
+ return &ehci_data.control[dev_addr].qhd;
+}
+
+static inline ehci_qhd_t* qhd_async_head(uint8_t rhport)
+{
+ (void) rhport;
+ return qhd_control(0); // control qhd of dev0 is used as async head
+}
+
+static inline ehci_qtd_t* qtd_control(uint8_t dev_addr)
+{
+ return &ehci_data.control[dev_addr].qtd;
+}
+
+
+static inline ehci_qhd_t* qhd_next (ehci_qhd_t const * p_qhd);
+static inline ehci_qhd_t* qhd_find_free (void);
+static inline ehci_qhd_t* qhd_get_from_addr (uint8_t dev_addr, uint8_t ep_addr);
+
+// determine if a queue head has bus-related error
+static inline bool qhd_has_xact_error (ehci_qhd_t * p_qhd)
+{
+ return (p_qhd->qtd_overlay.buffer_err || p_qhd->qtd_overlay.babble_err || p_qhd->qtd_overlay.xact_err);
+ //p_qhd->qtd_overlay.non_hs_period_missed_uframe || p_qhd->qtd_overlay.pingstate_err TODO split transaction error
+}
+
+static void qhd_init (ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc);
+
+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 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);
+
+static bool ehci_init (uint8_t rhport);
+
+//--------------------------------------------------------------------+
+// HCD API
+//--------------------------------------------------------------------+
+bool hcd_init(void)
+{
+ tu_memclr(&ehci_data, sizeof(ehci_data_t));
+ return ehci_init(TUH_OPT_RHPORT);
+}
+
+void hcd_port_reset(uint8_t rhport)
+{
+ (void) rhport;
+
+ ehci_registers_t* regs = ehci_data.regs;
+
+ regs->portsc_bm.port_enabled = 0; // disable port before reset
+ regs->portsc_bm.port_reset = 1;
+}
+
+bool hcd_port_connect_status(uint8_t rhport)
+{
+ (void) rhport;
+ return ehci_data.regs->portsc_bm.current_connect_status;
+}
+
+tusb_speed_t hcd_port_speed_get(uint8_t rhport)
+{
+ (void) rhport;
+ return (tusb_speed_t) ehci_data.regs->portsc_bm.nxp_port_speed; // NXP specific port speed
+}
+
+static void list_remove_qhd_by_addr(ehci_link_t* list_head, uint8_t dev_addr)
+{
+ for(ehci_link_t* prev = list_head;
+ !prev->terminate && (tu_align32(prev->address) != (uint32_t) list_head);
+ prev = list_next(prev) )
+ {
+ // TODO check type for ISO iTD and siTD
+ ehci_qhd_t* qhd = (ehci_qhd_t*) list_next(prev);
+ if ( qhd->dev_addr == dev_addr )
+ {
+ // TODO deactive all TD, wait for QHD to inactive before removal
+ prev->address = qhd->next.address;
+
+ // EHCI 4.8.2 link the removed qhd to async head (which always reachable by Host Controller)
+ qhd->next.address = ((uint32_t) list_head) | (EHCI_QTYPE_QHD << 1);
+
+ if ( qhd->int_smask )
+ {
+ // period list queue element is guarantee to be free in the next frame (1 ms)
+ qhd->used = 0;
+ }else
+ {
+ // async list use async advance handshake
+ // mark as removing, will completely re-usable when async advance isr occurs
+ qhd->removing = 1;
+ }
+ }
+ }
+}
+
+// Close all opened endpoint belong to this device
+void hcd_device_close(uint8_t rhport, uint8_t dev_addr)
+{
+ // skip dev0
+ if (dev_addr == 0) return;
+
+ // Remove from async list
+ list_remove_qhd_by_addr( (ehci_link_t*) qhd_async_head(rhport), dev_addr );
+
+ // Remove from all interval period list
+ for(uint8_t i = 0; i < TU_ARRAY_SZIE(ehci_data.period_head_arr); i++)
+ {
+ list_remove_qhd_by_addr( (ehci_link_t*) &ehci_data.period_head_arr[i], dev_addr);
+ }
+
+ // Async doorbell (EHCI 4.8.2 for operational details)
+ ehci_data.regs->command_bm.async_adv_doorbell = 1;
+}
+
+// EHCI controller init
+static bool ehci_init(uint8_t rhport)
+{
+ ehci_data.regs = (ehci_registers_t* ) hcd_ehci_register_addr(rhport);
+
+ ehci_registers_t* regs = ehci_data.regs;
+
+ //------------- CTRLDSSEGMENT Register (skip) -------------//
+ //------------- USB INT Register -------------//
+ regs->inten = 0; // 1. disable all the interrupt
+ regs->status = EHCI_INT_MASK_ALL; // 2. clear all status
+
+ regs->inten = EHCI_INT_MASK_ERROR | EHCI_INT_MASK_PORT_CHANGE | EHCI_INT_MASK_ASYNC_ADVANCE |
+ EHCI_INT_MASK_NXP_PERIODIC | EHCI_INT_MASK_NXP_ASYNC ;
+
+ //------------- Asynchronous List -------------//
+ ehci_qhd_t * const async_head = qhd_async_head(rhport);
+ tu_memclr(async_head, sizeof(ehci_qhd_t));
+
+ async_head->next.address = (uint32_t) async_head; // circular list, next is itself
+ async_head->next.type = EHCI_QTYPE_QHD;
+ async_head->head_list_flag = 1;
+ async_head->qtd_overlay.halted = 1; // inactive most of time
+ async_head->qtd_overlay.next.terminate = 1; // TODO removed if verified
+
+ regs->async_list_addr = (uint32_t) async_head;
+
+ //------------- Periodic List -------------//
+ // Build the polling interval tree with 1 ms, 2 ms, 4 ms and 8 ms (framesize) only
+ for(uint32_t i=0; i<4; i++)
+ {
+ ehci_data.period_head_arr[i].int_smask = 1; // queue head in period list must have smask non-zero
+ ehci_data.period_head_arr[i].qtd_overlay.halted = 1; // dummy node, always inactive
+ }
+
+ ehci_link_t * const framelist = ehci_data.period_framelist;
+ ehci_link_t * const period_1ms = get_period_head(rhport, 1);
+ // all links --> period_head_arr[0] (1ms)
+ // 0, 2, 4, 6 etc --> period_head_arr[1] (2ms)
+ // 1, 5 --> period_head_arr[2] (4ms)
+ // 3 --> period_head_arr[3] (8ms)
+
+ // TODO EHCI_FRAMELIST_SIZE with other size than 8
+ for(uint32_t i=0; i<EHCI_FRAMELIST_SIZE; i++)
+ {
+ framelist[i].address = (uint32_t) period_1ms;
+ framelist[i].type = EHCI_QTYPE_QHD;
+ }
+
+ for(uint32_t i=0; i<EHCI_FRAMELIST_SIZE; i+=2)
+ {
+ list_insert(framelist + i, get_period_head(rhport, 2), EHCI_QTYPE_QHD);
+ }
+
+ for(uint32_t i=1; i<EHCI_FRAMELIST_SIZE; i+=4)
+ {
+ list_insert(framelist + i, get_period_head(rhport, 4), EHCI_QTYPE_QHD);
+ }
+
+ list_insert(framelist+3, get_period_head(rhport, 8), EHCI_QTYPE_QHD);
+
+ period_1ms->terminate = 1;
+
+ regs->periodic_list_base = (uint32_t) framelist;
+
+ //------------- TT Control (NXP only) -------------//
+ regs->nxp_tt_control = 0;
+
+ //------------- USB CMD Register -------------//
+ regs->command |= BIT_(EHCI_USBCMD_POS_RUN_STOP) | BIT_(EHCI_USBCMD_POS_ASYNC_ENABLE)
+ | BIT_(EHCI_USBCMD_POS_PERIOD_ENABLE) // TODO enable period list only there is int/iso endpoint
+ | ((EHCI_CFG_FRAMELIST_SIZE_BITS & BIN8(011)) << EHCI_USBCMD_POS_FRAMELIST_SZIE)
+ | ((EHCI_CFG_FRAMELIST_SIZE_BITS >> 2) << EHCI_USBCMD_POS_NXP_FRAMELIST_SIZE_MSB);
+
+ //------------- ConfigFlag Register (skip) -------------//
+ regs->portsc_bm.port_power = 1; // enable port power
+
+ return true;
+}
+
+#if 0
+static void ehci_stop(uint8_t rhport)
+{
+ (void) rhport;
+
+ ehci_registers_t* regs = ehci_data.regs;
+
+ regs->command_bm.run_stop = 0;
+
+ // USB Spec: controller has to stop within 16 uframe = 2 frames
+ while( regs->status_bm.hc_halted == 0 ) {}
+}
+#endif
+
+//--------------------------------------------------------------------+
+// CONTROL PIPE API
+//--------------------------------------------------------------------+
+bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen)
+{
+ (void) rhport;
+
+ uint8_t const epnum = tu_edpt_number(ep_addr);
+ uint8_t const dir = tu_edpt_dir(ep_addr);
+
+ // FIXME control only for now
+ if ( epnum == 0 )
+ {
+ ehci_qhd_t* qhd = qhd_control(dev_addr);
+ ehci_qtd_t* qtd = qtd_control(dev_addr);
+
+ qtd_init(qtd, buffer, buflen);
+
+ // first first data toggle is always 1 (data & setup stage)
+ qtd->data_toggle = 1;
+ qtd->pid = dir ? EHCI_PID_IN : EHCI_PID_OUT;
+ qtd->int_on_complete = 1;
+ qtd->next.terminate = 1;
+
+ // sw region
+ qhd->p_qtd_list_head = qtd;
+ qhd->p_qtd_list_tail = qtd;
+
+ // attach TD
+ qhd->qtd_overlay.next.address = (uint32_t) qtd;
+ }
+
+ return true;
+}
+
+bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8])
+{
+ (void) rhport;
+
+ ehci_qhd_t* qhd = &ehci_data.control[dev_addr].qhd;
+ ehci_qtd_t* td = &ehci_data.control[dev_addr].qtd;
+
+ qtd_init(td, (void*) setup_packet, 8);
+ td->pid = EHCI_PID_SETUP;
+ td->int_on_complete = 1;
+ td->next.terminate = 1;
+
+ // sw region
+ qhd->p_qtd_list_head = td;
+ qhd->p_qtd_list_tail = td;
+
+ // attach TD
+ qhd->qtd_overlay.next.address = (uint32_t) td;
+
+ return true;
+}
+
+//--------------------------------------------------------------------+
+// BULK/INT/ISO PIPE API
+//--------------------------------------------------------------------+
+bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc)
+{
+ (void) rhport;
+
+ // TODO not support ISO yet
+ TU_ASSERT (ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS);
+
+ //------------- Prepare Queue Head -------------//
+ ehci_qhd_t * p_qhd;
+
+ if ( ep_desc->bEndpointAddress == 0 )
+ {
+ p_qhd = qhd_control(dev_addr);
+ }else
+ {
+ p_qhd = qhd_find_free();
+ }
+ TU_ASSERT(p_qhd);
+
+ qhd_init(p_qhd, dev_addr, ep_desc);
+
+ // control of dev0 is always present as async head
+ if ( dev_addr == 0 ) return true;
+
+ // Insert to list
+ ehci_link_t * list_head;
+
+ switch (ep_desc->bmAttributes.xfer)
+ {
+ case TUSB_XFER_CONTROL:
+ case TUSB_XFER_BULK:
+ list_head = (ehci_link_t*) qhd_async_head(rhport);
+ break;
+
+ case TUSB_XFER_INTERRUPT:
+ list_head = get_period_head(rhport, p_qhd->interval_ms);
+ break;
+
+ case TUSB_XFER_ISOCHRONOUS:
+ // TODO iso is not supported
+ break;
+
+ default: break;
+ }
+
+ // TODO might need to disable async/period list
+ list_insert( list_head, (ehci_link_t*) p_qhd, EHCI_QTYPE_QHD);
+
+ return true;
+}
+
+bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes)
+{
+ //------------- set up QTD -------------//
+ ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr);
+ ehci_qtd_t *p_qtd = qtd_find_free();
+
+ TU_ASSERT(p_qtd);
+
+ qtd_init(p_qtd, buffer, total_bytes);
+ p_qtd->pid = p_qhd->pid;
+
+ //------------- insert TD to TD list -------------//
+ qtd_insert_to_qhd(p_qhd, p_qtd);
+
+ return true;
+}
+
+bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete)
+{
+ TU_ASSERT ( hcd_pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes) );
+
+ ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr);
+
+ if ( int_on_complete )
+ { // the just added qtd is pointed by list_tail
+ p_qhd->p_qtd_list_tail->int_on_complete = 1;
+ }
+ p_qhd->qtd_overlay.next.address = (uint32_t) p_qhd->p_qtd_list_head; // attach head QTD to QHD start transferring
+
+ return true;
+}
+
+bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr)
+{
+ ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr);
+ return !p_qhd->qtd_overlay.halted && (p_qhd->p_qtd_list_head != NULL);
+}
+
+bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr)
+{
+ ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr);
+ return p_qhd->qtd_overlay.halted && !qhd_has_xact_error(p_qhd);
+}
+
+bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr)
+{
+ ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr);
+ p_qhd->qtd_overlay.halted = 0;
+ // TODO reset data toggle ?
+ return true;
+}
+
+//--------------------------------------------------------------------+
+// EHCI Interrupt Handler
+//--------------------------------------------------------------------+
+
+// async_advance is handshake between usb stack & ehci controller.
+// This isr mean it is safe to modify previously removed queue head from async list.
+// In tinyusb, queue head is only removed when device is unplugged.
+static void async_advance_isr(uint8_t rhport)
+{
+ (void) rhport;
+
+ ehci_qhd_t* qhd_pool = ehci_data.qhd_pool;
+ for(uint32_t i = 0; i < HCD_MAX_ENDPOINT; i++)
+ {
+ if ( qhd_pool[i].removing )
+ {
+ qhd_pool[i].removing = 0;
+ qhd_pool[i].used = 0;
+ }
+ }
+}
+
+static void port_connect_status_change_isr(uint8_t hostid)
+{
+ // NOTE There is an sequence plug->unplug->…..-> plug if device is powering with pre-plugged device
+ if (ehci_data.regs->portsc_bm.current_connect_status)
+ {
+ hcd_port_reset(hostid);
+ hcd_event_device_attach(hostid);
+ }else // device unplugged
+ {
+ hcd_event_device_remove(hostid);
+ }
+}
+
+static void qhd_xfer_complete_isr(ehci_qhd_t * p_qhd)
+{
+ // free all TDs from the head td to the first active TD
+ while(p_qhd->p_qtd_list_head != NULL && !p_qhd->p_qtd_list_head->active)
+ {
+ // TD need to be freed and removed from qhd, before invoking callback
+ bool is_ioc = (p_qhd->p_qtd_list_head->int_on_complete != 0);
+ p_qhd->total_xferred_bytes += p_qhd->p_qtd_list_head->expected_bytes - p_qhd->p_qtd_list_head->total_bytes;
+
+ p_qhd->p_qtd_list_head->used = 0; // free QTD
+ qtd_remove_1st_from_qhd(p_qhd);
+
+ if (is_ioc)
+ {
+ // end of request
+ // call USBH callback
+ hcd_event_xfer_complete(p_qhd->dev_addr, tu_edpt_addr(p_qhd->ep_number, p_qhd->pid == EHCI_PID_IN ? 1 : 0), XFER_RESULT_SUCCESS, p_qhd->total_xferred_bytes);
+ p_qhd->total_xferred_bytes = 0;
+ }
+ }
+}
+
+static void async_list_xfer_complete_isr(ehci_qhd_t * const async_head)
+{
+ ehci_qhd_t *p_qhd = async_head;
+ do
+ {
+ if ( !p_qhd->qtd_overlay.halted ) // halted or error is processed in error isr
+ {
+ qhd_xfer_complete_isr(p_qhd);
+ }
+ p_qhd = qhd_next(p_qhd);
+ }while(p_qhd != async_head); // async list traversal, stop if loop around
+}
+
+static void period_list_xfer_complete_isr(uint8_t hostid, uint8_t interval_ms)
+{
+ uint8_t max_loop = 0;
+ uint32_t const period_1ms_addr = (uint32_t) get_period_head(hostid, 1);
+ ehci_link_t next_item = * get_period_head(hostid, interval_ms);
+
+ // TODO abstract max loop guard for period
+ while( !next_item.terminate &&
+ !(interval_ms > 1 && period_1ms_addr == tu_align32(next_item.address)) &&
+ max_loop < (HCD_MAX_ENDPOINT + EHCI_MAX_ITD + EHCI_MAX_SITD)*CFG_TUSB_HOST_DEVICE_MAX)
+ {
+ switch ( next_item.type )
+ {
+ case EHCI_QTYPE_QHD:
+ {
+ ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) tu_align32(next_item.address);
+ if ( !p_qhd_int->qtd_overlay.halted )
+ {
+ qhd_xfer_complete_isr(p_qhd_int);
+ }
+ }
+ break;
+
+ case EHCI_QTYPE_ITD: // TODO support hs/fs ISO
+ case EHCI_QTYPE_SITD:
+ case EHCI_QTYPE_FSTN:
+
+ default: break;
+ }
+
+ next_item = *list_next(&next_item);
+ max_loop++;
+ }
+}
+
+static void qhd_xfer_error_isr(ehci_qhd_t * p_qhd)
+{
+ if ( (p_qhd->dev_addr != 0 && p_qhd->qtd_overlay.halted) || // addr0 cannot be protocol STALL
+ qhd_has_xact_error(p_qhd) )
+ {
+ // current qhd has error in transaction
+ xfer_result_t error_event;
+
+ // no error bits are set, endpoint is halted due to STALL
+ error_event = qhd_has_xact_error(p_qhd) ? XFER_RESULT_FAILED : XFER_RESULT_STALLED;
+
+ p_qhd->total_xferred_bytes += p_qhd->p_qtd_list_head->expected_bytes - p_qhd->p_qtd_list_head->total_bytes;
+
+// if ( XFER_RESULT_FAILED == error_event ) TU_BREAKPOINT(); // TODO skip unplugged device
+
+ p_qhd->p_qtd_list_head->used = 0; // free QTD
+ qtd_remove_1st_from_qhd(p_qhd);
+
+ if ( 0 == p_qhd->ep_number )
+ {
+ // control cannot be halted --> clear all qtd list
+ p_qhd->p_qtd_list_head = NULL;
+ p_qhd->p_qtd_list_tail = NULL;
+
+ p_qhd->qtd_overlay.next.terminate = 1;
+ p_qhd->qtd_overlay.alternate.terminate = 1;
+ p_qhd->qtd_overlay.halted = 0;
+
+ ehci_qtd_t *p_setup = qtd_control(p_qhd->dev_addr);
+ p_setup->used = 0;
+ }
+
+ // call USBH callback
+ hcd_event_xfer_complete(p_qhd->dev_addr, tu_edpt_addr(p_qhd->ep_number, p_qhd->pid == EHCI_PID_IN ? 1 : 0), error_event, p_qhd->total_xferred_bytes);
+
+ p_qhd->total_xferred_bytes = 0;
+ }
+}
+
+static void xfer_error_isr(uint8_t hostid)
+{
+ //------------- async list -------------//
+ ehci_qhd_t * const async_head = qhd_async_head(hostid);
+ ehci_qhd_t *p_qhd = async_head;
+ do
+ {
+ qhd_xfer_error_isr( p_qhd );
+ p_qhd = qhd_next(p_qhd);
+ }while(p_qhd != async_head); // async list traversal, stop if loop around
+
+ //------------- TODO refractor period list -------------//
+ uint32_t const period_1ms_addr = (uint32_t) get_period_head(hostid, 1);
+ for (uint8_t interval_ms=1; interval_ms <= EHCI_FRAMELIST_SIZE; interval_ms *= 2)
+ {
+ ehci_link_t next_item = * get_period_head(hostid, interval_ms);
+
+ // TODO abstract max loop guard for period
+ while( !next_item.terminate &&
+ !(interval_ms > 1 && period_1ms_addr == tu_align32(next_item.address)) )
+ {
+ switch ( next_item.type )
+ {
+ case EHCI_QTYPE_QHD:
+ {
+ ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) tu_align32(next_item.address);
+ qhd_xfer_error_isr(p_qhd_int);
+ }
+ break;
+
+ // TODO support hs/fs ISO
+ case EHCI_QTYPE_ITD:
+ case EHCI_QTYPE_SITD:
+ case EHCI_QTYPE_FSTN:
+ default: break;
+ }
+
+ next_item = *list_next(&next_item);
+ }
+ }
+}
+
+//------------- Host Controller Driver's Interrupt Handler -------------//
+void hal_hcd_isr(uint8_t rhport)
+{
+ ehci_registers_t* regs = ehci_data.regs;
+
+ uint32_t int_status = regs->status;
+ int_status &= regs->inten;
+
+ regs->status |= int_status; // Acknowledge handled interrupt
+
+ if (int_status == 0) return;
+
+ if (int_status & EHCI_INT_MASK_PORT_CHANGE)
+ {
+ uint32_t port_status = regs->portsc & EHCI_PORTSC_MASK_ALL;
+
+ if (regs->portsc_bm.connect_status_change)
+ {
+ port_connect_status_change_isr(rhport);
+ }
+
+ regs->portsc |= port_status; // Acknowledge change bits in portsc
+ }
+
+ if (int_status & EHCI_INT_MASK_ERROR)
+ {
+ xfer_error_isr(rhport);
+ }
+
+ //------------- some QTD/SITD/ITD with IOC set is completed -------------//
+ if (int_status & EHCI_INT_MASK_NXP_ASYNC)
+ {
+ async_list_xfer_complete_isr( qhd_async_head(rhport) );
+ }
+
+ if (int_status & EHCI_INT_MASK_NXP_PERIODIC)
+ {
+ for (uint8_t i=1; i <= EHCI_FRAMELIST_SIZE; i *= 2)
+ {
+ period_list_xfer_complete_isr( rhport, i );
+ }
+ }
+
+ //------------- There is some removed async previously -------------//
+ if (int_status & EHCI_INT_MASK_ASYNC_ADVANCE) // need to place after EHCI_INT_MASK_NXP_ASYNC
+ {
+ async_advance_isr(rhport);
+ }
+}
+
+//--------------------------------------------------------------------+
+// HELPER
+//--------------------------------------------------------------------+
+
+
+//------------- queue head helper -------------//
+static inline ehci_qhd_t* qhd_find_free (void)
+{
+ for (uint32_t i=0; i<HCD_MAX_ENDPOINT; i++)
+ {
+ if ( !ehci_data.qhd_pool[i].used ) return &ehci_data.qhd_pool[i];
+ }
+
+ return NULL;
+}
+
+static inline ehci_qhd_t* qhd_next(ehci_qhd_t const * p_qhd)
+{
+ return (ehci_qhd_t*) tu_align32(p_qhd->next.address);
+}
+
+static inline ehci_qhd_t* qhd_get_from_addr(uint8_t dev_addr, uint8_t ep_addr)
+{
+ ehci_qhd_t* qhd_pool = ehci_data.qhd_pool;
+
+ for(uint32_t i=0; i<HCD_MAX_ENDPOINT; i++)
+ {
+ if ( (qhd_pool[i].dev_addr == dev_addr) &&
+ ep_addr == tu_edpt_addr(qhd_pool[i].ep_number, qhd_pool[i].pid) )
+ {
+ return &qhd_pool[i];
+ }
+ }
+
+ return NULL;
+}
+
+//------------- TD helper -------------//
+static inline ehci_qtd_t* qtd_find_free(void)
+{
+ for (uint32_t i=0; i<HCD_MAX_XFER; i++)
+ {
+ if ( !ehci_data.qtd_pool[i].used ) return &ehci_data.qtd_pool[i];
+ }
+
+ return NULL;
+}
+
+static inline ehci_qtd_t* qtd_next(ehci_qtd_t const * p_qtd )
+{
+ return (ehci_qtd_t*) tu_align32(p_qtd->next.address);
+}
+
+static inline void qtd_remove_1st_from_qhd(ehci_qhd_t *p_qhd)
+{
+ if (p_qhd->p_qtd_list_head == p_qhd->p_qtd_list_tail) // last TD --> make it NULL
+ {
+ p_qhd->p_qtd_list_head = p_qhd->p_qtd_list_tail = NULL;
+ }else
+ {
+ p_qhd->p_qtd_list_head = qtd_next( p_qhd->p_qtd_list_head );
+ }
+}
+
+static inline void qtd_insert_to_qhd(ehci_qhd_t *p_qhd, ehci_qtd_t *p_qtd_new)
+{
+ if (p_qhd->p_qtd_list_head == NULL) // empty list
+ {
+ p_qhd->p_qtd_list_head = p_qhd->p_qtd_list_tail = p_qtd_new;
+ }else
+ {
+ p_qhd->p_qtd_list_tail->next.address = (uint32_t) p_qtd_new;
+ p_qhd->p_qtd_list_tail = p_qtd_new;
+ }
+}
+
+static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc)
+{
+ // address 0 is used as async head, which always on the list --> cannot be cleared (ehci halted otherwise)
+ if (dev_addr != 0)
+ {
+ tu_memclr(p_qhd, sizeof(ehci_qhd_t));
+ }
+
+ uint8_t const xfer_type = ep_desc->bmAttributes.xfer;
+ uint8_t const interval = ep_desc->bInterval;
+
+ p_qhd->dev_addr = dev_addr;
+ p_qhd->fl_inactive_next_xact = 0;
+ p_qhd->ep_number = tu_edpt_number(ep_desc->bEndpointAddress);
+ p_qhd->ep_speed = _usbh_devices[dev_addr].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->fl_ctrl_ep_flag = ((xfer_type == TUSB_XFER_CONTROL) && (p_qhd->ep_speed != TUSB_SPEED_HIGH)) ? 1 : 0;
+ p_qhd->nak_reload = 0;
+
+ // Bulk/Control -> smask = cmask = 0
+ // TODO Isochronous
+ if (TUSB_XFER_INTERRUPT == xfer_type)
+ {
+ if (TUSB_SPEED_HIGH == p_qhd->ep_speed)
+ {
+ TU_ASSERT( interval <= 16, );
+ if ( interval < 4) // sub milisecond interval
+ {
+ p_qhd->interval_ms = 0;
+ p_qhd->int_smask = (interval == 1) ? BIN8(11111111) :
+ (interval == 2) ? BIN8(10101010) : BIN8(01000100);
+ }else
+ {
+ p_qhd->interval_ms = (uint8_t) tu_min16( 1 << (interval-4), 255 );
+ p_qhd->int_smask = BIT_(interval % 8);
+ }
+ }else
+ {
+ TU_ASSERT( 0 != interval, );
+ // Full/Low: 4.12.2.1 (EHCI) case 1 schedule start split at 1 us & complete split at 2,3,4 uframes
+ p_qhd->int_smask = 0x01;
+ p_qhd->fl_int_cmask = BIN8(11100);
+ p_qhd->interval_ms = interval;
+ }
+ }else
+ {
+ p_qhd->int_smask = p_qhd->fl_int_cmask = 0;
+ }
+
+ p_qhd->fl_hub_addr = _usbh_devices[dev_addr].hub_addr;
+ p_qhd->fl_hub_port = _usbh_devices[dev_addr].hub_port;
+ p_qhd->mult = 1; // TODO not use high bandwidth/park mode yet
+
+ //------------- HCD Management Data -------------//
+ p_qhd->used = 1;
+ p_qhd->removing = 0;
+ p_qhd->p_qtd_list_head = NULL;
+ p_qhd->p_qtd_list_tail = NULL;
+ p_qhd->pid = tu_edpt_dir(ep_desc->bEndpointAddress) ? EHCI_PID_IN : EHCI_PID_OUT; // PID for TD under this endpoint
+
+ //------------- active, but no TD list -------------//
+ p_qhd->qtd_overlay.halted = 0;
+ p_qhd->qtd_overlay.next.terminate = 1;
+ p_qhd->qtd_overlay.alternate.terminate = 1;
+ if (TUSB_XFER_BULK == xfer_type && p_qhd->ep_speed == TUSB_SPEED_HIGH && p_qhd->pid == EHCI_PID_OUT)
+ {
+ p_qhd->qtd_overlay.ping_err = 1; // do PING for Highspeed Bulk OUT, EHCI section 4.11
+ }
+}
+
+static void qtd_init(ehci_qtd_t* p_qtd, void* buffer, uint16_t total_bytes)
+{
+ tu_memclr(p_qtd, sizeof(ehci_qtd_t));
+
+ p_qtd->used = 1;
+
+ p_qtd->next.terminate = 1; // init to null
+ p_qtd->alternate.terminate = 1; // not used, always set to terminated
+ p_qtd->active = 1;
+ p_qtd->err_count = 3; // TODO 3 consecutive errors tolerance
+ p_qtd->data_toggle = 0;
+ p_qtd->total_bytes = total_bytes;
+ p_qtd->expected_bytes = total_bytes;
+
+ p_qtd->buffer[0] = (uint32_t) buffer;
+ for(uint8_t i=1; i<5; i++)
+ {
+ p_qtd->buffer[i] |= tu_align4k( p_qtd->buffer[i-1] ) + 4096;
+ }
+}
+
+//------------- List Managing Helper -------------//
+static inline void list_insert(ehci_link_t *current, ehci_link_t *new, uint8_t new_type)
+{
+ new->address = current->address;
+ current->address = ((uint32_t) new) | (new_type << 1);
+}
+
+static inline ehci_link_t* list_next(ehci_link_t *p_link_pointer)
+{
+ return (ehci_link_t*) tu_align32(p_link_pointer->address);
+}
+
+#endif
diff --git a/src/host/ehci/ehci.h b/src/host/ehci/ehci.h new file mode 100644 index 000000000..c1c274793 --- /dev/null +++ b/src/host/ehci/ehci.h @@ -0,0 +1,470 @@ +/**************************************************************************/ +/*! + @file ehci.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup Group_HCD + * @{ + * \defgroup EHCI + * \brief EHCI driver. All documents sources mentioned here (eg section 3.5) is referring to EHCI Specs unless state otherwise + * @{ */ + +#ifndef _TUSB_EHCI_H_ +#define _TUSB_EHCI_H_ + +#include "common/tusb_common.h" +#include "../hcd.h" + +/* Abbreviation + * HC: Host Controller + * HCD: Host Controller Driver + * QHD: Queue Head for non-ISO transfer + * QTD: Queue Transfer Descriptor for non-ISO transfer + * ITD: Iso Transfer Descriptor for highspeed + * SITD: Split ISO Transfer Descriptor for full-speed + * SMASK: Start Split mask for Slipt Transaction + * CMASK: Complete Split mask for Slipt Transaction +*/ + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// EHCI CONFIGURATION & CONSTANTS +//--------------------------------------------------------------------+ +#define EHCI_CFG_FRAMELIST_SIZE_BITS 7 /// Framelist Size (NXP specific) (0:1024) - (1:512) - (2:256) - (3:128) - (4:64) - (5:32) - (6:16) - (7:8) +#define EHCI_FRAMELIST_SIZE (1024 >> EHCI_CFG_FRAMELIST_SIZE_BITS) + +// TODO merge OHCI with EHCI +enum { + EHCI_MAX_ITD = 4, + EHCI_MAX_SITD = 16 +}; + +//------------- Validation -------------// +TU_VERIFY_STATIC(EHCI_CFG_FRAMELIST_SIZE_BITS <= 7, "incorrect value"); + +//--------------------------------------------------------------------+ +// EHCI Data Structure +//--------------------------------------------------------------------+ +enum +{ + EHCI_QTYPE_ITD = 0 , + EHCI_QTYPE_QHD , + EHCI_QTYPE_SITD , + EHCI_QTYPE_FSTN +}; + +/// EHCI PID +enum +{ + EHCI_PID_OUT = 0 , + EHCI_PID_IN , + EHCI_PID_SETUP +}; + +/// Link pointer +typedef union { + uint32_t address; + struct { + uint32_t terminate : 1; + uint32_t type : 2; + }; +}ehci_link_t; + +/// Queue Element Transfer Descriptor +/// Qtd is used to declare overlay in ehci_qhd_t -> cannot be declared with ATTR_ALIGNED(32) +typedef struct +{ + // Word 0: Next QTD Pointer + ehci_link_t next; + + // Word 1: Alternate Next QTD Pointer (not used) + union{ + ehci_link_t alternate; + struct { + uint32_t : 5; + uint32_t used : 1; + uint32_t : 10; + uint32_t expected_bytes : 16; + }; + }; + + // Word 2: qTQ Token + volatile uint32_t ping_err : 1 ; ///< For Highspeed: 0 Out, 1 Ping. Full/Slow used as error indicator + volatile uint32_t non_hs_split_state : 1 ; ///< Used by HC to track the state of slipt transaction + volatile uint32_t non_hs_missed_uframe : 1 ; ///< HC misses a complete slip transaction + volatile uint32_t xact_err : 1 ; ///< Error (Timeout, CRC, Bad PID ... ) + volatile uint32_t babble_err : 1 ; ///< Babble detected, also set Halted bit to 1 + volatile uint32_t buffer_err : 1 ; ///< Data overrun/underrun error + volatile uint32_t halted : 1 ; ///< Serious error or STALL received + volatile uint32_t active : 1 ; ///< Start transfer, clear by HC when complete + + uint32_t pid : 2 ; ///< 0: OUT, 1: IN, 2 Setup + volatile uint32_t err_count : 2 ; ///< Error Counter of consecutive errors + volatile uint32_t current_page : 3 ; ///< Index into the qTD buffer pointer list + uint32_t int_on_complete : 1 ; ///< Interrupt on complete + volatile uint32_t total_bytes : 15 ; ///< Transfer bytes, decreased during transaction + volatile uint32_t data_toggle : 1 ; ///< Data Toogle bit + + + /// Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page + uint32_t buffer[5]; +} ehci_qtd_t; + +TU_VERIFY_STATIC( sizeof(ehci_qtd_t) == 32, "size is not correct" ); + +/// Queue Head +typedef struct ATTR_ALIGNED(32) +{ + // Word 0: Next QHD + ehci_link_t next; + + // Word 1: Endpoint Characteristics + uint32_t dev_addr : 7 ; ///< device address + uint32_t fl_inactive_next_xact : 1 ; ///< Only valid for Periodic with Full/Slow speed + uint32_t ep_number : 4 ; ///< EP number + uint32_t ep_speed : 2 ; ///< 0: Full, 1: Low, 2: High + uint32_t data_toggle_control : 1 ; ///< 0: use DT in qHD, 1: use DT in qTD + uint32_t head_list_flag : 1 ; ///< Head of the queue + uint32_t max_packet_size : 11 ; ///< Max packet size + uint32_t fl_ctrl_ep_flag : 1 ; ///< 1 if is Full/Low speed control endpoint + uint32_t nak_reload : 4 ; ///< Used by HC + + // Word 2: Endpoint Capabilities + uint32_t int_smask : 8 ; ///< Interrupt Schedule Mask + uint32_t fl_int_cmask : 8 ; ///< Split Completion Mask for Full/Slow speed + uint32_t fl_hub_addr : 7 ; ///< Hub Address for Full/Slow speed + uint32_t fl_hub_port : 7 ; ///< Hub Port for Full/Slow speed + uint32_t mult : 2 ; ///< Transaction per micro frame + + // Word 3: Current qTD Pointer + volatile uint32_t qtd_addr; + + // Word 4-11: Transfer Overlay + volatile ehci_qtd_t qtd_overlay; + + //--------------------------------------------------------------------+ + /// Due to the fact QHD is 32 bytes aligned but occupies only 48 bytes + /// thus there are 16 bytes padding free that we can make use of. + //--------------------------------------------------------------------+ + uint8_t used; + uint8_t removing; // removed from asyn list, waiting for async advance + uint8_t pid; + uint8_t interval_ms; // polling interval in frames (or milisecond) + + uint16_t total_xferred_bytes; // number of bytes xferred until a qtd with ioc bit set + uint8_t reserved2[2]; + + ehci_qtd_t * volatile p_qtd_list_head; // head of the scheduled TD list + ehci_qtd_t * volatile p_qtd_list_tail; // tail of the scheduled TD list +} ehci_qhd_t; + +TU_VERIFY_STATIC( sizeof(ehci_qhd_t) == 64, "size is not correct" ); + +/// Highspeed Isochronous Transfer Descriptor (section 3.3) +typedef struct ATTR_ALIGNED(32) { + // Word 0: Next Link Pointer + ehci_link_t next; + + // Word 1-8: iTD Transaction Status and Control List + struct { + // iTD Control + volatile uint32_t offset : 12 ; ///< This field is a value that is an offset, expressed in bytes, from the beginning of a buffer. + volatile uint32_t page_select : 3 ; ///< These bits are set by software to indicate which of the buffer page pointers the offset field in this slot should be concatenated to produce the starting memory address for this transaction. The valid range of values for this field is 0 to 6 + uint32_t int_on_complete : 1 ; ///< If this bit is set to a one, it specifies that when this transaction completes, the Host Controller should issue an interrupt at the next interrupt threshold + volatile uint32_t length : 12 ; ///< For an OUT, this field is the number of data bytes the host controller will send during the transaction. The host controller is not required to update this field to reflect the actual number of bytes transferred during the transfer + ///< For an IN, the initial value of the field is the number of bytes the host expects the endpoint to deliver. During the status update, the host controller writes back the number of bytes successfully received. The value in this register is the actual byte count + // iTD Status + volatile uint32_t error : 1 ; ///< Set to a one by the Host Controller during status update in the case where the host did not receive a valid response from the device (Timeout, CRC, Bad PID, etc.). This bit may only be set for isochronous IN transactions. + volatile uint32_t babble_err : 1 ; ///< Set to a 1 by the Host Controller during status update when a babble is detected during the transaction + volatile uint32_t buffer_err : 1 ; ///< Set to a 1 by the Host Controller during status update to indicate that the Host Controller is unable to keep up with the reception of incoming data (overrun) or is unable to supply data fast enough during transmission (underrun). + volatile uint32_t active : 1 ; ///< Set to 1 by software to enable the execution of an isochronous transaction by the Host Controller + } xact[8]; + + // Word 9-15 Buffer Page Pointer List (Plus) + uint32_t BufferPointer[7]; + +// // FIXME: Store meta data into buffer pointer reserved for saving memory +// /*---------- HCD Area ----------*/ +// uint32_t used; +// uint32_t IhdIdx; +// uint32_t reserved[6]; +} ehci_itd_t; + +TU_VERIFY_STATIC( sizeof(ehci_itd_t) == 64, "size is not correct" ); + +/// Split (Full-Speed) Isochronous Transfer Descriptor +typedef struct ATTR_ALIGNED(32) +{ + // Word 0: Next Link Pointer + ehci_link_t next; + + // Word 1: siTD Endpoint Characteristics + uint32_t dev_addr : 7; ///< This field selects the specific device serving as the data source or sink. + uint32_t : 1; ///< reserved + uint32_t ep_number : 4; ///< This 4-bit field selects the particular endpoint number on the device serving as the data source or sink. + uint32_t : 4; ///< This field is reserved and should be set to zero. + uint32_t hub_addr : 7; ///< This field holds the device address of the transaction translators’ hub. + uint32_t : 1; ///< reserved + uint32_t port_number : 7; ///< This field is the port number of the recipient transaction translator. + uint32_t direction : 1; ///< 0 = OUT; 1 = IN. This field encodes whether the full-speed transaction should be an IN or OUT. + uint32_t : 0; // padding to the end of current storage unit + + // Word 2: Micro-frame Schedule Control + uint8_t int_smask ; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute complete-split transactions + uint8_t fl_int_cmask; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute start-split transactions. + uint16_t reserved ; ///< reserved + + // Word 3: siTD Transfer Status and Control + // Status [7:0] TODO indentical to qTD Token'status --> refractor later + volatile uint32_t : 1 ; // reserved + volatile uint32_t split_state : 1 ; + volatile uint32_t missed_uframe : 1 ; + volatile uint32_t xact_err : 1 ; + volatile uint32_t babble_err : 1 ; + volatile uint32_t buffer_err : 1 ; + volatile uint32_t error : 1 ; + volatile uint32_t active : 1 ; + // Micro-frame Schedule Control + volatile uint32_t cmask_progress : 8 ; ///< This field is used by the host controller to record which split-completes have been executed. See Section 4.12.3.3.2 for behavioral requirements. + volatile uint32_t total_bytes : 10 ; ///< This field is initialized by software to the total number of bytes expected in this transfer. Maximum value is 1023 + volatile uint32_t : 4 ; ///< reserved + volatile uint32_t page_select : 1 ; ///< Used to indicate which data page pointer should be concatenated with the CurrentOffsetfield to construct a data buffer pointer + uint32_t int_on_complete : 1 ; ///< Do not interrupt when transaction is complete. 1 = Do interrupt when transaction is complete + uint32_t : 0 ; // padding to the end of current storage unit + + /// Word 4-5: Buffer Pointer List + uint32_t buffer[2]; // buffer[1] TP: Transaction Position - T-Count: Transaction Count + +// union{ +// uint32_t BufferPointer1; +// struct { +// volatile uint32_t TCount : 3; +// volatile uint32_t TPosition : 2; +// }; +// }; + + /*---------- Word 6 ----------*/ + ehci_link_t back; + + /// SITD is 32-byte aligned but occupies only 28 --> 4 bytes for storing extra data + uint8_t used; + uint8_t ihd_idx; + uint8_t reserved2[2]; +} ehci_sitd_t; + +TU_VERIFY_STATIC( sizeof(ehci_sitd_t) == 32, "size is not correct" ); + +//--------------------------------------------------------------------+ +// EHCI Operational Register +//--------------------------------------------------------------------+ +enum ehci_interrupt_mask_{ + EHCI_INT_MASK_USB = BIT_(0), + EHCI_INT_MASK_ERROR = BIT_(1), + EHCI_INT_MASK_PORT_CHANGE = BIT_(2), + + EHCI_INT_MASK_FRAMELIST_ROLLOVER = BIT_(3), + EHCI_INT_MASK_PCI_HOST_SYSTEM_ERROR = BIT_(4), + EHCI_INT_MASK_ASYNC_ADVANCE = BIT_(5), + EHCI_INT_MASK_NXP_SOF = BIT_(7), + + EHCI_INT_MASK_NXP_ASYNC = BIT_(18), + EHCI_INT_MASK_NXP_PERIODIC = BIT_(19), + + EHCI_INT_MASK_ALL = + EHCI_INT_MASK_USB | EHCI_INT_MASK_ERROR | EHCI_INT_MASK_PORT_CHANGE | + EHCI_INT_MASK_FRAMELIST_ROLLOVER | EHCI_INT_MASK_PCI_HOST_SYSTEM_ERROR | + EHCI_INT_MASK_ASYNC_ADVANCE | EHCI_INT_MASK_NXP_SOF | + EHCI_INT_MASK_NXP_ASYNC | EHCI_INT_MASK_NXP_PERIODIC +}; + +enum ehci_usbcmd_pos_ { + EHCI_USBCMD_POS_RUN_STOP = 0, + EHCI_USBCMD_POS_FRAMELIST_SZIE = 2, + EHCI_USBCMD_POS_PERIOD_ENABLE = 4, + EHCI_USBCMD_POS_ASYNC_ENABLE = 5, + EHCI_USBCMD_POS_NXP_FRAMELIST_SIZE_MSB = 15, + EHCI_USBCMD_POS_INTERRUPT_THRESHOLD = 16 +}; + +enum ehci_portsc_change_mask_{ + EHCI_PORTSC_MASK_CONNECT_STATUS_CHANGE = BIT_(1), + EHCI_PORTSC_MASK_PORT_ENABLE_CHAGNE = BIT_(3), + EHCI_PORTSC_MASK_OVER_CURRENT_CHANGE = BIT_(5), + + EHCI_PORTSC_MASK_ALL = + EHCI_PORTSC_MASK_CONNECT_STATUS_CHANGE | + EHCI_PORTSC_MASK_PORT_ENABLE_CHAGNE | + EHCI_PORTSC_MASK_OVER_CURRENT_CHANGE +}; + +typedef volatile struct +{ + union { + uint32_t command; + + struct { + uint32_t run_stop : 1 ; ///< 1=Run. 0=Stop + uint32_t reset : 1 ; ///< SW write 1 to reset HC, clear by HC when complete + uint32_t framelist_size : 2 ; ///< Frame List size 0: 1024, 1: 512, 2: 256 + uint32_t periodic_enable : 1 ; ///< This bit controls whether the host controller skips processing the Periodic Schedule. Values mean: 0b Do not process the Periodic Schedule 1b Use the PERIODICLISTBASE register to access the Periodic Schedule. + uint32_t async_enable : 1 ; ///< This bit controls whether the host controller skips processing the Asynchronous Schedule. Values mean: 0b Do not process the Asynchronous Schedule 1b Use the ASYNCLISTADDR register to access the Asynchronous Schedule. + uint32_t async_adv_doorbell : 1 ; ///< Tell HC to interrupt next time it advances async list. Clear by HC + uint32_t light_reset : 1 ; ///< Reset HC without affecting ports state + uint32_t async_park_count : 2 ; ///< not used by tinyusb + uint32_t : 1 ; + uint32_t async_park_enable : 1 ; ///< Enable park mode, not used by tinyusb + uint32_t : 3 ; + uint32_t nxp_framelist_size_msb : 1 ; ///< NXP customized : Bit 2 of the Frame List Size bits \n 011b: 128 elements \n 100b: 64 elements \n 101b: 32 elements \n 110b: 16 elements \n 111b: 8 elements + uint32_t int_threshold : 8 ; ///< Default 08h. Interrupt rate in unit of micro frame + }command_bm; + }; + + union { + uint32_t status; + + struct { + uint32_t usb : 1 ; ///< qTD with IOC is retired + uint32_t usb_error : 1 ; ///< qTD retired due to error + uint32_t port_change_detect : 1 ; ///< Set when PortOwner or ForcePortResume change from 0 -> 1 + uint32_t framelist_rollover : 1 ; ///< R/WC The Host Controller sets this bit to a one when the Frame List Index(see Section 2.3.4) rolls over from its maximum value to zero. The exact value at which the rollover occurs depends on the frame list size. For example, if the frame list size (as programmed in the Frame List Sizefield of the USBCMD register) is 1024, the Frame Index Registerrolls over every time FRINDEX[13] toggles. Similarly, if the size is 512, the Host Controller sets this bit to a one every time FRINDEX[12] toggles. + uint32_t pci_host_system_error : 1 ; ///< R/WC (not used by NXP) The Host Controller sets this bit to 1 when a serious error occurs during a host system access involving the Host Controller module. In a PCI system, conditions that set this bit to 1 include PCI Parity error, PCI Master Abort, and PCI Target Abort. When this error occurs, the Host Controller clears the Run/Stop bit in the Command register to prevent further execution of the scheduled TDs. + uint32_t async_adv : 1 ; ///< Async Advance interrupt + uint32_t : 1 ; + uint32_t nxp_int_sof : 1 ; ///< NXP customized: this bit will be set every 125us and can be used by host controller driver as a time base. + uint32_t : 4 ; + uint32_t hc_halted : 1 ; ///< Opposite value to run_stop bit. + uint32_t reclamation : 1 ; ///< Used to detect empty async shecudle + uint32_t periodic_status : 1 ; ///< Periodic schedule status + uint32_t async_status : 1 ; ///< Async schedule status + uint32_t : 2 ; + uint32_t nxp_int_async : 1 ; ///< NXP customized: This bit is set by the Host Controller when the cause of an interrupt is a completion of a USB transaction where the Transfer Descriptor (TD) has an interrupt on complete (IOC) bit set andthe TD was from the asynchronous schedule. This bit is also set by the Host when a short packet is detected andthe packet is on the asynchronous schedule. + uint32_t nxp_int_period : 1 ; ///< NXP customized: This bit is set by the Host Controller when the cause of an interrupt is a completion of a USB transaction where the Transfer Descriptor (TD) has an interrupt on complete (IOC) bit set andthe TD was from the periodic schedule. + uint32_t : 12 ; + }status_bm; + }; + + union{ + uint32_t inten; + + struct { + uint32_t usb : 1 ; + uint32_t usb_error : 1 ; + uint32_t port_change_detect : 1 ; + uint32_t framelist_rollover : 1 ; + uint32_t pci_host_system_error : 1 ; + uint32_t async_adv : 1 ; + uint32_t : 1 ; + uint32_t nxp_int_sof : 1 ; + uint32_t : 10 ; + uint32_t nxp_int_async : 1 ; + uint32_t nxp_int_period : 1 ; + uint32_t : 12 ; + }inten_bm; + }; + + uint32_t frame_index ; ///< Micro frame counter + uint32_t ctrl_ds_seg ; ///< Control Data Structure Segment + uint32_t periodic_list_base ; ///< Beginning address of perodic frame list + uint32_t async_list_addr ; ///< Address of next async QHD to be executed + uint32_t nxp_tt_control ; ///< nxp embedded transaction translator (reserved by EHCI specs) + uint32_t reserved[8] ; + uint32_t config_flag ; ///< not used by NXP + + union { + uint32_t portsc ; ///< port status and control + struct { + uint32_t current_connect_status : 1; ///< 0: No device, 1: Device is present on port + uint32_t connect_status_change : 1; ///< Change in Current Connect Status + uint32_t port_enabled : 1; ///< Ports can only be enabled by HC as a part of the reset and enable. SW can write 0 to disable + uint32_t port_enable_change : 1; ///< Port Enabled has changed + uint32_t over_current_active : 1; ///< Port has an over-current condition + uint32_t over_current_change : 1; ///< Change to Over-current Active + uint32_t force_port_resume : 1; ///< Resume detected/driven on port. This functionality defined for manipulating this bit depends on the value of the Suspend bit. + uint32_t suspend : 1; ///< Port in suspend state + uint32_t port_reset : 1; ///< 1=Port is in Reset. 0=Port is not in Reset + uint32_t nxp_highspeed_status : 1; ///< NXP customized: 0=connected to the port is not in High-speed mode, 1=connected to the port is in High-speed mode + uint32_t line_status : 2; ///< D+/D- state: 00: SE0, 10: J-state, 01: K-state + uint32_t port_power : 1; ///< 0= power off, 1= power on + uint32_t port_owner : 1; ///< not used by NXP + uint32_t port_indicator_control : 2; ///< 00b: off, 01b: Amber, 10b: green, 11b: undefined + uint32_t port_test_control : 4; ///< Port test mode, not used by tinyusb + uint32_t wake_on_connect_enable : 1; ///< Enables device connects as wake-up events + uint32_t wake_on_disconnect_enable : 1; ///< Enables device disconnects as wake-up events + uint32_t wake_on_over_current_enable : 1; ///< Enables over-current conditions as wake-up events + uint32_t nxp_phy_clock_disable : 1; ///< NXP customized: the PHY can be put into Low Power Suspend – Clock Disable when the downstream device has been put into suspend mode or when no downstream device is connected. Low power suspend is completely under the control of software. 0: enable PHY clock, 1: disable PHY clock + uint32_t nxp_port_force_fullspeed : 1; ///< NXP customized: Writing this bit to a 1 will force the port to only connect at Full Speed. It disables the chirp sequence that allowsthe port to identify itself as High Speed. This is useful for testing FS configurations with a HS host, hub or device. + uint32_t : 1; + uint32_t nxp_port_speed : 2; ///< NXP customized: This register field indicates the speed atwhich the port is operating. For HS mode operation in the host controllerand HS/FS operation in the device controller the port routing steers data to the Protocol engine. For FS and LS mode operation in the host controller, the port routing steers data to the Protocol Engine w/ Embedded Transaction Translator. 0x0: Fullspeed, 0x1: Lowspeed, 0x2: Highspeed + uint32_t : 0; // padding to the boundary of storage unit + }portsc_bm; + }; +}ehci_registers_t; + +//--------------------------------------------------------------------+ +// EHCI Data Organization +//--------------------------------------------------------------------+ +typedef struct +{ + ehci_link_t period_framelist[EHCI_FRAMELIST_SIZE]; + + // for NXP ECHI, only implement 1 ms & 2 ms & 4 ms, 8 ms (framelist) + // [0] : 1ms, [1] : 2ms, [2] : 4ms, [3] : 8 ms + ehci_qhd_t period_head_arr[4]; + + // Note control qhd of dev0 is used as head of async list + struct { + ehci_qhd_t qhd; + ehci_qtd_t qtd; + }control[CFG_TUSB_HOST_DEVICE_MAX+1]; + + ehci_qhd_t qhd_pool[HCD_MAX_ENDPOINT]; + ehci_qtd_t qtd_pool[HCD_MAX_XFER] ATTR_ALIGNED(32); + + ehci_registers_t* regs; +}ehci_data_t; + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_EHCI_H_ */ + +/** @} */ +/** @} */ + diff --git a/src/host/hcd.h b/src/host/hcd.h new file mode 100644 index 000000000..e117c20ff --- /dev/null +++ b/src/host/hcd.h @@ -0,0 +1,158 @@ +/**************************************************************************/
+/*!
+ @file hcd.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_usbh
+ * \defgroup Group_HCD Host Controller Driver (HCD)
+ * @{ */
+
+#ifndef _TUSB_HCD_H_
+#define _TUSB_HCD_H_
+
+#include <common/tusb_common.h>
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+ //--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+typedef enum
+{
+ HCD_EVENT_DEVICE_ATTACH,
+ HCD_EVENT_DEVICE_REMOVE,
+ HCD_EVENT_XFER_COMPLETE,
+} hcd_eventid_t;
+
+typedef struct
+{
+ uint8_t rhport;
+ uint8_t event_id;
+
+ union
+ {
+ struct
+ {
+ uint8_t hub_addr;
+ uint8_t hub_port;
+ } attach, remove;
+
+ struct
+ {
+ uint8_t ep_addr;
+ uint8_t result;
+ uint32_t len;
+ } xfer_complete;
+ };
+
+} hcd_event_t;
+
+#if TUSB_OPT_HOST_ENABLED
+// Max number of endpoints per device
+enum {
+ HCD_MAX_ENDPOINT = CFG_TUSB_HOST_DEVICE_MAX*(CFG_TUH_HUB + CFG_TUH_HID_KEYBOARD + CFG_TUH_HID_MOUSE + CFG_TUSB_HOST_HID_GENERIC +
+ CFG_TUH_MSC*2 + CFG_TUH_CDC*3),
+
+ HCD_MAX_XFER = HCD_MAX_ENDPOINT*2,
+};
+
+//#define HCD_MAX_ENDPOINT 16
+//#define HCD_MAX_XFER 16
+#endif
+
+//--------------------------------------------------------------------+
+// HCD API
+//--------------------------------------------------------------------+
+bool hcd_init(void);
+void hcd_int_enable (uint8_t rhport);
+void hcd_int_disable(uint8_t rhport);
+
+// PORT API
+/// return the current connect status of roothub port
+bool hcd_port_connect_status(uint8_t hostid);
+void hcd_port_reset(uint8_t hostid);
+tusb_speed_t hcd_port_speed_get(uint8_t hostid);
+
+// HCD closes all opened endpoints belong to this device
+void hcd_device_close(uint8_t rhport, uint8_t dev_addr);
+
+//--------------------------------------------------------------------+
+// Event function
+//--------------------------------------------------------------------+
+void hcd_event_handler(hcd_event_t const* event, bool in_isr);
+
+// Helper to send device attach event
+void hcd_event_device_attach(uint8_t rhport);
+
+// Helper to send device removal event
+void hcd_event_device_remove(uint8_t rhport);
+
+// Helper to send USB transfer event
+void hcd_event_xfer_complete(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
+
+//--------------------------------------------------------------------+
+// Endpoints API
+//--------------------------------------------------------------------+
+bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]);
+bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc);
+
+bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr);
+bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr);
+bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr);
+
+// TODO merge with pipe_xfer
+bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen);
+
+//--------------------------------------------------------------------+
+// PIPE API
+//--------------------------------------------------------------------+
+// TODO control xfer should be used via usbh layer
+bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes); // only queue, not transferring yet
+bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete);
+
+#if 0
+tusb_error_t hcd_pipe_cancel()ATTR_WARN_UNUSED_RESULT;
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_HCD_H_ */
+
+/// @}
diff --git a/src/host/hub.c b/src/host/hub.c new file mode 100644 index 000000000..6b87e935e --- /dev/null +++ b/src/host/hub.c @@ -0,0 +1,264 @@ +/**************************************************************************/
+/*!
+ @file hub.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if (TUSB_OPT_HOST_ENABLED && CFG_TUH_HUB)
+
+#define _TINY_USB_SOURCE_FILE_
+
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "hub.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+typedef struct
+{
+ uint8_t itf_num;
+ uint8_t ep_status;
+ uint8_t port_number;
+ uint8_t status_change; // data from status change interrupt endpoint
+}usbh_hub_t;
+
+CFG_TUSB_MEM_SECTION STATIC_VAR usbh_hub_t hub_data[CFG_TUSB_HOST_DEVICE_MAX];
+ATTR_ALIGNED(4) CFG_TUSB_MEM_SECTION STATIC_VAR uint8_t hub_enum_buffer[sizeof(descriptor_hub_desc_t)];
+
+//OSAL_SEM_DEF(hub_enum_semaphore);
+//static osal_semaphore_handle_t hub_enum_sem_hdl;
+
+//--------------------------------------------------------------------+
+// HUB
+//--------------------------------------------------------------------+
+bool hub_port_clear_feature_subtask(uint8_t hub_addr, uint8_t hub_port, uint8_t feature)
+{
+ TU_ASSERT(HUB_FEATURE_PORT_CONNECTION_CHANGE <= feature && feature <= HUB_FEATURE_PORT_RESET_CHANGE);
+
+ tusb_control_request_t request = {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT },
+ .bRequest = HUB_REQUEST_CLEAR_FEATURE,
+ .wValue = feature,
+ .wIndex = hub_port,
+ .wLength = 0
+ };
+
+ //------------- Clear Port Feature request -------------//
+ TU_ASSERT( usbh_control_xfer( hub_addr, &request, NULL ) );
+
+ //------------- Get Port Status to check if feature is cleared -------------//
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN },
+ .bRequest = HUB_REQUEST_GET_STATUS,
+ .wValue = 0,
+ .wIndex = hub_port,
+ .wLength = 4
+ };
+
+ TU_ASSERT( usbh_control_xfer( hub_addr, &request, hub_enum_buffer ) );
+
+ //------------- Check if feature is cleared -------------//
+ hub_port_status_response_t * p_port_status;
+ p_port_status = (hub_port_status_response_t *) hub_enum_buffer;
+
+ TU_ASSERT( !BIT_TEST_(p_port_status->status_change.value, feature-16) );
+
+ return true;
+}
+
+bool hub_port_reset_subtask(uint8_t hub_addr, uint8_t hub_port)
+{
+ enum { RESET_DELAY = 200 }; // USB specs say only 50ms but many devices require much longer
+
+ //------------- Set Port Reset -------------//
+ tusb_control_request_t request = {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT },
+ .bRequest = HUB_REQUEST_SET_FEATURE,
+ .wValue = HUB_FEATURE_PORT_RESET,
+ .wIndex = hub_port,
+ .wLength = 0
+ };
+
+ TU_ASSERT( usbh_control_xfer( hub_addr, &request, NULL ) );
+
+ osal_task_delay(RESET_DELAY); // TODO Hub wait for Status Endpoint on Reset Change
+
+ //------------- Get Port Status to check if port is enabled, powered and reset_change -------------//
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN },
+ .bRequest = HUB_REQUEST_GET_STATUS,
+ .wValue = 0,
+ .wIndex = hub_port,
+ .wLength = 4
+ };
+
+ TU_ASSERT( usbh_control_xfer( hub_addr, &request, hub_enum_buffer ) );
+
+ hub_port_status_response_t * p_port_status;
+ p_port_status = (hub_port_status_response_t *) hub_enum_buffer;
+
+ TU_ASSERT ( p_port_status->status_change.reset && p_port_status->status_current.connect_status &&
+ p_port_status->status_current.port_power && p_port_status->status_current.port_enable);
+
+ return true;
+}
+
+// can only get the speed RIGHT AFTER hub_port_reset_subtask call
+tusb_speed_t hub_port_get_speed(void)
+{
+ hub_port_status_response_t * p_port_status = (hub_port_status_response_t *) hub_enum_buffer;
+ return (p_port_status->status_current.high_speed_device_attached) ? TUSB_SPEED_HIGH :
+ (p_port_status->status_current.low_speed_device_attached ) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL;
+}
+
+//--------------------------------------------------------------------+
+// CLASS-USBH API (don't require to verify parameters)
+//--------------------------------------------------------------------+
+void hub_init(void)
+{
+ tu_memclr(hub_data, CFG_TUSB_HOST_DEVICE_MAX*sizeof(usbh_hub_t));
+// hub_enum_sem_hdl = osal_semaphore_create( OSAL_SEM_REF(hub_enum_semaphore) );
+}
+
+bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length)
+{
+ // not support multiple TT yet
+ if ( itf_desc->bInterfaceProtocol > 1 ) return false;
+
+ //------------- Open Interrupt Status Pipe -------------//
+ tusb_desc_endpoint_t const *ep_desc;
+ ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc);
+
+ TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType);
+ TU_ASSERT(TUSB_XFER_INTERRUPT == ep_desc->bmAttributes.xfer);
+
+ TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc));
+
+ hub_data[dev_addr-1].itf_num = itf_desc->bInterfaceNumber;
+ hub_data[dev_addr-1].ep_status = ep_desc->bEndpointAddress;
+
+ (*p_length) = sizeof(tusb_desc_interface_t) + sizeof(tusb_desc_endpoint_t);
+
+ //------------- Get Hub Descriptor -------------//
+ tusb_control_request_t request = {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN },
+ .bRequest = HUB_REQUEST_GET_DESCRIPTOR,
+ .wValue = 0,
+ .wIndex = 0,
+ .wLength = sizeof(descriptor_hub_desc_t)
+ };
+
+ TU_ASSERT( usbh_control_xfer( dev_addr, &request, hub_enum_buffer ) );
+
+ // only care about this field in hub descriptor
+ hub_data[dev_addr-1].port_number = ((descriptor_hub_desc_t*) hub_enum_buffer)->bNbrPorts;
+
+ //------------- Set Port_Power on all ports -------------//
+ // TODO may only power port with attached
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT },
+ .bRequest = HUB_REQUEST_SET_FEATURE,
+ .wValue = HUB_FEATURE_PORT_POWER,
+ .wIndex = 0,
+ .wLength = 0
+ };
+
+ for(uint8_t i=1; i <= hub_data[dev_addr-1].port_number; i++)
+ {
+ request.wIndex = i;
+ TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) );
+ }
+
+ //------------- Queue the initial Status endpoint transfer -------------//
+ TU_ASSERT( hcd_pipe_xfer(dev_addr, hub_data[dev_addr-1].ep_status, &hub_data[dev_addr-1].status_change, 1, true) );
+
+ return true;
+}
+
+// is the response of interrupt endpoint polling
+#include "usbh_hcd.h" // FIXME remove
+void hub_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
+{
+ (void) xferred_bytes; // TODO can be more than 1 for hub with lots of ports
+ (void) ep_addr;
+
+ usbh_hub_t * p_hub = &hub_data[dev_addr-1];
+
+ if ( event == XFER_RESULT_SUCCESS )
+ {
+ for (uint8_t port=1; port <= p_hub->port_number; port++)
+ {
+ // TODO HUB ignore bit0 hub_status_change
+ if ( BIT_TEST_(p_hub->status_change, port) )
+ {
+ hcd_event_t event =
+ {
+ .rhport = _usbh_devices[dev_addr].rhport,
+ .event_id = HCD_EVENT_DEVICE_ATTACH
+ };
+
+ event.attach.hub_addr = dev_addr;
+ event.attach.hub_port = port;
+
+ hcd_event_handler(&event, true);
+ break; // handle one port at a time, next port if any will be handled in the next cycle
+ }
+ }
+ // NOTE: next status transfer is queued by usbh.c after handling this request
+ }
+ else
+ {
+ // TODO [HUB] check if hub is still plugged before polling status endpoint since failed usually mean hub unplugged
+// TU_ASSERT ( hub_status_pipe_queue(dev_addr) );
+ }
+}
+
+void hub_close(uint8_t dev_addr)
+{
+ tu_memclr(&hub_data[dev_addr-1], sizeof(usbh_hub_t));
+// osal_semaphore_reset(hub_enum_sem_hdl);
+}
+
+bool hub_status_pipe_queue(uint8_t dev_addr)
+{
+ return hcd_pipe_xfer(dev_addr, hub_data[dev_addr-1].ep_status, &hub_data[dev_addr-1].status_change, 1, true);
+}
+
+
+#endif
diff --git a/src/host/hub.h b/src/host/hub.h new file mode 100644 index 000000000..f8d8a4c6a --- /dev/null +++ b/src/host/hub.h @@ -0,0 +1,210 @@ +/**************************************************************************/
+/*!
+ @file hub.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_class
+ * \defgroup ClassDriver_Hub Hub (Host only)
+ * \details Like most PC's OS, Hub support is completely hidden from Application. In fact, application cannot determine whether
+ * a device is mounted directly via roothub or via a hub's port. All Hub-related procedures are performed and managed
+ * by tinyusb stack. Unless you are trying to develop the stack itself, there are nothing else can be used by Application.
+ * \note Due to my laziness, only 1-level of Hub is supported. In other way, the stack cannot mount a hub via another hub.
+ * @{
+ */
+
+#ifndef _TUSB_HUB_H_
+#define _TUSB_HUB_H_
+
+#include <common/tusb_common.h>
+#include "usbh.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//D1...D0: Logical Power Switching Mode
+//00: Ganged power switching (all ports’power at
+//once)
+//01: Individual port power switching
+//1X: Reserved. Used only on 1.0 compliant hubs
+//that implement no power switching
+//D2: Identifies a Compound Device
+//0: Hub is not part of a compound device.
+//1: Hub is part of a compound device.
+//D4...D3: Over-current Protection Mode
+//00: Global Over-current Protection. The hub
+//reports over-current as a summation of all
+//ports’current draw, without a breakdown of
+//individual port over-current status.
+//01: Individual Port Over-current Protection. The
+//hub reports over-current on a per-port basis.
+//Each port has an over-current status.
+//1X: No Over-current Protection. This option is
+//allowed only for bus-powered hubs that do not
+//implement over-current protection.
+//
+//D6...D5: TT Think TIme
+//00: TT requires at most 8 FS bit times of inter
+//transaction gap on a full-/low-speed
+//downstream bus.
+//01: TT requires at most 16 FS bit times.
+//10: TT requires at most 24 FS bit times.
+//11: TT requires at most 32 FS bit times.
+//D7: Port Indicators Supported
+//0: Port Indicators are not supported on its
+//downstream facing ports and the
+//PORT_INDICATOR request has no effect.
+//1: Port Indicators are supported on its
+//downstream facing ports and the
+//PORT_INDICATOR request controls the
+//indicators. See Section 11.5.3.
+//D15...D8: Reserved
+
+typedef struct ATTR_PACKED{
+ uint8_t bLength ; ///< Size of descriptor
+ uint8_t bDescriptorType ; ///< Other_speed_Configuration Type
+ uint8_t bNbrPorts;
+ uint16_t wHubCharacteristics;
+ uint8_t bPwrOn2PwrGood;
+ uint8_t bHubContrCurrent;
+ uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1)
+ uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff
+} descriptor_hub_desc_t;
+
+TU_VERIFY_STATIC( sizeof(descriptor_hub_desc_t) == 9, "size is not correct");
+
+enum {
+ HUB_REQUEST_GET_STATUS = 0 ,
+ HUB_REQUEST_CLEAR_FEATURE = 1 ,
+
+ HUB_REQUEST_SET_FEATURE = 3 ,
+
+ HUB_REQUEST_GET_DESCRIPTOR = 6 ,
+ HUB_REQUEST_SET_DESCRIPTOR = 7 ,
+ HUB_REQUEST_CLEAR_TT_BUFFER = 8 ,
+ HUB_REQUEST_RESET_TT = 9 ,
+ HUB_REQUEST_GET_TT_STATE = 10 ,
+ HUB_REQUEST_STOP_TT = 11
+};
+
+enum {
+ HUB_FEATURE_HUB_LOCAL_POWER_CHANGE = 0,
+ HUB_FEATURE_HUB_OVER_CURRENT_CHANGE
+};
+
+enum{
+ HUB_FEATURE_PORT_CONNECTION = 0,
+ HUB_FEATURE_PORT_ENABLE = 1,
+ HUB_FEATURE_PORT_SUSPEND = 2,
+ HUB_FEATURE_PORT_OVER_CURRENT = 3,
+ HUB_FEATURE_PORT_RESET = 4,
+
+ HUB_FEATURE_PORT_POWER = 8,
+ HUB_FEATURE_PORT_LOW_SPEED = 9,
+
+ HUB_FEATURE_PORT_CONNECTION_CHANGE = 16,
+ HUB_FEATURE_PORT_ENABLE_CHANGE = 17,
+ HUB_FEATURE_PORT_SUSPEND_CHANGE = 18,
+ HUB_FEATURE_PORT_OVER_CURRENT_CHANGE = 19,
+ HUB_FEATURE_PORT_RESET_CHANGE = 20,
+ HUB_FEATURE_PORT_TEST = 21,
+ HUB_FEATURE_PORT_INDICATOR = 22
+};
+
+// data in response of HUB_REQUEST_GET_STATUS, wIndex = 0 (hub)
+typedef struct {
+ union{
+ struct ATTR_PACKED {
+ uint16_t local_power_source : 1;
+ uint16_t over_current : 1;
+ uint16_t : 14;
+ };
+
+ uint16_t value;
+ } status, status_change;
+} hub_status_response_t;
+
+TU_VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct");
+
+// data in response of HUB_REQUEST_GET_STATUS, wIndex = Port num
+typedef struct {
+ union {
+ struct ATTR_PACKED {
+ uint16_t connect_status : 1;
+ uint16_t port_enable : 1;
+ uint16_t suspend : 1;
+ uint16_t over_current : 1;
+ uint16_t reset : 1;
+
+ uint16_t : 3;
+ uint16_t port_power : 1;
+ uint16_t low_speed_device_attached : 1;
+ uint16_t high_speed_device_attached : 1;
+ uint16_t port_test_mode : 1;
+ uint16_t port_indicator_control : 1;
+ uint16_t : 0;
+ };
+
+ uint16_t value;
+ } status_current, status_change;
+} hub_port_status_response_t;
+
+TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct");
+
+bool hub_port_reset_subtask(uint8_t hub_addr, uint8_t hub_port);
+bool hub_port_clear_feature_subtask(uint8_t hub_addr, uint8_t hub_port, uint8_t feature);
+tusb_speed_t hub_port_get_speed(void);
+bool hub_status_pipe_queue(uint8_t dev_addr);
+
+//--------------------------------------------------------------------+
+// USBH-CLASS DRIVER API
+//--------------------------------------------------------------------+
+#ifdef _TINY_USB_SOURCE_FILE_
+
+void hub_init(void);
+bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length) ATTR_WARN_UNUSED_RESULT;
+void hub_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
+void hub_close(uint8_t dev_addr);
+
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_HUB_H_ */
+
+/** @} */
diff --git a/src/host/ohci/ohci.c b/src/host/ohci/ohci.c new file mode 100644 index 000000000..bebb8a2ef --- /dev/null +++ b/src/host/ohci/ohci.c @@ -0,0 +1,663 @@ +/**************************************************************************/
+/*!
+ @file ohci.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include <common/tusb_common.h>
+
+#if TUSB_OPT_HOST_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC40XX)
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "osal/osal.h"
+
+#include "../hcd.h"
+#include "../usbh_hcd.h"
+#include "ohci.h"
+
+// TODO remove
+#include "chip.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+#define OHCI_REG ((ohci_registers_t *) LPC_USB_BASE)
+
+enum {
+ OHCI_CONTROL_FUNCSTATE_RESET = 0,
+ OHCI_CONTROL_FUNCSTATE_RESUME,
+ OHCI_CONTROL_FUNCSTATE_OPERATIONAL,
+ OHCI_CONTROL_FUNCSTATE_SUSPEND
+};
+
+enum {
+ OHCI_CONTROL_CONTROL_BULK_RATIO = 3, ///< This specifies the service ratio between Control and Bulk EDs. 0 = 1:1, 3 = 4:1
+ OHCI_CONTROL_LIST_PERIODIC_ENABLE_MASK = BIT_(2),
+ OHCI_CONTROL_LIST_ISOCHRONOUS_ENABLE_MASK = BIT_(3),
+ OHCI_CONTROL_LIST_CONTROL_ENABLE_MASK = BIT_(4),
+ OHCI_CONTROL_LIST_BULK_ENABLE_MASK = BIT_(5),
+};
+
+enum {
+ OHCI_FMINTERVAL_FI = 0x2EDF, // 7.3.1 nominal (reset) value
+ OHCI_FMINTERVAL_FSMPS = (6*(OHCI_FMINTERVAL_FI-210)) / 7, // 5.4 calculated based on maximum overhead + bit stuffing
+};
+
+enum {
+ OHCI_PERIODIC_START = 0x3E67
+};
+
+enum {
+ OHCI_INT_SCHEDULING_OVERUN_MASK = BIT_(0),
+ OHCI_INT_WRITEBACK_DONEHEAD_MASK = BIT_(1),
+ OHCI_INT_SOF_MASK = BIT_(2),
+ OHCI_INT_RESUME_DETECTED_MASK = BIT_(3),
+ OHCI_INT_UNRECOVERABLE_ERROR_MASK = BIT_(4),
+ OHCI_INT_FRAME_OVERFLOW_MASK = BIT_(5),
+ OHCI_INT_RHPORT_STATUS_CHANGE_MASK = BIT_(6),
+
+ OHCI_INT_OWNERSHIP_CHANGE_MASK = BIT_(30),
+ OHCI_INT_MASTER_ENABLE_MASK = BIT_(31),
+};
+
+enum {
+ OHCI_RHPORT_CURRENT_CONNECT_STATUS_MASK = BIT_(0),
+ OHCI_RHPORT_PORT_ENABLE_STATUS_MASK = BIT_(1),
+ OHCI_RHPORT_PORT_SUSPEND_STATUS_MASK = BIT_(2),
+ OHCI_RHPORT_PORT_OVER_CURRENT_INDICATOR_MASK = BIT_(3),
+ OHCI_RHPORT_PORT_RESET_STATUS_MASK = BIT_(4), ///< write '1' to reset port
+
+ OHCI_RHPORT_PORT_POWER_STATUS_MASK = BIT_(8),
+ OHCI_RHPORT_LOW_SPEED_DEVICE_ATTACHED_MASK = BIT_(9),
+
+ OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK = BIT_(16),
+ OHCI_RHPORT_PORT_ENABLE_CHANGE_MASK = BIT_(17),
+ OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK = BIT_(18),
+ OHCI_RHPORT_OVER_CURRENT_CHANGE_MASK = BIT_(19),
+ OHCI_RHPORT_PORT_RESET_CHANGE_MASK = BIT_(20),
+
+ OHCI_RHPORT_ALL_CHANGE_MASK = OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK | OHCI_RHPORT_PORT_ENABLE_CHANGE_MASK |
+ OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK | OHCI_RHPORT_OVER_CURRENT_CHANGE_MASK | OHCI_RHPORT_PORT_RESET_CHANGE_MASK
+};
+
+enum {
+ OHCI_CCODE_NO_ERROR = 0,
+ OHCI_CCODE_CRC = 1,
+ OHCI_CCODE_BIT_STUFFING = 2,
+ OHCI_CCODE_DATA_TOGGLE_MISMATCH = 3,
+ OHCI_CCODE_STALL = 4,
+ OHCI_CCODE_DEVICE_NOT_RESPONDING = 5,
+ OHCI_CCODE_PID_CHECK_FAILURE = 6,
+ OHCI_CCODE_UNEXPECTED_PID = 7,
+ OHCI_CCODE_DATA_OVERRUN = 8,
+ OHCI_CCODE_DATA_UNDERRUN = 9,
+ OHCI_CCODE_BUFFER_OVERRUN = 12,
+ OHCI_CCODE_BUFFER_UNDERRUN = 13,
+ OHCI_CCODE_NOT_ACCESSED = 14,
+};
+
+enum {
+ OHCI_INT_ON_COMPLETE_YES = 0,
+ OHCI_INT_ON_COMPLETE_NO = BIN8(111)
+};
+//--------------------------------------------------------------------+
+// INTERNAL OBJECT & FUNCTION DECLARATION
+//--------------------------------------------------------------------+
+CFG_TUSB_MEM_SECTION ATTR_ALIGNED(256) static ohci_data_t ohci_data;
+
+static ohci_ed_t * const p_ed_head[] =
+{
+ [TUSB_XFER_CONTROL] = &ohci_data.control[0].ed,
+ [TUSB_XFER_BULK ] = &ohci_data.bulk_head_ed,
+ [TUSB_XFER_INTERRUPT] = &ohci_data.period_head_ed,
+ [TUSB_XFER_ISOCHRONOUS] = NULL // TODO Isochronous
+};
+
+static void ed_list_insert(ohci_ed_t * p_pre, ohci_ed_t * p_ed);
+static void ed_list_remove_by_addr(ohci_ed_t * p_head, uint8_t dev_addr);
+
+//--------------------------------------------------------------------+
+// USBH-HCD API
+//--------------------------------------------------------------------+
+// Initialization according to 5.1.1.4
+bool hcd_init(void)
+{
+ //------------- Data Structure init -------------//
+ tu_memclr(&ohci_data, sizeof(ohci_data_t));
+ for(uint8_t i=0; i<32; i++)
+ { // assign all interrupt pointes to period head ed
+ ohci_data.hcca.interrupt_table[i] = (uint32_t) &ohci_data.period_head_ed;
+ }
+
+ ohci_data.control[0].ed.skip = 1;
+ ohci_data.bulk_head_ed.skip = 1;
+ ohci_data.period_head_ed.skip = 1;
+
+ // reset controller
+ OHCI_REG->command_status_bit.controller_reset = 1;
+ while( OHCI_REG->command_status_bit.controller_reset ) {} // should not take longer than 10 us
+
+ //------------- init ohci registers -------------//
+ OHCI_REG->control_head_ed = (uint32_t) &ohci_data.control[0].ed;
+ OHCI_REG->bulk_head_ed = (uint32_t) &ohci_data.bulk_head_ed;
+ OHCI_REG->hcca = (uint32_t) &ohci_data.hcca;
+
+ OHCI_REG->interrupt_disable = OHCI_REG->interrupt_enable; // disable all interrupts
+ OHCI_REG->interrupt_status = OHCI_REG->interrupt_status; // clear current set bits
+ OHCI_REG->interrupt_enable = OHCI_INT_WRITEBACK_DONEHEAD_MASK | OHCI_INT_RESUME_DETECTED_MASK |
+ OHCI_INT_UNRECOVERABLE_ERROR_MASK | /*OHCI_INT_FRAME_OVERFLOW_MASK |*/ OHCI_INT_RHPORT_STATUS_CHANGE_MASK |
+ OHCI_INT_MASTER_ENABLE_MASK;
+
+ OHCI_REG->control |= OHCI_CONTROL_CONTROL_BULK_RATIO | OHCI_CONTROL_LIST_CONTROL_ENABLE_MASK |
+ OHCI_CONTROL_LIST_BULK_ENABLE_MASK | OHCI_CONTROL_LIST_PERIODIC_ENABLE_MASK; // TODO Isochronous
+
+ OHCI_REG->frame_interval = (OHCI_FMINTERVAL_FSMPS << 16) | OHCI_FMINTERVAL_FI;
+ OHCI_REG->periodic_start = (OHCI_FMINTERVAL_FI * 9) / 10; // Periodic start is 90% of frame interval
+
+ OHCI_REG->control_bit.hc_functional_state = OHCI_CONTROL_FUNCSTATE_OPERATIONAL; // make HC's state to operational state TODO use this to suspend (save power)
+ OHCI_REG->rh_status_bit.local_power_status_change = 1; // set global power for ports
+
+ return true;
+}
+
+//--------------------------------------------------------------------+
+// PORT API
+//--------------------------------------------------------------------+
+void hcd_port_reset(uint8_t hostid)
+{
+ (void) hostid;
+ OHCI_REG->rhport_status[0] = OHCI_RHPORT_PORT_RESET_STATUS_MASK;
+}
+
+bool hcd_port_connect_status(uint8_t hostid)
+{
+ (void) hostid;
+ return OHCI_REG->rhport_status_bit[0].current_connect_status;
+}
+
+tusb_speed_t hcd_port_speed_get(uint8_t hostid)
+{
+ (void) hostid;
+ return OHCI_REG->rhport_status_bit[0].low_speed_device_attached ? TUSB_SPEED_LOW : TUSB_SPEED_FULL;
+}
+
+// endpoints are tied to an address, which only reclaim after a long delay when enumerating
+// thus there is no need to make sure ED is not in HC's cahed as it will not for sure
+void hcd_device_close(uint8_t rhport, uint8_t dev_addr)
+{
+ // TODO OHCI
+ (void) rhport;
+
+ // addr0 serves as static head --> only set skip bit
+ if ( dev_addr == 0 )
+ {
+ ohci_data.control[0].ed.skip = 1;
+ }else
+ {
+ // remove control
+ ed_list_remove_by_addr( p_ed_head[TUSB_XFER_CONTROL], dev_addr);
+
+ // remove bulk
+ ed_list_remove_by_addr(p_ed_head[TUSB_XFER_BULK], dev_addr);
+
+ // remove interrupt
+ ed_list_remove_by_addr(p_ed_head[TUSB_XFER_INTERRUPT], dev_addr);
+
+ // TODO remove ISO
+ }
+}
+
+//--------------------------------------------------------------------+
+// Controller API
+//--------------------------------------------------------------------+
+
+//--------------------------------------------------------------------+
+// CONTROL PIPE API
+//--------------------------------------------------------------------+
+static inline tusb_xfer_type_t ed_get_xfer_type(ohci_ed_t const * const p_ed)
+{
+ return (p_ed->ep_number == 0 ) ? TUSB_XFER_CONTROL :
+ (p_ed->is_iso ) ? TUSB_XFER_ISOCHRONOUS :
+ (p_ed->is_interrupt_xfer ) ? TUSB_XFER_INTERRUPT : TUSB_XFER_BULK;
+}
+
+static void ed_init(ohci_ed_t *p_ed, uint8_t dev_addr, uint16_t max_packet_size, uint8_t endpoint_addr, uint8_t xfer_type, uint8_t interval)
+{
+ (void) interval;
+
+ // address 0 is used as async head, which always on the list --> cannot be cleared
+ if (dev_addr != 0)
+ {
+ tu_memclr(p_ed, sizeof(ohci_ed_t));
+ }
+
+ p_ed->dev_addr = dev_addr;
+ p_ed->ep_number = endpoint_addr & 0x0F;
+ p_ed->pid = (xfer_type == TUSB_XFER_CONTROL) ? OHCI_PID_SETUP : ( (endpoint_addr & TUSB_DIR_IN_MASK) ? OHCI_PID_IN : OHCI_PID_OUT );
+ p_ed->speed = _usbh_devices[dev_addr].speed;
+ p_ed->is_iso = (xfer_type == TUSB_XFER_ISOCHRONOUS) ? 1 : 0;
+ p_ed->max_packet_size = max_packet_size;
+
+ p_ed->used = 1;
+ p_ed->is_interrupt_xfer = (xfer_type == TUSB_XFER_INTERRUPT ? 1 : 0);
+}
+
+static void gtd_init(ohci_gtd_t* p_td, void* data_ptr, uint16_t total_bytes)
+{
+ tu_memclr(p_td, sizeof(ohci_gtd_t));
+
+ p_td->used = 1;
+ p_td->expected_bytes = total_bytes;
+
+ p_td->buffer_rounding = 1; // less than queued length is not a error
+ p_td->delay_interrupt = OHCI_INT_ON_COMPLETE_NO;
+ p_td->condition_code = OHCI_CCODE_NOT_ACCESSED;
+
+ p_td->current_buffer_pointer = data_ptr;
+ p_td->buffer_end = total_bytes ? (((uint8_t*) data_ptr) + total_bytes-1) : NULL;
+}
+
+bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8])
+{
+ (void) rhport;
+
+ ohci_ed_t* p_ed = &ohci_data.control[dev_addr].ed;
+ ohci_gtd_t *p_setup = &ohci_data.control[dev_addr].gtd;
+
+ gtd_init(p_setup, (void*) setup_packet, 8);
+ p_setup->index = dev_addr;
+ p_setup->pid = OHCI_PID_SETUP;
+ p_setup->data_toggle = BIN8(10); // DATA0
+ p_setup->delay_interrupt = OHCI_INT_ON_COMPLETE_YES;
+
+ //------------- Attach TDs list to Control Endpoint -------------//
+ p_ed->td_head.address = (uint32_t) p_setup;
+
+ OHCI_REG->command_status_bit.control_list_filled = 1;
+
+ 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;
+
+ uint8_t const epnum = tu_edpt_number(ep_addr);
+ uint8_t const dir = tu_edpt_dir(ep_addr);
+
+ // FIXME control only for now
+ if ( epnum == 0 )
+ {
+ ohci_ed_t* const p_ed = &ohci_data.control[dev_addr].ed;
+ ohci_gtd_t *p_data = &ohci_data.control[dev_addr].gtd;
+
+ gtd_init(p_data, buffer, buflen);
+
+ p_data->index = dev_addr;
+ p_data->pid = dir ? OHCI_PID_IN : OHCI_PID_OUT;
+ p_data->data_toggle = BIN8(11); // DATA1
+ p_data->delay_interrupt = OHCI_INT_ON_COMPLETE_YES;
+
+ p_ed->td_head.address = (uint32_t) p_data;
+
+ OHCI_REG->command_status_bit.control_list_filled = 1;
+ }
+
+ return true;
+}
+
+//--------------------------------------------------------------------+
+// BULK/INT/ISO PIPE API
+//--------------------------------------------------------------------+
+static inline ohci_ed_t * ed_from_addr(uint8_t dev_addr, uint8_t ep_addr)
+{
+ if ( tu_edpt_number(ep_addr) == 0 ) return &ohci_data.control[dev_addr].ed;
+
+ ohci_ed_t* ed_pool = ohci_data.ed_pool;
+
+ for(uint32_t i=0; i<HCD_MAX_ENDPOINT; i++)
+ {
+ if ( (ed_pool[i].dev_addr == dev_addr) &&
+ ep_addr == tu_edpt_addr(ed_pool[i].ep_number, ed_pool[i].pid == OHCI_PID_IN) )
+ {
+ return &ed_pool[i];
+ }
+ }
+
+ return NULL;
+}
+
+static inline ohci_ed_t * ed_find_free(void)
+{
+ ohci_ed_t* ed_pool = ohci_data.ed_pool;
+
+ for(uint8_t i = 0; i < HCD_MAX_ENDPOINT; i++)
+ {
+ if ( !ed_pool[i].used ) return &ed_pool[i];
+ }
+
+ return NULL;
+}
+
+static void ed_list_insert(ohci_ed_t * p_pre, ohci_ed_t * p_ed)
+{
+ p_ed->next = p_pre->next;
+ p_pre->next = (uint32_t) p_ed;
+}
+
+static void ed_list_remove_by_addr(ohci_ed_t * p_head, uint8_t dev_addr)
+{
+ ohci_ed_t* p_prev = p_head;
+
+ while( p_prev->next )
+ {
+ ohci_ed_t* ed = (ohci_ed_t*) p_prev->next;
+
+ if (ed->dev_addr == dev_addr)
+ {
+ // unlink ed
+ p_prev->next = ed->next;
+
+ // point the removed ED's next pointer to list head to make sure HC can always safely move away from this ED
+ ed->next = (uint32_t) p_head;
+ ed->used = 0;
+ }
+
+ // check next valid since we could remove it
+ if (p_prev->next) p_prev = (ohci_ed_t*) p_prev->next;
+ }
+}
+
+bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc)
+{
+ (void) rhport;
+
+ // TODO iso support
+ TU_ASSERT(ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS);
+
+ //------------- Prepare Queue Head -------------//
+ ohci_ed_t * p_ed;
+
+ if ( ep_desc->bEndpointAddress == 0 )
+ {
+ p_ed = &ohci_data.control[dev_addr].ed;
+ }else
+ {
+ p_ed = ed_find_free();
+ }
+ TU_ASSERT(p_ed);
+
+ ed_init( p_ed, dev_addr, ep_desc->wMaxPacketSize.size, ep_desc->bEndpointAddress,
+ ep_desc->bmAttributes.xfer, ep_desc->bInterval );
+
+ // control of dev0 is used as static async head
+ if ( dev_addr == 0 )
+ {
+ p_ed->skip = 0; // only need to clear skip bit
+ return true;
+ }
+
+ ed_list_insert( p_ed_head[ep_desc->bmAttributes.xfer], p_ed );
+
+ return true;
+}
+
+static ohci_gtd_t * gtd_find_free(void)
+{
+ for(uint8_t i=0; i < HCD_MAX_XFER; i++)
+ {
+ if ( !ohci_data.gtd_pool[i].used ) return &ohci_data.gtd_pool[i];
+ }
+
+ return NULL;
+}
+
+static void td_insert_to_ed(ohci_ed_t* p_ed, ohci_gtd_t * p_gtd)
+{
+ // tail is always NULL
+ if ( tu_align16(p_ed->td_head.address) == 0 )
+ { // TD queue is empty --> head = TD
+ p_ed->td_head.address |= (uint32_t) p_gtd;
+ }
+ else
+ { // TODO currently only support queue up to 2 TD each endpoint at a time
+ ((ohci_gtd_t*) tu_align16(p_ed->td_head.address))->next = (uint32_t) p_gtd;
+ }
+}
+
+static bool pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete)
+{
+ ohci_ed_t* const p_ed = ed_from_addr(dev_addr, ep_addr);
+
+ // not support ISO yet
+ TU_VERIFY ( !p_ed->is_iso );
+
+ ohci_gtd_t * const p_gtd = gtd_find_free();
+ TU_ASSERT(p_gtd); // not enough gtd
+
+ gtd_init(p_gtd, buffer, total_bytes);
+ p_gtd->index = p_ed-ohci_data.ed_pool;
+
+ if ( int_on_complete ) p_gtd->delay_interrupt = OHCI_INT_ON_COMPLETE_YES;
+
+ td_insert_to_ed(p_ed, p_gtd);
+
+ return true;
+}
+
+bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes)
+{
+ return pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes, false);
+}
+
+bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete)
+{
+ (void) int_on_complete;
+ TU_ASSERT( pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes, true) );
+
+ tusb_xfer_type_t xfer_type = ed_get_xfer_type( ed_from_addr(dev_addr, ep_addr) );
+
+ if (TUSB_XFER_BULK == xfer_type) OHCI_REG->command_status_bit.bulk_list_filled = 1;
+
+ return true;
+}
+
+bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr)
+{
+ ohci_ed_t const * const p_ed = ed_from_addr(dev_addr, ep_addr);
+ return tu_align16(p_ed->td_head.address) != tu_align16(p_ed->td_tail);
+}
+
+bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr)
+{
+ ohci_ed_t const * const p_ed = ed_from_addr(dev_addr, ep_addr);
+ return p_ed->td_head.halted && p_ed->is_stalled;
+}
+
+bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr)
+{
+ ohci_ed_t * const p_ed = ed_from_addr(dev_addr, ep_addr);
+
+ p_ed->is_stalled = 0;
+ p_ed->td_tail &= 0x0Ful; // set tail pointer back to NULL
+
+ p_ed->td_head.toggle = 0; // reset data toggle
+ p_ed->td_head.halted = 0;
+
+ if ( TUSB_XFER_BULK == ed_get_xfer_type(p_ed) ) OHCI_REG->command_status_bit.bulk_list_filled = 1;
+
+ return true;
+}
+
+
+//--------------------------------------------------------------------+
+// OHCI Interrupt Handler
+//--------------------------------------------------------------------+
+static ohci_td_item_t* list_reverse(ohci_td_item_t* td_head)
+{
+ ohci_td_item_t* td_reverse_head = NULL;
+
+ while(td_head != NULL)
+ {
+ uint32_t next = td_head->next;
+
+ // make current's item become reverse's first item
+ td_head->next = (uint32_t) td_reverse_head;
+ td_reverse_head = td_head;
+
+ td_head = (ohci_td_item_t*) next; // advance to next item
+ }
+
+ return td_reverse_head;
+}
+
+static inline bool gtd_is_control(ohci_gtd_t const * const p_qtd)
+{
+ return ((uint32_t) p_qtd) < ((uint32_t) ohci_data.gtd_pool); // check ohci_data_t for memory layout
+}
+
+static inline ohci_ed_t* gtd_get_ed(ohci_gtd_t const * const p_qtd)
+{
+ if ( gtd_is_control(p_qtd) )
+ {
+ return &ohci_data.control[p_qtd->index].ed;
+ }else
+ {
+ return &ohci_data.ed_pool[p_qtd->index];
+ }
+}
+
+static inline uint32_t gtd_xfer_byte_left(uint32_t buffer_end, uint32_t current_buffer)
+{ // 5.2.9 OHCI sample code
+ return (tu_align4k(buffer_end ^ current_buffer) ? 0x1000 : 0) +
+ tu_offset4k(buffer_end) - tu_offset4k(current_buffer) + 1;
+}
+
+static void done_queue_isr(uint8_t hostid)
+{
+ (void) hostid;
+
+ // done head is written in reversed order of completion --> need to reverse the done queue first
+ ohci_td_item_t* td_head = list_reverse ( (ohci_td_item_t*) tu_align16(ohci_data.hcca.done_head) );
+
+ while( td_head != NULL )
+ {
+ // TODO check if td_head is iso td
+ //------------- Non ISO transfer -------------//
+ ohci_gtd_t * const p_qtd = (ohci_gtd_t *) td_head;
+ xfer_result_t const event = (p_qtd->condition_code == OHCI_CCODE_NO_ERROR) ? XFER_RESULT_SUCCESS :
+ (p_qtd->condition_code == OHCI_CCODE_STALL) ? XFER_RESULT_STALLED : XFER_RESULT_FAILED;
+
+ p_qtd->used = 0; // free TD
+ if ( (p_qtd->delay_interrupt == OHCI_INT_ON_COMPLETE_YES) || (event != XFER_RESULT_SUCCESS) )
+ {
+ ohci_ed_t * const p_ed = gtd_get_ed(p_qtd);
+
+ uint32_t const xferred_bytes = p_qtd->expected_bytes - gtd_xfer_byte_left((uint32_t) p_qtd->buffer_end, (uint32_t) p_qtd->current_buffer_pointer);
+
+ // NOTE Assuming the current list is BULK and there is no other EDs in the list has queued TDs.
+ // When there is a error resulting this ED is halted, and this EP still has other queued TD
+ // --> the Bulk list only has this halted EP queueing TDs (remaining)
+ // --> Bulk list will be considered as not empty by HC !!! while there is no attempt transaction on this list
+ // --> HC will not process Control list (due to service ratio when Bulk list not empty)
+ // To walk-around this, the halted ED will have TailP = HeadP (empty list condition), when clearing halt
+ // the TailP must be set back to NULL for processing remaining TDs
+ if ((event != XFER_RESULT_SUCCESS))
+ {
+ p_ed->td_tail &= 0x0Ful;
+ p_ed->td_tail |= tu_align16(p_ed->td_head.address); // mark halted EP as empty queue
+ if ( event == XFER_RESULT_STALLED ) p_ed->is_stalled = 1;
+ }
+
+ hcd_event_xfer_complete(p_ed->dev_addr,
+ tu_edpt_addr(p_ed->ep_number, p_ed->pid == OHCI_PID_IN),
+ event, xferred_bytes);
+ }
+
+ td_head = (ohci_td_item_t*) td_head->next;
+ }
+}
+
+void hal_hcd_isr(uint8_t hostid)
+{
+ uint32_t const int_en = OHCI_REG->interrupt_enable;
+ uint32_t const int_status = OHCI_REG->interrupt_status & int_en;
+
+ if (int_status == 0) return;
+
+ //------------- RootHub status -------------//
+ if ( int_status & OHCI_INT_RHPORT_STATUS_CHANGE_MASK )
+ {
+ uint32_t const rhport_status = OHCI_REG->rhport_status[0] & OHCI_RHPORT_ALL_CHANGE_MASK;
+
+ // TODO dual port is not yet supported
+ if ( rhport_status & OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK )
+ {
+ // TODO check if remote wake-up
+ if ( OHCI_REG->rhport_status_bit[0].current_connect_status )
+ {
+ // TODO reset port immediately, without this controller will got 2-3 (debouncing connection status change)
+ OHCI_REG->rhport_status[0] = OHCI_RHPORT_PORT_RESET_STATUS_MASK;
+ hcd_event_device_attach(0);
+ }else
+ {
+ hcd_event_device_remove(0);
+ }
+ }
+
+ if ( rhport_status & OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK)
+ {
+
+ }
+
+ OHCI_REG->rhport_status[0] = rhport_status; // acknowledge all interrupt
+ }
+
+ //------------- Transfer Complete -------------//
+ if ( int_status & OHCI_INT_WRITEBACK_DONEHEAD_MASK)
+ {
+ done_queue_isr(hostid);
+ }
+
+ OHCI_REG->interrupt_status = int_status; // Acknowledge handled interrupt
+}
+//--------------------------------------------------------------------+
+// HELPER
+//--------------------------------------------------------------------+
+
+
+#endif
+
diff --git a/src/host/ohci/ohci.h b/src/host/ohci/ohci.h new file mode 100644 index 000000000..5c0bd0b45 --- /dev/null +++ b/src/host/ohci/ohci.h @@ -0,0 +1,303 @@ +/**************************************************************************/
+/*!
+ @file ohci.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup Group_HCD
+ * @{
+ * \defgroup OHCI
+ * \brief OHCI driver. All documents sources mentioned here (eg section 3.5) is referring to OHCI Specs unless state otherwise
+ * @{ */
+
+#ifndef _TUSB_OHCI_H_
+#define _TUSB_OHCI_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#include "common/tusb_common.h"
+
+//--------------------------------------------------------------------+
+// OHCI CONFIGURATION & CONSTANTS
+//--------------------------------------------------------------------+
+#define HOST_HCD_XFER_INTERRUPT // TODO interrupt is used widely, should always be enalbed
+#define OHCI_PERIODIC_LIST (defined HOST_HCD_XFER_INTERRUPT || defined HOST_HCD_XFER_ISOCHRONOUS)
+
+// TODO merge OHCI with EHCI
+enum {
+ OHCI_MAX_ITD = 4
+};
+
+enum {
+ OHCI_PID_SETUP = 0,
+ OHCI_PID_OUT,
+ OHCI_PID_IN,
+};
+
+//--------------------------------------------------------------------+
+// OHCI Data Structure
+//--------------------------------------------------------------------+
+typedef struct {
+ uint32_t interrupt_table[32];
+ volatile uint16_t frame_number;
+ volatile uint16_t frame_pad;
+ volatile uint32_t done_head;
+ uint8_t reserved[116+4]; // TODO try to make use of this area if possible, extra 4 byte to make the whole struct size = 256
+}ohci_hcca_t; // ATTR_ALIGNED(256)
+
+TU_VERIFY_STATIC( sizeof(ohci_hcca_t) == 256, "size is not correct" );
+
+typedef struct {
+ uint32_t reserved[2];
+ volatile uint32_t next;
+ uint32_t reserved2;
+}ohci_td_item_t;
+
+
+typedef struct ATTR_ALIGNED(16)
+{
+ // Word 0
+ uint32_t used : 1;
+ uint32_t index : 4; // endpoint index the td belongs to, or device address in case of control xfer
+ uint32_t expected_bytes : 13; // TODO available for hcd
+
+ uint32_t buffer_rounding : 1;
+ uint32_t pid : 2;
+ uint32_t delay_interrupt : 3;
+ volatile uint32_t data_toggle : 2;
+ volatile uint32_t error_count : 2;
+ volatile uint32_t condition_code : 4;
+
+ // Word 1
+ volatile uint8_t* current_buffer_pointer;
+
+ // Word 2 : next TD
+ volatile uint32_t next;
+
+ // Word 3
+ uint8_t* buffer_end;
+} ohci_gtd_t;
+
+TU_VERIFY_STATIC( sizeof(ohci_gtd_t) == 16, "size is not correct" );
+
+typedef struct ATTR_ALIGNED(16)
+{
+ // Word 0
+ uint32_t dev_addr : 7;
+ uint32_t ep_number : 4;
+ uint32_t pid : 2; // 00b from TD, 01b Out, 10b In
+ uint32_t speed : 1;
+ uint32_t skip : 1;
+ uint32_t is_iso : 1;
+ uint32_t max_packet_size : 11;
+ // HCD: make use of 5 reserved bits
+ uint32_t used : 1;
+ uint32_t is_interrupt_xfer : 1;
+ uint32_t is_stalled : 1;
+ uint32_t : 2;
+
+ // Word 1
+ uint32_t td_tail;
+
+ // Word 2
+ volatile union {
+ uint32_t address;
+ struct {
+ uint32_t halted : 1;
+ uint32_t toggle : 1;
+ uint32_t : 30;
+ };
+ }td_head;
+
+ // Word 3: next ED
+ uint32_t next;
+} ohci_ed_t;
+
+TU_VERIFY_STATIC( sizeof(ohci_ed_t) == 16, "size is not correct" );
+
+typedef struct ATTR_ALIGNED(32)
+{
+ /*---------- Word 1 ----------*/
+ uint32_t starting_frame : 16;
+ uint32_t : 5; // can be used
+ uint32_t delay_interrupt : 3;
+ uint32_t frame_count : 3;
+ uint32_t : 1; // can be used
+ volatile uint32_t condition_code : 4;
+
+ /*---------- Word 2 ----------*/
+ uint32_t buffer_page0; // 12 lsb bits can be used
+
+ /*---------- Word 3 ----------*/
+ volatile uint32_t next;
+
+ /*---------- Word 4 ----------*/
+ uint32_t buffer_end;
+
+ /*---------- Word 5-8 ----------*/
+ volatile uint16_t offset_packetstatus[8];
+} ochi_itd_t;
+
+TU_VERIFY_STATIC( sizeof(ochi_itd_t) == 32, "size is not correct" );
+
+// structure with member alignment required from large to small
+typedef struct ATTR_ALIGNED(256)
+{
+ ohci_hcca_t hcca;
+
+ ohci_ed_t bulk_head_ed; // static bulk head (dummy)
+ ohci_ed_t period_head_ed; // static periodic list head (dummy)
+
+ // control endpoints has reserved resources
+ struct {
+ ohci_ed_t ed;
+ ohci_gtd_t gtd;
+ }control[CFG_TUSB_HOST_DEVICE_MAX+1];
+
+ // ochi_itd_t itd[OHCI_MAX_ITD]; // itd requires alignment of 32
+ ohci_ed_t ed_pool[HCD_MAX_ENDPOINT];
+ ohci_gtd_t gtd_pool[HCD_MAX_XFER];
+
+} ohci_data_t;
+
+//--------------------------------------------------------------------+
+// OHCI Operational Register
+//--------------------------------------------------------------------+
+
+
+//--------------------------------------------------------------------+
+// OHCI Data Organization
+//--------------------------------------------------------------------+
+typedef volatile struct
+{
+ uint32_t revision;
+
+ union {
+ uint32_t control;
+ struct {
+ uint32_t control_bulk_service_ratio : 2;
+ uint32_t periodic_list_enable : 1;
+ uint32_t isochronous_enable : 1;
+ uint32_t control_list_enable : 1;
+ uint32_t bulk_list_enable : 1;
+ uint32_t hc_functional_state : 2;
+ uint32_t interrupt_routing : 1;
+ uint32_t remote_wakeup_connected : 1;
+ uint32_t remote_wakeup_enale : 1;
+ uint32_t : 0;
+ }control_bit;
+ };
+
+ union {
+ uint32_t command_status;
+ struct {
+ uint32_t controller_reset : 1;
+ uint32_t control_list_filled : 1;
+ uint32_t bulk_list_filled : 1;
+ uint32_t ownership_change_request : 1;
+ uint32_t : 12;
+ uint32_t scheduling_overrun_count : 2;
+ }command_status_bit;
+ };
+
+ uint32_t interrupt_status;
+ uint32_t interrupt_enable;
+ uint32_t interrupt_disable;
+
+ uint32_t hcca;
+ uint32_t period_current_ed;
+ uint32_t control_head_ed;
+ uint32_t control_current_ed;
+ uint32_t bulk_head_ed;
+ uint32_t bulk_current_ed;
+ uint32_t done_head;
+
+ uint32_t frame_interval;
+ uint32_t frame_remaining;
+ uint32_t frame_number;
+ uint32_t periodic_start;
+ uint32_t lowspeed_threshold;
+
+ uint32_t rh_descriptorA;
+ uint32_t rh_descriptorB;
+
+ union {
+ uint32_t rh_status;
+ struct {
+ uint32_t local_power_status : 1; // read Local Power Status; write: Clear Global Power
+ uint32_t over_current_indicator : 1;
+ uint32_t : 13;
+ uint32_t device_remote_wakeup_enable : 1;
+ uint32_t local_power_status_change : 1;
+ uint32_t over_current_indicator_change : 1;
+ uint32_t : 13;
+ uint32_t clear_remote_wakeup_enable : 1;
+ }rh_status_bit;
+ };
+
+ union {
+ uint32_t rhport_status[2]; // TODO NXP OHCI controller only has 2 ports
+ struct {
+ uint32_t current_connect_status : 1;
+ uint32_t port_enable_status : 1;
+ uint32_t port_suspend_status : 1;
+ uint32_t port_over_current_indicator : 1;
+ uint32_t port_reset_status : 1;
+ uint32_t : 3;
+ uint32_t port_power_status : 1;
+ uint32_t low_speed_device_attached : 1;
+ uint32_t : 6;
+ uint32_t connect_status_change : 1;
+ uint32_t port_enable_status_change : 1;
+ uint32_t port_suspend_status_change : 1;
+ uint32_t port_over_current_indicator_change : 1;
+ uint32_t port_reset_status_change : 1;
+ uint32_t : 0;
+ }rhport_status_bit[2];
+ };
+}ohci_registers_t;
+
+TU_VERIFY_STATIC( sizeof(ohci_registers_t) == 0x5c, "size is not correct");
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_OHCI_H_ */
+
+/** @} */
+/** @} */
diff --git a/src/host/usbh.c b/src/host/usbh.c new file mode 100644 index 000000000..39de4f7e7 --- /dev/null +++ b/src/host/usbh.c @@ -0,0 +1,697 @@ +/**************************************************************************/
+/*!
+ @file usbd_host.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "common/tusb_common.h"
+
+#if TUSB_OPT_HOST_ENABLED
+
+#define _TINY_USB_SOURCE_FILE_
+
+#ifndef CFG_TUH_TASK_QUEUE_SZ
+#define CFG_TUH_TASK_QUEUE_SZ 16
+#endif
+
+#ifndef CFG_TUH_TASK_STACK_SZ
+#define CFG_TUH_TASK_STACK_SZ 200
+#endif
+
+#ifndef CFG_TUH_TASK_PRIO
+#define CFG_TUH_TASK_PRIO 0
+#endif
+
+
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "tusb.h"
+#include "hub.h"
+#include "usbh_hcd.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+static host_class_driver_t const usbh_class_drivers[] =
+{
+ #if CFG_TUH_CDC
+ {
+ .class_code = TUSB_CLASS_CDC,
+ .init = cdch_init,
+ .open = cdch_open,
+ .isr = cdch_isr,
+ .close = cdch_close
+ },
+ #endif
+
+ #if CFG_TUH_MSC
+ {
+ .class_code = TUSB_CLASS_MSC,
+ .init = msch_init,
+ .open = msch_open,
+ .isr = msch_isr,
+ .close = msch_close
+ },
+ #endif
+
+ #if HOST_CLASS_HID
+ {
+ .class_code = TUSB_CLASS_HID,
+ .init = hidh_init,
+ .open = hidh_open_subtask,
+ .isr = hidh_isr,
+ .close = hidh_close
+ },
+ #endif
+
+ #if CFG_TUH_HUB
+ {
+ .class_code = TUSB_CLASS_HUB,
+ .init = hub_init,
+ .open = hub_open,
+ .isr = hub_isr,
+ .close = hub_close
+ },
+ #endif
+
+ #if CFG_TUSB_HOST_CUSTOM_CLASS
+ {
+ .class_code = TUSB_CLASS_VENDOR_SPECIFIC,
+ .init = cush_init,
+ .open = cush_open_subtask,
+ .isr = cush_isr,
+ .close = cush_close
+ }
+ #endif
+};
+
+enum { USBH_CLASS_DRIVER_COUNT = TU_ARRAY_SZIE(usbh_class_drivers) };
+
+//--------------------------------------------------------------------+
+// INTERNAL OBJECT & FUNCTION DECLARATION
+//--------------------------------------------------------------------+
+CFG_TUSB_MEM_SECTION usbh_device_t _usbh_devices[CFG_TUSB_HOST_DEVICE_MAX+1]; // including zero-address
+
+OSAL_TASK_DEF(_usbh_task_def, "usbh", usbh_task, CFG_TUH_TASK_PRIO, CFG_TUH_TASK_STACK_SZ);
+
+// Event queue
+// role device/host is used by OS NONE for mutex (disable usb isr) only
+OSAL_QUEUE_DEF(OPT_MODE_HOST, _usbh_qdef, CFG_TUH_TASK_QUEUE_SZ, hcd_event_t);
+static osal_queue_t _usbh_q;
+
+CFG_TUSB_MEM_SECTION ATTR_ALIGNED(4) static uint8_t _usbh_ctrl_buf[CFG_TUSB_HOST_ENUM_BUFFER_SIZE];
+
+//------------- Reporter Task Data -------------//
+
+//------------- Helper Function Prototypes -------------//
+static inline uint8_t get_new_address(void) ATTR_ALWAYS_INLINE;
+static inline uint8_t get_configure_number_for_device(tusb_desc_device_t* dev_desc) ATTR_ALWAYS_INLINE;
+static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id);
+
+//--------------------------------------------------------------------+
+// PUBLIC API (Parameter Verification is required)
+//--------------------------------------------------------------------+
+tusb_device_state_t tuh_device_get_state (uint8_t const dev_addr)
+{
+ TU_ASSERT( dev_addr <= CFG_TUSB_HOST_DEVICE_MAX, TUSB_DEVICE_STATE_UNPLUG);
+ return (tusb_device_state_t) _usbh_devices[dev_addr].state;
+}
+
+//--------------------------------------------------------------------+
+// CLASS-USBD API (don't require to verify parameters)
+//--------------------------------------------------------------------+
+bool usbh_init(void)
+{
+ tu_memclr(_usbh_devices, sizeof(usbh_device_t)*(CFG_TUSB_HOST_DEVICE_MAX+1));
+
+ //------------- Enumeration & Reporter Task init -------------//
+ _usbh_q = osal_queue_create( &_usbh_qdef );
+ TU_ASSERT(_usbh_q != NULL);
+
+ osal_task_create(&_usbh_task_def);
+
+ //------------- Semaphore, Mutex for Control Pipe -------------//
+ for(uint8_t i=0; i<CFG_TUSB_HOST_DEVICE_MAX+1; i++) // including address zero
+ {
+ usbh_device_t * const dev = &_usbh_devices[i];
+
+ dev->control.sem_hdl = osal_semaphore_create(&dev->control.sem_def);
+ TU_ASSERT(dev->control.sem_hdl != NULL);
+
+ dev->control.mutex_hdl = osal_mutex_create(&dev->control.mutex_def);
+ TU_ASSERT(dev->control.mutex_hdl != NULL);
+
+ memset(dev->itf2drv, 0xff, sizeof(dev->itf2drv)); // invalid mapping
+ memset(dev->ep2drv , 0xff, sizeof(dev->ep2drv )); // invalid mapping
+ }
+
+ // Class drivers init
+ for (uint8_t drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++) usbh_class_drivers[drv_id].init();
+
+ TU_ASSERT(hcd_init());
+ hcd_int_enable(TUH_OPT_RHPORT);
+
+ return true;
+}
+
+//------------- USBH control transfer -------------//
+bool usbh_control_xfer (uint8_t dev_addr, tusb_control_request_t* request, uint8_t* data)
+{
+ usbh_device_t* dev = &_usbh_devices[dev_addr];
+ const uint8_t rhport = dev->rhport;
+
+ TU_ASSERT(osal_mutex_lock(dev->control.mutex_hdl, OSAL_TIMEOUT_NORMAL));
+
+ dev->control.request = *request;
+ dev->control.pipe_status = 0;
+
+ // Setup Stage
+ hcd_setup_send(rhport, dev_addr, (uint8_t*) &dev->control.request);
+ TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL));
+
+ // Data stage : first data toggle is always 1
+ if ( request->wLength )
+ {
+ hcd_edpt_xfer(rhport, dev_addr, tu_edpt_addr(0, request->bmRequestType_bit.direction), data, request->wLength);
+ TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL));
+ }
+
+ // Status : data toggle is always 1
+ hcd_edpt_xfer(rhport, dev_addr, tu_edpt_addr(0, 1-request->bmRequestType_bit.direction), NULL, 0);
+ TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL));
+
+ osal_mutex_unlock(dev->control.mutex_hdl);
+
+ if ( XFER_RESULT_STALLED == dev->control.pipe_status ) return false;
+ if ( XFER_RESULT_FAILED == dev->control.pipe_status ) return false;
+
+ return true;
+}
+
+tusb_error_t usbh_pipe_control_open(uint8_t dev_addr, uint8_t max_packet_size)
+{
+ osal_semaphore_reset( _usbh_devices[dev_addr].control.sem_hdl );
+ //osal_mutex_reset( usbh_devices[dev_addr].control.mutex_hdl );
+
+ tusb_desc_endpoint_t ep0_desc =
+ {
+ .bLength = sizeof(tusb_desc_endpoint_t),
+ .bDescriptorType = TUSB_DESC_ENDPOINT,
+ .bEndpointAddress = 0,
+ .bmAttributes = { .xfer = TUSB_XFER_CONTROL },
+ .wMaxPacketSize = { .size = max_packet_size },
+ .bInterval = 0
+ };
+
+ hcd_edpt_open(_usbh_devices[dev_addr].rhport, dev_addr, &ep0_desc);
+
+ return TUSB_ERROR_NONE;
+}
+
+//--------------------------------------------------------------------+
+// USBH-HCD ISR/Callback API
+//--------------------------------------------------------------------+
+// interrupt caused by a TD (with IOC=1) in pipe of class class_code
+void hcd_event_xfer_complete(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
+{
+ usbh_device_t* dev = &_usbh_devices[ dev_addr ];
+
+ if (0 == tu_edpt_number(ep_addr))
+ {
+ dev->control.pipe_status = event;
+// usbh_devices[ pipe_hdl.dev_addr ].control.xferred_bytes = xferred_bytes; not yet neccessary
+ osal_semaphore_post( dev->control.sem_hdl, true );
+ }
+ else
+ {
+ uint8_t drv_id = dev->ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)];
+ TU_ASSERT(drv_id < USBH_CLASS_DRIVER_COUNT, );
+
+ if (usbh_class_drivers[drv_id].isr)
+ {
+ usbh_class_drivers[drv_id].isr(dev_addr, ep_addr, event, xferred_bytes);
+ }
+ else
+ {
+ TU_BREAKPOINT(); // something wrong, no one claims the isr's source
+ }
+ }
+}
+
+void hcd_event_device_attach(uint8_t rhport)
+{
+ hcd_event_t event =
+ {
+ .rhport = rhport,
+ .event_id = HCD_EVENT_DEVICE_ATTACH
+ };
+
+ event.attach.hub_addr = 0;
+ event.attach.hub_port = 0;
+
+ hcd_event_handler(&event, true);
+}
+
+void hcd_event_handler(hcd_event_t const* event, bool in_isr)
+{
+ switch (event->event_id)
+ {
+ default:
+ osal_queue_send(_usbh_q, event, in_isr);
+ break;
+ }
+}
+
+void hcd_event_device_remove(uint8_t hostid)
+{
+ hcd_event_t event =
+ {
+ .rhport = hostid,
+ .event_id = HCD_EVENT_DEVICE_REMOVE
+ };
+
+ event.attach.hub_addr = 0;
+ event.attach.hub_port = 0;
+
+ hcd_event_handler(&event, true);
+}
+
+
+// a device unplugged on hostid, hub_addr, hub_port
+// return true if found and unmounted device, false if cannot find
+static void usbh_device_unplugged(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port)
+{
+ //------------- find the all devices (star-network) under port that is unplugged -------------//
+ for (uint8_t dev_addr = 0; dev_addr <= CFG_TUSB_HOST_DEVICE_MAX; dev_addr ++)
+ {
+ usbh_device_t* dev = &_usbh_devices[dev_addr];
+
+ // TODO Hub multiple level
+ if (dev->rhport == rhport &&
+ (hub_addr == 0 || dev->hub_addr == hub_addr) && // hub_addr == 0 & hub_port == 0 means roothub
+ (hub_port == 0 || dev->hub_port == hub_port) &&
+ dev->state != TUSB_DEVICE_STATE_UNPLUG)
+ {
+ // Invoke callback before close driver
+ if (tuh_umount_cb) tuh_umount_cb(dev_addr);
+
+ // Close class driver
+ for (uint8_t drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++) usbh_class_drivers[drv_id].close(dev_addr);
+
+ memset(dev->itf2drv, 0xff, sizeof(dev->itf2drv)); // invalid mapping
+ memset(dev->ep2drv , 0xff, sizeof(dev->ep2drv )); // invalid mapping
+
+ hcd_device_close(rhport, dev_addr);
+
+ dev->state = TUSB_DEVICE_STATE_UNPLUG;
+ }
+ }
+}
+
+//--------------------------------------------------------------------+
+// ENUMERATION TASK
+//--------------------------------------------------------------------+
+
+bool enum_task(hcd_event_t* event)
+{
+ enum {
+#if 1
+ // FIXME ohci LPC1769 xpresso + debugging to have 1st control xfer to work, some kind of timing or ohci driver issue !!!
+ POWER_STABLE_DELAY = 100,
+ RESET_DELAY = 500
+#else
+ POWER_STABLE_DELAY = 500,
+ RESET_DELAY = 200, // USB specs say only 50ms but many devices require much longer
+#endif
+ };
+
+ // for OSAL_NONE local variable won't retain value after blocking service sem_wait/queue_recv
+ static uint8_t configure_selected = 1; // TODO move
+
+ usbh_device_t* dev0 = &_usbh_devices[0];
+ tusb_control_request_t request;
+
+ dev0->rhport = event->rhport; // TODO refractor integrate to device_pool
+ dev0->hub_addr = event->attach.hub_addr;
+ dev0->hub_port = event->attach.hub_port;
+ dev0->state = TUSB_DEVICE_STATE_UNPLUG;
+
+ //------------- connected/disconnected directly with roothub -------------//
+ if ( dev0->hub_addr == 0)
+ {
+ if( hcd_port_connect_status(dev0->rhport) )
+ {
+ // connection event
+ osal_task_delay(POWER_STABLE_DELAY); // wait until device is stable. Increase this if the first 8 bytes is failed to get
+
+ // exit if device unplugged while delaying
+ if ( !hcd_port_connect_status(dev0->rhport) ) return true;
+
+ hcd_port_reset( dev0->rhport ); // port must be reset to have correct speed operation
+ osal_task_delay(RESET_DELAY);
+
+ dev0->speed = hcd_port_speed_get( dev0->rhport );
+ }
+ else
+ {
+ // disconnection event
+ usbh_device_unplugged(dev0->rhport, 0, 0);
+ return true; // restart task
+ }
+ }
+ #if CFG_TUH_HUB
+ //------------- connected/disconnected via hub -------------//
+ else
+ {
+ //------------- Get Port Status -------------//
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN },
+ .bRequest = HUB_REQUEST_GET_STATUS,
+ .wValue = 0,
+ .wIndex = dev0->hub_port,
+ .wLength = 4
+ };
+ // TODO hub refractor
+ TU_VERIFY_HDLR( usbh_control_xfer( dev0->hub_addr, &request, _usbh_ctrl_buf ), hub_status_pipe_queue( dev0->hub_addr) );
+
+ // Acknowledge Port Connection Change
+ hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_CONNECTION_CHANGE);
+
+ hub_port_status_response_t * p_port_status;
+ p_port_status = ((hub_port_status_response_t *) _usbh_ctrl_buf);
+
+ if ( ! p_port_status->status_change.connect_status ) return true; // only handle connection change
+
+ if ( ! p_port_status->status_current.connect_status )
+ {
+ // Disconnection event
+ usbh_device_unplugged(dev0->rhport, dev0->hub_addr, dev0->hub_port);
+
+ (void) hub_status_pipe_queue( dev0->hub_addr ); // done with hub, waiting for next data on status pipe
+ return true; // restart task
+ }
+ else
+ {
+ // Connection Event
+ TU_VERIFY_HDLR(hub_port_reset_subtask(dev0->hub_addr, dev0->hub_port),
+ hub_status_pipe_queue( dev0->hub_addr) ); // TODO hub refractor
+
+ dev0->speed = hub_port_get_speed();
+
+ // Acknowledge Port Reset Change
+ hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_RESET_CHANGE);
+ }
+ }
+ #endif
+
+ TU_ASSERT_ERR( usbh_pipe_control_open(0, 8) );
+
+ //------------- Get first 8 bytes of device descriptor to get Control Endpoint Size -------------//
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN },
+ .bRequest = TUSB_REQ_GET_DESCRIPTOR,
+ .wValue = TUSB_DESC_DEVICE << 8,
+ .wIndex = 0,
+ .wLength = 8
+ };
+ bool is_ok = usbh_control_xfer(0, &request, _usbh_ctrl_buf);
+
+ //------------- Reset device again before Set Address -------------//
+ if (dev0->hub_addr == 0)
+ {
+ // connected directly to roothub
+ TU_ASSERT(is_ok); // TODO some slow device is observed to fail the very fist controller xfer, can try more times
+ hcd_port_reset( dev0->rhport ); // reset port after 8 byte descriptor
+ osal_task_delay(RESET_DELAY);
+ }
+ #if CFG_TUH_HUB
+ else
+ {
+ // connected via a hub
+ TU_VERIFY_HDLR(is_ok, hub_status_pipe_queue( dev0->hub_addr) ); // TODO hub refractor
+
+ if ( hub_port_reset_subtask(dev0->hub_addr, dev0->hub_port) )
+ {
+ // Acknowledge Port Reset Change if Reset Successful
+ hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_RESET_CHANGE);
+ }
+
+ (void) hub_status_pipe_queue( dev0->hub_addr ); // done with hub, waiting for next data on status pipe
+ }
+ #endif
+
+ //------------- Set new address -------------//
+ uint8_t const new_addr = get_new_address();
+ TU_ASSERT(new_addr <= CFG_TUSB_HOST_DEVICE_MAX); // TODO notify application we reach max devices
+
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT },
+ .bRequest = TUSB_REQ_SET_ADDRESS,
+ .wValue = new_addr,
+ .wIndex = 0,
+ .wLength = 0
+ };
+ TU_ASSERT(usbh_control_xfer(0, &request, NULL));
+
+ //------------- update port info & close control pipe of addr0 -------------//
+ usbh_device_t* new_dev = &_usbh_devices[new_addr];
+ new_dev->rhport = dev0->rhport;
+ new_dev->hub_addr = dev0->hub_addr;
+ new_dev->hub_port = dev0->hub_port;
+ new_dev->speed = dev0->speed;
+
+ hcd_device_close(dev0->rhport, 0); // close device 0
+ dev0->state = TUSB_DEVICE_STATE_UNPLUG;
+
+ // open control pipe for new address
+ TU_ASSERT_ERR ( usbh_pipe_control_open(new_addr, ((tusb_desc_device_t*) _usbh_ctrl_buf)->bMaxPacketSize0 ) );
+
+ //------------- Get full device descriptor -------------//
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN },
+ .bRequest = TUSB_REQ_GET_DESCRIPTOR,
+ .wValue = TUSB_DESC_DEVICE << 8,
+ .wIndex = 0,
+ .wLength = 18
+ };
+ TU_ASSERT(usbh_control_xfer(new_addr, &request, _usbh_ctrl_buf));
+
+ // update device info TODO alignment issue
+ new_dev->vendor_id = ((tusb_desc_device_t*) _usbh_ctrl_buf)->idVendor;
+ new_dev->product_id = ((tusb_desc_device_t*) _usbh_ctrl_buf)->idProduct;
+ new_dev->configure_count = ((tusb_desc_device_t*) _usbh_ctrl_buf)->bNumConfigurations;
+
+ configure_selected = get_configure_number_for_device((tusb_desc_device_t*) _usbh_ctrl_buf);
+ TU_ASSERT(configure_selected <= new_dev->configure_count); // TODO notify application when invalid configuration
+
+ //------------- Get 9 bytes of configuration descriptor -------------//
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN },
+ .bRequest = TUSB_REQ_GET_DESCRIPTOR,
+ .wValue = (TUSB_DESC_CONFIGURATION << 8) | (configure_selected - 1),
+ .wIndex = 0,
+ .wLength = 9
+ };
+ TU_ASSERT( usbh_control_xfer(new_addr, &request, _usbh_ctrl_buf));
+
+ // TODO not enough buffer to hold configuration descriptor
+ TU_ASSERT( CFG_TUSB_HOST_ENUM_BUFFER_SIZE >= ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength );
+
+ //------------- Get full configuration descriptor -------------//
+ request.wLength = ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength; // full length
+ TU_ASSERT( usbh_control_xfer( new_addr, &request, _usbh_ctrl_buf ) );
+
+ // update configuration info
+ new_dev->interface_count = ((tusb_desc_configuration_t*) _usbh_ctrl_buf)->bNumInterfaces;
+
+ //------------- Set Configure -------------//
+ request = (tusb_control_request_t ) {
+ .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT },
+ .bRequest = TUSB_REQ_SET_CONFIGURATION,
+ .wValue = configure_selected,
+ .wIndex = 0,
+ .wLength = 0
+ };
+ TU_ASSERT(usbh_control_xfer( new_addr, &request, NULL ));
+
+ new_dev->state = TUSB_DEVICE_STATE_CONFIGURED;
+
+ //------------- TODO Get String Descriptors -------------//
+
+ //------------- parse configuration & install drivers -------------//
+ uint8_t const* p_desc = _usbh_ctrl_buf + sizeof(tusb_desc_configuration_t);
+
+ // parse each interfaces
+ while( p_desc < _usbh_ctrl_buf + ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength )
+ {
+ // skip until we see interface descriptor
+ if ( TUSB_DESC_INTERFACE != tu_desc_type(p_desc) )
+ {
+ p_desc = tu_desc_next(p_desc); // skip the descriptor, increase by the descriptor's length
+ }else
+ {
+ tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc;
+
+ // Check if class is supported
+ uint8_t drv_id;
+ for (drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++)
+ {
+ if ( usbh_class_drivers[drv_id].class_code == desc_itf->bInterfaceClass ) break;
+ }
+
+ if( drv_id >= USBH_CLASS_DRIVER_COUNT )
+ {
+ // skip unsupported class
+ p_desc = tu_desc_next(p_desc);
+ }
+ else
+ {
+ // Interface number must not be used already TODO alternate interface
+ TU_ASSERT( new_dev->itf2drv[desc_itf->bInterfaceNumber] == 0xff );
+ new_dev->itf2drv[desc_itf->bInterfaceNumber] = drv_id;
+
+ if (desc_itf->bInterfaceClass == TUSB_CLASS_HUB && new_dev->hub_addr != 0)
+ {
+ // TODO Attach hub to Hub is not currently supported
+ // skip this interface
+ p_desc = tu_desc_next(p_desc);
+ }
+ else
+ {
+ uint16_t itf_len = 0;
+
+ if ( usbh_class_drivers[drv_id].open(new_dev->rhport, new_addr, desc_itf, &itf_len) )
+ {
+ mark_interface_endpoint(new_dev->ep2drv, p_desc, itf_len, drv_id);
+ }
+
+ TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) );
+ p_desc += itf_len;
+ }
+ }
+ }
+ }
+
+ if (tuh_mount_cb) tuh_mount_cb(new_addr);
+
+ return true;
+}
+
+bool usbh_task_body(void)
+{
+ while (1)
+ {
+ hcd_event_t event;
+ if ( !osal_queue_receive(_usbh_q, &event) ) return false;
+
+ switch (event.event_id)
+ {
+ case HCD_EVENT_DEVICE_ATTACH:
+ case HCD_EVENT_DEVICE_REMOVE:
+ enum_task(&event);
+ break;
+
+ default: break;
+ }
+ }
+}
+
+/* USB Host task
+ * Thread that handles all device events. With an real RTOS, the task must be a forever loop and never return.
+ * For coding convenience with no RTOS, we use wrapped sub-function for processing to easily return at any time.
+ */
+void usbh_task(void* param)
+{
+ (void) param;
+
+#if CFG_TUSB_OS != OPT_OS_NONE
+ while (1) {
+#endif
+
+ usbh_task_body();
+
+#if CFG_TUSB_OS != OPT_OS_NONE
+ }
+#endif
+}
+
+//--------------------------------------------------------------------+
+// INTERNAL HELPER
+//--------------------------------------------------------------------+
+static inline uint8_t get_new_address(void)
+{
+ for (uint8_t addr=1; addr <= CFG_TUSB_HOST_DEVICE_MAX; addr++)
+ {
+ if (_usbh_devices[addr].state == TUSB_DEVICE_STATE_UNPLUG) return addr;
+ }
+ return CFG_TUSB_HOST_DEVICE_MAX;
+}
+
+static inline uint8_t get_configure_number_for_device(tusb_desc_device_t* dev_desc)
+{
+ uint8_t config_num = 1;
+
+ // invoke callback to ask user which configuration to select
+ if (tuh_device_attached_cb)
+ {
+ config_num = tu_min8(1, tuh_device_attached_cb(dev_desc) );
+ }
+
+ return config_num;
+}
+
+// Helper marking endpoint of interface belongs to class driver
+// TODO merge with usbd
+static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id)
+{
+ uint16_t len = 0;
+
+ while( len < desc_len )
+ {
+ if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
+ {
+ uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress;
+
+ ep2drv[ tu_edpt_number(ep_addr) ][ tu_edpt_dir(ep_addr) ] = driver_id;
+ }
+
+ len += tu_desc_len(p_desc);
+ p_desc = tu_desc_next(p_desc);
+ }
+}
+
+
+#endif
diff --git a/src/host/usbh.h b/src/host/usbh.h new file mode 100644 index 000000000..3656b9a0d --- /dev/null +++ b/src/host/usbh.h @@ -0,0 +1,118 @@ +/**************************************************************************/ +/*! + @file usbh.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_usbh USB Host Core (USBH) + * @{ */ + +#ifndef _TUSB_USBH_H_ +#define _TUSB_USBH_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "osal/osal.h" // TODO refractor move to common.h ? +#include "hcd.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +typedef enum tusb_interface_status_{ + TUSB_INTERFACE_STATUS_READY = 0, + TUSB_INTERFACE_STATUS_BUSY, + TUSB_INTERFACE_STATUS_COMPLETE, + TUSB_INTERFACE_STATUS_ERROR, + TUSB_INTERFACE_STATUS_INVALID_PARA +} tusb_interface_status_t; + +typedef struct { + uint8_t class_code; + + void (* const init) (void); + bool (* const open)(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const * itf_desc, uint16_t* outlen); + void (* const isr) (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t len); + void (* const close) (uint8_t); +} host_class_driver_t; +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ +//tusb_error_t tusbh_configuration_set (uint8_t dev_addr, uint8_t configure_number) ATTR_WARN_UNUSED_RESULT; +tusb_device_state_t tuh_device_get_state (uint8_t dev_addr) ATTR_WARN_UNUSED_RESULT ATTR_PURE; +static inline bool tuh_device_is_configured(uint8_t dev_addr) ATTR_ALWAYS_INLINE ATTR_WARN_UNUSED_RESULT ATTR_PURE; +static inline bool tuh_device_is_configured(uint8_t dev_addr) +{ + return tuh_device_get_state(dev_addr) == TUSB_DEVICE_STATE_CONFIGURED; +} + +//--------------------------------------------------------------------+ +// APPLICATION CALLBACK +//--------------------------------------------------------------------+ +ATTR_WEAK uint8_t tuh_device_attached_cb (tusb_desc_device_t const *p_desc_device) ATTR_WARN_UNUSED_RESULT; + +/** Callback invoked when device is mounted (configured) */ +ATTR_WEAK void tuh_mount_cb (uint8_t dev_addr); + +/** Callback invoked when device is unmounted (bus reset/unplugged) */ +ATTR_WEAK void tuh_umount_cb(uint8_t dev_addr); + +//--------------------------------------------------------------------+ +// CLASS-USBH & INTERNAL API +//--------------------------------------------------------------------+ +#ifdef _TINY_USB_SOURCE_FILE_ + +bool usbh_init(void); +void usbh_task(void* param); + +bool usbh_control_xfer (uint8_t dev_addr, tusb_control_request_t* request, uint8_t* data); + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_USBH_H_ */ + +/** @} */ diff --git a/src/host/usbh_hcd.h b/src/host/usbh_hcd.h new file mode 100644 index 000000000..48bb4bb9d --- /dev/null +++ b/src/host/usbh_hcd.h @@ -0,0 +1,107 @@ +/**************************************************************************/ +/*! + @file usbh_hcd.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup Group_HCD + * @{ */ + +#ifndef _TUSB_USBH_HCD_H_ +#define _TUSB_USBH_HCD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "osal/osal.h" + +//--------------------------------------------------------------------+ +// USBH-HCD common data structure +//--------------------------------------------------------------------+ +typedef struct { + //------------- port -------------// + uint8_t rhport; + uint8_t hub_addr; + uint8_t hub_port; + uint8_t speed; + + //------------- device descriptor -------------// + uint16_t vendor_id; + uint16_t product_id; + uint8_t configure_count; // bNumConfigurations alias + + //------------- configuration descriptor -------------// + uint8_t interface_count; // bNumInterfaces alias + + //------------- device -------------// + volatile uint8_t state; // device state, value from enum tusbh_device_state_t + + //------------- control pipe -------------// + struct { + volatile uint8_t pipe_status; +// uint8_t xferred_bytes; TODO not yet necessary + tusb_control_request_t request; + + osal_semaphore_def_t sem_def; + osal_semaphore_t sem_hdl; // used to synchronize with HCD when control xfer complete + + osal_mutex_def_t mutex_def; + osal_mutex_t mutex_hdl; // used to exclusively occupy control pipe + } control; + + uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid) + uint8_t ep2drv[8][2]; // map endpoint to driver ( 0xff is invalid ) +} usbh_device_t; + +extern usbh_device_t _usbh_devices[CFG_TUSB_HOST_DEVICE_MAX+1]; // including zero-address + +//--------------------------------------------------------------------+ +// callback from HCD ISR +//--------------------------------------------------------------------+ + + + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_USBH_HCD_H_ */ + +/** @} */ diff --git a/src/license.md b/src/license.md new file mode 100644 index 000000000..597d93939 --- /dev/null +++ b/src/license.md @@ -0,0 +1,27 @@ +# License + +<pre>Software License Agreement (BSD License) +Copyright (c) 2013, hathach (tinyusb.org) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT +OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGE.</pre>
\ No newline at end of file diff --git a/src/osal/osal.c b/src/osal/osal.c new file mode 100644 index 000000000..f5105d4d1 --- /dev/null +++ b/src/osal/osal.c @@ -0,0 +1,60 @@ +/**************************************************************************/ +/*! + @file osal.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" +#include "osal.h" + +//--------------------------------------------------------------------+ +// TICK API +//--------------------------------------------------------------------+ +#if CFG_TUSB_OS == OPT_OS_FREERTOS + +uint32_t tusb_hal_millis(void) +{ + return ( ( ((uint64_t) xTaskGetTickCount()) * 1000) / configTICK_RATE_HZ ); +} + +#elif CFG_TUSB_OS == OPT_OS_MYNEWT + +uint32_t tusb_hal_millis(void) +{ + return os_time_ticks_to_ms32( os_time_get() ); +} + +#endif + diff --git a/src/osal/osal.h b/src/osal/osal.h new file mode 100644 index 000000000..55e3e077c --- /dev/null +++ b/src/osal/osal.h @@ -0,0 +1,127 @@ +/**************************************************************************/
+/*!
+ @file osal.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_OSAL_H_
+#define _TUSB_OSAL_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/** \addtogroup group_osal
+ * @{ */
+
+#include "tusb_option.h"
+#include "common/tusb_common.h"
+
+enum
+{
+ OSAL_TIMEOUT_NOTIMEOUT = 0, // return immediately
+ OSAL_TIMEOUT_NORMAL = 10, // default timeout
+ OSAL_TIMEOUT_WAIT_FOREVER = 0xFFFFFFFFUL
+};
+
+#define OSAL_TIMEOUT_CONTROL_XFER OSAL_TIMEOUT_WAIT_FOREVER
+
+typedef void (*osal_task_func_t)( void * );
+
+#if CFG_TUSB_OS == OPT_OS_NONE
+ #include "osal_none.h"
+#else
+ /* RTOS Porting API
+ *
+ * uint32_t tusb_hal_millis(void)
+ *
+ * Task
+ * osal_task_def_t
+ * bool osal_task_create(osal_task_def_t* taskdef)
+ * void osal_task_delay(uint32_t msec)
+ *
+ * Queue
+ * osal_queue_def_t, osal_queue_t
+ * osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
+ * osal_queue_receive (osal_queue_t const queue_hdl, void *p_data, uint32_t msec, uint32_t *p_error)
+ * bool osal_queue_send(osal_queue_t const queue_hdl, void const * data, bool in_isr)
+ * osal_queue_reset()
+ *
+ * Semaphore
+ * osal_semaphore_def_t, osal_semaphore_t
+ * osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
+ * bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
+ * bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec)
+ * void osal_semaphore_reset(osal_semaphore_t const sem_hdl)
+ *
+ * Mutex
+ * osal_mutex_t
+ * osal_mutex_create(osal_mutex_def_t* mdef)
+ * bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
+ * void osal_mutex_lock(osal_mutex_t mutex_hdl, uint32_t msec, uint32_t *p_error)
+ */
+
+ #if CFG_TUSB_OS == OPT_OS_FREERTOS
+ #include "osal_freertos.h"
+ #elif CFG_TUSB_OS == OPT_OS_MYNEWT
+ #include "osal_mynewt.h"
+ #else
+ #error CFG_TUSB_OS is not defined or OS is not supported yet
+ #endif
+
+ // TODO remove subtask related macros later
+
+ //------------- Sub Task -------------//
+ #define OSAL_SUBTASK_BEGIN
+ #define OSAL_SUBTASK_END return TUSB_ERROR_NONE;
+
+ #define STASK_RETURN(_error) return _error;
+ #define STASK_INVOKE(_subtask, _status) (_status) = _subtask
+
+ //------------- Sub Task Assert -------------//
+ #define STASK_ASSERT_ERR(_err) TU_VERIFY_ERR(_err)
+ #define STASK_ASSERT_ERR_HDLR(_err, _func) TU_VERIFY_ERR_HDLR(_err, _func)
+
+ #define STASK_ASSERT(_cond) TU_VERIFY(_cond, TUSB_ERROR_OSAL_TASK_FAILED)
+ #define STASK_ASSERT_HDLR(_cond, _func) TU_VERIFY_HDLR(_cond, _func)
+#endif
+
+#ifdef __cplusplus
+ }
+#endif
+
+/** @} */
+
+#endif /* _TUSB_OSAL_H_ */
diff --git a/src/osal/osal_freertos.h b/src/osal/osal_freertos.h new file mode 100644 index 000000000..acec4a95d --- /dev/null +++ b/src/osal/osal_freertos.h @@ -0,0 +1,186 @@ +/**************************************************************************/ +/*! + @file osal_freeRTOS.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_osal + * @{ + * \defgroup Group_FreeRTOS FreeRTOS + * @{ */ + +#ifndef _TUSB_OSAL_FREERTOS_H_ +#define _TUSB_OSAL_FREERTOS_H_ + +//------------- FreeRTOS Headers -------------// +#include "FreeRTOS.h" +#include "semphr.h" +#include "queue.h" +#include "task.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if 0 +// Helper to determine if we are in ISR to use ISR API (only cover ARM Cortex) +static inline bool in_isr(void) +{ + return (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk); +} +#endif + +//--------------------------------------------------------------------+ +// TASK API +//--------------------------------------------------------------------+ +#define OSAL_TASK_DEF(_name, _str, _func, _prio, _stack_sz) \ + static uint8_t _name##_##buf[_stack_sz*sizeof(StackType_t)]; \ + osal_task_def_t _name = { .func = _func, .prio = _prio, .stack_sz = _stack_sz, .buf = _name##_##buf, .strname = _str }; + +typedef struct +{ + osal_task_func_t func; + + uint16_t prio; + uint16_t stack_sz; + void* buf; + const char* strname; + + StaticTask_t stask; +}osal_task_def_t; + +static inline bool osal_task_create(osal_task_def_t* taskdef) +{ + return NULL != xTaskCreateStatic(taskdef->func, taskdef->strname, taskdef->stack_sz, NULL, taskdef->prio, (StackType_t*) taskdef->buf, &taskdef->stask); +} + +static inline void osal_task_delay(uint32_t msec) +{ + vTaskDelay( pdMS_TO_TICKS(msec) ); +} + +//--------------------------------------------------------------------+ +// Semaphore API +//--------------------------------------------------------------------+ +typedef StaticSemaphore_t osal_semaphore_def_t; +typedef SemaphoreHandle_t osal_semaphore_t; + +static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef) +{ + return xSemaphoreCreateBinaryStatic(semdef); +} + +static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) +{ + return in_isr ? xSemaphoreGiveFromISR(sem_hdl, NULL) : xSemaphoreGive(sem_hdl); +} + +static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec) +{ + uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? portMAX_DELAY : pdMS_TO_TICKS(msec); + return xSemaphoreTake(sem_hdl, ticks); +} + +static inline void osal_semaphore_reset(osal_semaphore_t const sem_hdl) +{ + xQueueReset(sem_hdl); +} + +//--------------------------------------------------------------------+ +// MUTEX API (priority inheritance) +//--------------------------------------------------------------------+ +typedef StaticSemaphore_t osal_mutex_def_t; +typedef SemaphoreHandle_t osal_mutex_t; + +static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef) +{ + return xSemaphoreCreateMutexStatic(mdef); +} + +#define osal_mutex_lock osal_semaphore_wait + +static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl) +{ + return xSemaphoreGive(mutex_hdl); +} + +//--------------------------------------------------------------------+ +// QUEUE API +//--------------------------------------------------------------------+ + +// role device/host is used by OS NONE for mutex (disable usb isr) only +#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \ + static _type _name##_##buf[_depth];\ + osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf }; + +typedef struct +{ + uint16_t depth; + uint16_t item_sz; + void* buf; + + StaticQueue_t sq; +}osal_queue_def_t; + +typedef QueueHandle_t osal_queue_t; + +static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) +{ + return xQueueCreateStatic(qdef->depth, qdef->item_sz, (uint8_t*) qdef->buf, &qdef->sq); +} + +static inline bool osal_queue_receive(osal_queue_t const queue_hdl, void* data) +{ + return xQueueReceive(queue_hdl, data, portMAX_DELAY); +} + +static inline bool osal_queue_send(osal_queue_t const queue_hdl, void const * data, bool in_isr) +{ + return in_isr ? xQueueSendToBackFromISR(queue_hdl, data, NULL) : xQueueSendToBack(queue_hdl, data, OSAL_TIMEOUT_WAIT_FOREVER); +} + +static inline void osal_queue_reset(osal_queue_t const queue_hdl) +{ + xQueueReset(queue_hdl); +} + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_OSAL_FREERTOS_H_ */ + +/** @} */ +/** @} */ diff --git a/src/osal/osal_mynewt.h b/src/osal/osal_mynewt.h new file mode 100644 index 000000000..62b5b45e8 --- /dev/null +++ b/src/osal/osal_mynewt.h @@ -0,0 +1,216 @@ +/**************************************************************************/ +/*! + @file osal_mynewt.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#ifndef OSAL_MYNEWT_H_ +#define OSAL_MYNEWT_H_ + +#include "os/os.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// TASK API +//--------------------------------------------------------------------+ +#define OSAL_TASK_DEF(_name, _str, _func, _prio, _stack_sz) \ + static os_stack_t _name##_##buf[_stack_sz]; \ + osal_task_def_t _name = { .func = _func, .prio = _prio, .stack_sz = _stack_sz, .buf = _name##_##buf, .strname = _str }; + +typedef struct +{ + struct os_task mynewt_task; + osal_task_func_t func; + + uint16_t prio; + uint16_t stack_sz; + void* buf; + const char* strname; +}osal_task_def_t; + +static inline bool osal_task_create(osal_task_def_t* taskdef) +{ + return OS_OK == os_task_init(&taskdef->mynewt_task, taskdef->strname, taskdef->func, NULL, taskdef->prio, OS_WAIT_FOREVER, + (os_stack_t*) taskdef->buf, taskdef->stack_sz); +} + +static inline void osal_task_delay(uint32_t msec) +{ + os_time_delay( os_time_ms_to_ticks32(msec) ); +} + +//--------------------------------------------------------------------+ +// QUEUE API +//--------------------------------------------------------------------+ + +// role device/host is used by OS NONE for mutex (disable usb isr) only +#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \ + static _type _name##_##buf[_depth];\ + static struct os_event* _name##_##evbuf[_depth];\ + osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf, .evbuf = _name##_##evbuf};\ + +typedef struct +{ + uint16_t depth; + uint16_t item_sz; + void* buf; + void* evbuf; + + struct os_mempool mpool; + struct os_mempool epool; + + struct os_eventq evq; +}osal_queue_def_t; + +typedef osal_queue_def_t* osal_queue_t; + +static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) +{ + if ( OS_OK != os_mempool_init(&qdef->mpool, qdef->depth, qdef->item_sz, qdef->buf, "usbd queue") ) return NULL; + if ( OS_OK != os_mempool_init(&qdef->epool, qdef->depth, sizeof(struct os_event), qdef->evbuf, "usbd evqueue") ) return NULL; + + os_eventq_init(&qdef->evq); + return (osal_queue_t) qdef; +} + +static inline void osal_queue_receive (osal_queue_t const queue_hdl, void *p_data, uint32_t msec, tusb_error_t *p_error) +{ + (void) msec; + struct os_event* ev; + + if ( msec == 0 ) + { + ev = os_eventq_get_no_wait(&queue_hdl->evq); + if ( !ev ) + { + *p_error = TUSB_ERROR_OSAL_TIMEOUT; + return; + } + }else + { + ev = os_eventq_get(&queue_hdl->evq); + } + + memcpy(p_data, ev->ev_arg, queue_hdl->item_sz); // copy message + os_memblock_put(&queue_hdl->mpool, ev->ev_arg); // put back mem block + os_memblock_put(&queue_hdl->epool, ev); // put back ev block + + *p_error = TUSB_ERROR_NONE; +} + +static inline bool osal_queue_send(osal_queue_t const queue_hdl, void const * data, bool in_isr) +{ + (void) in_isr; + + // get a block from mem pool for data + void* ptr = os_memblock_get(&queue_hdl->mpool); + if (!ptr) return false; + memcpy(ptr, data, queue_hdl->item_sz); + + // get a block from event pool to put into queue + struct os_event* ev = (struct os_event*) os_memblock_get(&queue_hdl->epool); + if (!ev) + { + os_memblock_put(&queue_hdl->mpool, ptr); + return false; + } + tu_memclr(ev, sizeof(struct os_event)); + ev->ev_arg = ptr; + + os_eventq_put(&queue_hdl->evq, ev); + + return true; +} + +static inline void osal_queue_flush(osal_queue_t const queue_hdl) +{ + +} + +//--------------------------------------------------------------------+ +// Semaphore API +//--------------------------------------------------------------------+ +typedef struct os_sem osal_semaphore_def_t; +typedef struct os_sem* osal_semaphore_t; + +static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef) +{ + return (os_sem_init(semdef, 0) == OS_OK) ? (osal_semaphore_t) semdef : NULL; +} + +static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) +{ + (void) in_isr; + return os_sem_release(sem_hdl) == OS_OK; +} + +static inline void osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec, tusb_error_t *p_error) +{ + uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? OS_TIMEOUT_NEVER : os_time_ms_to_ticks32(msec); + (*p_error) = ( (os_sem_pend(sem_hdl, ticks) == OS_OK) ? TUSB_ERROR_NONE : TUSB_ERROR_OSAL_TIMEOUT ); +} + +static inline void osal_semaphore_reset_isr(osal_semaphore_t const sem_hdl) +{ +// xSemaphoreTakeFromISR(sem_hdl, NULL); +} + +#if 0 +//--------------------------------------------------------------------+ +// MUTEX API (priority inheritance) +//--------------------------------------------------------------------+ +typedef struct os_mutex osal_mutex_t; + +#define osal_mutex_create(x) xSemaphoreCreateMutex() + +static inline bool osal_mutex_release(osal_mutex_t mutex_hdl) +{ + return xSemaphoreGive(mutex_hdl); +} + +static inline void osal_mutex_wait(osal_mutex_t mutex_hdl, uint32_t msec, tusb_error_t *p_error) +{ + uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? portMAX_DELAY : pdMS_TO_TICKS(msec); + (*p_error) = (xSemaphoreTake(mutex_hdl, ticks) ? TUSB_ERROR_NONE : TUSB_ERROR_OSAL_TIMEOUT); +} +#endif + + +#ifdef __cplusplus + } +#endif + +#endif /* OSAL_MYNEWT_H_ */ diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h new file mode 100644 index 000000000..ff37113c6 --- /dev/null +++ b/src/osal/osal_none.h @@ -0,0 +1,231 @@ +/**************************************************************************/
+/*!
+ @file osal_none.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \ingroup group_osal
+ * \defgroup Group_OSNone None OS
+ * @{ */
+
+#ifndef _TUSB_OSAL_NONE_H_
+#define _TUSB_OSAL_NONE_H_
+
+#include "tusb_hal.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// TASK API
+// Virtually do nothing in osal none
+//--------------------------------------------------------------------+
+#define OSAL_TASK_DEF(_name, _str, _func, _prio, _stack_sz) osal_task_def_t _name;
+typedef uint8_t osal_task_def_t;
+
+static inline bool osal_task_create(osal_task_def_t* taskdef)
+{
+ (void) taskdef;
+ return true;
+}
+
+static inline void osal_task_delay(uint32_t msec)
+{
+ uint32_t start = tusb_hal_millis();
+ while ( ( tusb_hal_millis() - start ) < msec ) {}
+}
+
+//--------------------------------------------------------------------+
+// Binary Semaphore API
+//--------------------------------------------------------------------+
+typedef struct
+{
+ volatile uint16_t count;
+}osal_semaphore_def_t;
+
+typedef osal_semaphore_def_t* osal_semaphore_t;
+
+static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
+{
+ semdef->count = 0;
+ return semdef;
+}
+
+static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
+{
+ (void) in_isr;
+ sem_hdl->count++;
+ return true;
+}
+
+static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl)
+{
+ sem_hdl->count = 0;
+}
+
+// TODO blocking for now
+static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec)
+{
+ (void) msec;
+
+ while (sem_hdl->count == 0) { }
+ sem_hdl->count--;
+
+ return true;
+}
+
+//--------------------------------------------------------------------+
+// MUTEX API
+// Within tinyusb, mutex is never used in ISR context
+//--------------------------------------------------------------------+
+typedef osal_semaphore_def_t osal_mutex_def_t;
+typedef osal_semaphore_t osal_mutex_t;
+
+static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
+{
+ mdef->count = 1;
+ return mdef;
+}
+
+#define osal_mutex_unlock(_mutex_hdl) osal_semaphore_post(_mutex_hdl, false)
+#define osal_mutex_lock osal_semaphore_wait
+
+//--------------------------------------------------------------------+
+// QUEUE API
+//--------------------------------------------------------------------+
+#include "common/tusb_fifo.h"
+
+// extern to avoid including dcd.h and hcd.h
+#if TUSB_OPT_DEVICE_ENABLED
+extern void dcd_int_disable(uint8_t rhport);
+extern void dcd_int_enable(uint8_t rhport);
+#endif
+
+#if TUSB_OPT_HOST_ENABLED
+extern void hcd_int_disable(uint8_t rhport);
+extern void hcd_int_enable(uint8_t rhport);
+#endif
+
+typedef struct
+{
+ uint8_t role; // device or host
+ tu_fifo_t ff;
+}osal_queue_def_t;
+
+typedef osal_queue_def_t* osal_queue_t;
+
+// role device/host is used by OS NONE for mutex (disable usb isr) only
+#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \
+ uint8_t _name##_buf[_depth*sizeof(_type)]; \
+ osal_queue_def_t _name = { \
+ .role = _role, \
+ .ff = { \
+ .buffer = _name##_buf, \
+ .depth = _depth, \
+ .item_size = sizeof(_type), \
+ .overwritable = false, \
+ }\
+ }
+
+// lock queue by disable usb isr
+static inline void _osal_q_lock(osal_queue_t qhdl)
+{
+#if TUSB_OPT_DEVICE_ENABLED
+ if (qhdl->role == OPT_MODE_DEVICE) dcd_int_disable(TUD_OPT_RHPORT);
+#endif
+
+#if TUSB_OPT_HOST_ENABLED
+ if (qhdl->role == OPT_MODE_HOST) hcd_int_disable(TUH_OPT_RHPORT);
+#endif
+}
+
+// unlock queue
+static inline void _osal_q_unlock(osal_queue_t qhdl)
+{
+#if TUSB_OPT_DEVICE_ENABLED
+ if (qhdl->role == OPT_MODE_DEVICE) dcd_int_enable(TUD_OPT_RHPORT);
+#endif
+
+#if TUSB_OPT_HOST_ENABLED
+ if (qhdl->role == OPT_MODE_HOST) hcd_int_enable(TUH_OPT_RHPORT);
+#endif
+}
+
+static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
+{
+ tu_fifo_clear(&qdef->ff);
+ return (osal_queue_t) qdef;
+}
+
+static inline bool osal_queue_send(osal_queue_t const qhdl, void const * data, bool in_isr)
+{
+ if (!in_isr) {
+ _osal_q_lock(qhdl);
+ }
+
+ bool success = tu_fifo_write(&qhdl->ff, data);
+
+ if (!in_isr) {
+ _osal_q_unlock(qhdl);
+ }
+
+ return success;
+}
+
+static inline void osal_queue_reset(osal_queue_t const qhdl)
+{
+ // tusb_hal_int_disable_all();
+ tu_fifo_clear(&qhdl->ff);
+ // tusb_hal_int_enable_all();
+}
+
+// non blocking
+static inline bool osal_queue_receive(osal_queue_t const qhdl, void* data)
+{
+ _osal_q_lock(qhdl);
+ bool success = tu_fifo_read(&qhdl->ff, data);
+ _osal_q_unlock(qhdl);
+
+ return success;
+}
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_OSAL_NONE_H_ */
+
+/** @} */
diff --git a/src/portable/microchip/samd21/dcd_samd21.c b/src/portable/microchip/samd21/dcd_samd21.c new file mode 100644 index 000000000..af0721ec3 --- /dev/null +++ b/src/portable/microchip/samd21/dcd_samd21.c @@ -0,0 +1,348 @@ +/**************************************************************************/ +/*! + @file dcd_nrf5x.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, Scott Shawcroft for Adafruit Industries + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD21 + +#include "device/dcd.h" +#include "sam.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +static ATTR_ALIGNED(4) UsbDeviceDescBank sram_registers[8][2]; +static ATTR_ALIGNED(4) uint8_t _setup_packet[8]; + +// Setup the control endpoint 0. +static void bus_reset(void) { + // Max size of packets is 64 bytes. + UsbDeviceDescBank* bank_out = &sram_registers[0][TUSB_DIR_OUT]; + bank_out->PCKSIZE.bit.SIZE = 0x3; + UsbDeviceDescBank* bank_in = &sram_registers[0][TUSB_DIR_IN]; + bank_in->PCKSIZE.bit.SIZE = 0x3; + + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[0]; + ep->EPCFG.reg = USB_DEVICE_EPCFG_EPTYPE0(0x1) | USB_DEVICE_EPCFG_EPTYPE1(0x1); + ep->EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0 | USB_DEVICE_EPINTENSET_TRCPT1 | USB_DEVICE_EPINTENSET_RXSTP; + + // Prepare for setup packet + dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet)); +} + + +/*------------------------------------------------------------------*/ +/* Controller API + *------------------------------------------------------------------*/ +bool dcd_init (uint8_t rhport) +{ + (void) rhport; + + // Reset to get in a clean state. + USB->DEVICE.CTRLA.bit.SWRST = true; + while (USB->DEVICE.SYNCBUSY.bit.SWRST == 0) {} + while (USB->DEVICE.SYNCBUSY.bit.SWRST == 1) {} + + USB->DEVICE.PADCAL.bit.TRANSP = (*((uint32_t*) USB_FUSES_TRANSP_ADDR) & USB_FUSES_TRANSP_Msk) >> USB_FUSES_TRANSP_Pos; + USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos; + USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos; + + USB->DEVICE.QOSCTRL.bit.CQOS = USB_QOSCTRL_CQOS_HIGH_Val; + USB->DEVICE.QOSCTRL.bit.DQOS = USB_QOSCTRL_DQOS_HIGH_Val; + + // Configure registers + USB->DEVICE.DESCADD.reg = (uint32_t) &sram_registers; + USB->DEVICE.CTRLB.reg = USB_DEVICE_CTRLB_SPDCONF_FS; + USB->DEVICE.CTRLA.reg = USB_CTRLA_MODE_DEVICE | USB_CTRLA_ENABLE | USB_CTRLA_RUNSTDBY; + while (USB->DEVICE.SYNCBUSY.bit.ENABLE == 1) {} + + USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SOF | USB_DEVICE_INTENSET_EORST; + + return true; +} + +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); +} + +void dcd_set_address (uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + + // Wait for EP0 to finish before switching the address. + while (USB->DEVICE.DeviceEndpoint[0].EPSTATUS.bit.BK1RDY == 1) {} + USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; +} + +void dcd_set_config (uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + // Nothing to do +} + +/*------------------------------------------------------------------*/ +/* DCD Endpoint port + *------------------------------------------------------------------*/ + +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); + + UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; + uint32_t size_value = 0; + while (size_value < 7) { + if (1 << (size_value + 3) == desc_edpt->wMaxPacketSize.size) { + break; + } + size_value++; + } + + // unsupported endpoint size + if ( size_value == 7 && desc_edpt->wMaxPacketSize.size != 1023 ) return false; + + bank->PCKSIZE.bit.SIZE = size_value; + + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if ( dir == TUSB_DIR_OUT ) + { + ep->EPCFG.bit.EPTYPE0 = desc_edpt->bmAttributes.xfer + 1; + ep->EPINTENSET.bit.TRCPT0 = true; + }else + { + ep->EPCFG.bit.EPTYPE1 = desc_edpt->bmAttributes.xfer + 1; + ep->EPINTENSET.bit.TRCPT1 = true; + } + + 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); + + UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + // A setup token can occur immediately after an OUT STATUS packet so make sure we have a valid + // buffer for the control endpoint. + if (epnum == 0 && dir == 0 && buffer == NULL) { + buffer = _setup_packet; + } + + bank->ADDR.reg = (uint32_t) buffer; + if ( dir == TUSB_DIR_OUT ) + { + bank->PCKSIZE.bit.MULTI_PACKET_SIZE = total_bytes; + bank->PCKSIZE.bit.BYTE_COUNT = 0; + ep->EPSTATUSCLR.reg |= USB_DEVICE_EPSTATUSCLR_BK0RDY; + ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL0; + } else + { + bank->PCKSIZE.bit.MULTI_PACKET_SIZE = 0; + bank->PCKSIZE.bit.BYTE_COUNT = total_bytes; + // bank->PCKSIZE.bit.AUTO_ZLP = 1; + ep->EPSTATUSSET.reg |= USB_DEVICE_EPSTATUSSET_BK1RDY; + ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL1; + } + + return true; +} + +bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // control is never got halted + if ( ep_addr == 0 ) { + return false; + } + + uint8_t const epnum = tu_edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + return (tu_edpt_dir(ep_addr) == TUSB_DIR_IN ) ? ep->EPINTFLAG.bit.STALL1 : ep->EPINTFLAG.bit.STALL0; +} + +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1; + } else { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ0; + + // for control, stall both IN & OUT + if (ep_addr == 0) { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1; + } + } +} + +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ1; + } else { + ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ0; + } +} + +bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // USBD shouldn't check control endpoint state + if ( 0 == ep_addr ) return false; + + uint8_t const epnum = tu_edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + return ep->EPINTFLAG.bit.TRCPT1 == 0 && ep->EPSTATUS.bit.BK1RDY == 1; + } + return ep->EPINTFLAG.bit.TRCPT0 == 0 && ep->EPSTATUS.bit.BK0RDY == 1; +} + +/*------------------------------------------------------------------*/ + +static bool maybe_handle_setup_packet(void) { + if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP) + { + USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; + + // This copies the data elsewhere so we can reuse the buffer. + dcd_event_setup_received(0, (uint8_t*) sram_registers[0][0].ADDR.reg, true); + return true; + } + return false; +} + +void maybe_transfer_complete(void) { + uint32_t epints = USB->DEVICE.EPINTSMRY.reg; + for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) { + if ((epints & (1 << epnum)) == 0) { + continue; + } + + if (maybe_handle_setup_packet()) { + continue; + } + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + uint32_t epintflag = ep->EPINTFLAG.reg; + + uint16_t total_transfer_size; + + // Handle IN completions + if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT1) != 0) { + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; + + UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_IN]; + total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + + uint8_t ep_addr = epnum | TUSB_DIR_IN_MASK; + dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); + } + + // Handle OUT completions + if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT0) != 0) { + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0; + + UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_OUT]; + total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + + uint8_t ep_addr = epnum; + dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); + } + + // just finished status stage (total size = 0), prepare for next setup packet + if (epnum == 0 && total_transfer_size == 0) { + dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet)); + } + } +} + +void USB_Handler(void) { + uint32_t int_status = USB->DEVICE.INTFLAG.reg; + + /*------------- Interrupt Processing -------------*/ + if ( int_status & USB_DEVICE_INTFLAG_EORST ) + { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_EORST; + bus_reset(); + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + if ( int_status & USB_DEVICE_INTFLAG_SOF ) + { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_SOF; + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); + } + + // Setup packet received. + maybe_handle_setup_packet(); + + // Handle complete transfer + maybe_transfer_complete(); +} + +#endif diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd51/dcd_samd51.c new file mode 100644 index 000000000..ce66b8245 --- /dev/null +++ b/src/portable/microchip/samd51/dcd_samd51.c @@ -0,0 +1,368 @@ +/**************************************************************************/ +/*! + @file dcd_nrf5x.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, Scott Shawcroft for Adafruit Industries + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD51 + +#include "device/dcd.h" +#include "sam.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +static UsbDeviceDescBank sram_registers[8][2]; +static ATTR_ALIGNED(4) uint8_t _setup_packet[8]; + +// Setup the control endpoint 0. +static void bus_reset(void) { + // Max size of packets is 64 bytes. + UsbDeviceDescBank* bank_out = &sram_registers[0][TUSB_DIR_OUT]; + bank_out->PCKSIZE.bit.SIZE = 0x3; + UsbDeviceDescBank* bank_in = &sram_registers[0][TUSB_DIR_IN]; + bank_in->PCKSIZE.bit.SIZE = 0x3; + + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[0]; + ep->EPCFG.reg = USB_DEVICE_EPCFG_EPTYPE0(0x1) | USB_DEVICE_EPCFG_EPTYPE1(0x1); + ep->EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0 | USB_DEVICE_EPINTENSET_TRCPT1 | USB_DEVICE_EPINTENSET_RXSTP; + + // Prepare for setup packet + dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet)); +} + + +/*------------------------------------------------------------------*/ +/* Controller API + *------------------------------------------------------------------*/ +bool dcd_init (uint8_t rhport) +{ + (void) rhport; + + // Reset to get in a clean state. + USB->DEVICE.CTRLA.bit.SWRST = true; + while (USB->DEVICE.SYNCBUSY.bit.SWRST == 0) {} + while (USB->DEVICE.SYNCBUSY.bit.SWRST == 1) {} + + USB->DEVICE.PADCAL.bit.TRANSP = (*((uint32_t*) USB_FUSES_TRANSP_ADDR) & USB_FUSES_TRANSP_Msk) >> USB_FUSES_TRANSP_Pos; + USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos; + USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos; + + USB->DEVICE.QOSCTRL.bit.CQOS = 3; + USB->DEVICE.QOSCTRL.bit.DQOS = 3; + + // Configure registers + USB->DEVICE.DESCADD.reg = (uint32_t) &sram_registers; + USB->DEVICE.CTRLB.reg = USB_DEVICE_CTRLB_SPDCONF_FS; + USB->DEVICE.CTRLA.reg = USB_CTRLA_MODE_DEVICE | USB_CTRLA_ENABLE | USB_CTRLA_RUNSTDBY; + while (USB->DEVICE.SYNCBUSY.bit.ENABLE == 1) {} + USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SOF | USB_DEVICE_INTENSET_EORST; + + return true; +} + +void dcd_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USB_0_IRQn); + NVIC_EnableIRQ(USB_1_IRQn); + NVIC_EnableIRQ(USB_2_IRQn); + NVIC_EnableIRQ(USB_3_IRQn); +} + +void dcd_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USB_3_IRQn); + NVIC_DisableIRQ(USB_2_IRQn); + NVIC_DisableIRQ(USB_1_IRQn); + NVIC_DisableIRQ(USB_0_IRQn); +} + +void dcd_set_address (uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + + // Wait for EP0 to finish before switching the address. + while (USB->DEVICE.DeviceEndpoint[0].EPSTATUS.bit.BK1RDY == 1) {} + USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; +} + +void dcd_set_config (uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + // Nothing to do +} + +/*------------------------------------------------------------------*/ +/* DCD Endpoint port + *------------------------------------------------------------------*/ + +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); + + UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; + uint32_t size_value = 0; + while (size_value < 7) { + if (1 << (size_value + 3) == desc_edpt->wMaxPacketSize.size) { + break; + } + size_value++; + } + + // unsupported endpoint size + if ( size_value == 7 && desc_edpt->wMaxPacketSize.size != 1023 ) return false; + + bank->PCKSIZE.bit.SIZE = size_value; + + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if ( dir == TUSB_DIR_OUT ) + { + ep->EPCFG.bit.EPTYPE0 = desc_edpt->bmAttributes.xfer + 1; + ep->EPINTENSET.bit.TRCPT0 = true; + }else + { + ep->EPCFG.bit.EPTYPE1 = desc_edpt->bmAttributes.xfer + 1; + ep->EPINTENSET.bit.TRCPT1 = true; + } + + 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); + + UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + // A setup token can occur immediately after an OUT STATUS packet so make sure we have a valid + // buffer for the control endpoint. + if (epnum == 0 && dir == 0 && buffer == NULL) { + buffer = _setup_packet; + } + + bank->ADDR.reg = (uint32_t) buffer; + if ( dir == TUSB_DIR_OUT ) + { + bank->PCKSIZE.bit.MULTI_PACKET_SIZE = total_bytes; + bank->PCKSIZE.bit.BYTE_COUNT = 0; + ep->EPSTATUSCLR.reg |= USB_DEVICE_EPSTATUSCLR_BK0RDY; + ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL0; + } else + { + bank->PCKSIZE.bit.MULTI_PACKET_SIZE = 0; + bank->PCKSIZE.bit.BYTE_COUNT = total_bytes; + ep->EPSTATUSSET.reg |= USB_DEVICE_EPSTATUSSET_BK1RDY; + ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL1; + } + + return true; +} + +bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // control is never got halted + if ( ep_addr == 0 ) { + return false; + } + + uint8_t const epnum = tu_edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + return (tu_edpt_dir(ep_addr) == TUSB_DIR_IN ) ? ep->EPINTFLAG.bit.STALL1 : ep->EPINTFLAG.bit.STALL0; +} + +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1; + } else { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ0; + + // for control, stall both IN & OUT + if (ep_addr == 0) { + ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1; + } + } +} + +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ1; + } else { + ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ0; + } +} + +bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // USBD shouldn't check control endpoint state + if ( 0 == ep_addr ) return false; + + uint8_t const epnum = tu_edpt_number(ep_addr); + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + return ep->EPINTFLAG.bit.TRCPT1 == 0 && ep->EPSTATUS.bit.BK1RDY == 1; + } + return ep->EPINTFLAG.bit.TRCPT0 == 0 && ep->EPSTATUS.bit.BK0RDY == 1; +} + +/*------------------------------------------------------------------*/ + +static bool maybe_handle_setup_packet(void) { + if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP) + { + USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; + + // This copies the data elsewhere so we can reuse the buffer. + dcd_event_setup_received(0, (uint8_t*) sram_registers[0][0].ADDR.reg, true); + return true; + } + return false; +} +/* + *------------------------------------------------------------------*/ +/* USB_EORSM_DNRSM, USB_EORST_RST, USB_LPMSUSP_DDISC, USB_LPM_DCONN, +USB_MSOF, USB_RAMACER, USB_RXSTP_TXSTP_0, USB_RXSTP_TXSTP_1, +USB_RXSTP_TXSTP_2, USB_RXSTP_TXSTP_3, USB_RXSTP_TXSTP_4, +USB_RXSTP_TXSTP_5, USB_RXSTP_TXSTP_6, USB_RXSTP_TXSTP_7, +USB_STALL0_STALL_0, USB_STALL0_STALL_1, USB_STALL0_STALL_2, +USB_STALL0_STALL_3, USB_STALL0_STALL_4, USB_STALL0_STALL_5, +USB_STALL0_STALL_6, USB_STALL0_STALL_7, USB_STALL1_0, USB_STALL1_1, +USB_STALL1_2, USB_STALL1_3, USB_STALL1_4, USB_STALL1_5, USB_STALL1_6, +USB_STALL1_7, USB_SUSPEND, USB_TRFAIL0_TRFAIL_0, USB_TRFAIL0_TRFAIL_1, +USB_TRFAIL0_TRFAIL_2, USB_TRFAIL0_TRFAIL_3, USB_TRFAIL0_TRFAIL_4, +USB_TRFAIL0_TRFAIL_5, USB_TRFAIL0_TRFAIL_6, USB_TRFAIL0_TRFAIL_7, +USB_TRFAIL1_PERR_0, USB_TRFAIL1_PERR_1, USB_TRFAIL1_PERR_2, +USB_TRFAIL1_PERR_3, USB_TRFAIL1_PERR_4, USB_TRFAIL1_PERR_5, +USB_TRFAIL1_PERR_6, USB_TRFAIL1_PERR_7, USB_UPRSM, USB_WAKEUP */ +void USB_0_Handler(void) { + uint32_t int_status = USB->DEVICE.INTFLAG.reg; + + /*------------- Interrupt Processing -------------*/ + if ( int_status & USB_DEVICE_INTFLAG_EORST ) + { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_EORST; + bus_reset(); + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + // Setup packet received. + maybe_handle_setup_packet(); +} +/* USB_SOF_HSOF */ +void USB_1_Handler(void) { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_SOF; + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); +} + +void transfer_complete(uint8_t direction) { + uint32_t epints = USB->DEVICE.EPINTSMRY.reg; + for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) { + if ((epints & (1 << epnum)) == 0) { + continue; + } + + if (direction == TUSB_DIR_OUT && maybe_handle_setup_packet()) { + continue; + } + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + + UsbDeviceDescBank* bank = &sram_registers[epnum][direction]; + uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + + uint8_t ep_addr = epnum; + if (direction == TUSB_DIR_IN) { + ep_addr |= TUSB_DIR_IN_MASK; + } + dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); + + // just finished status stage (total size = 0), prepare for next setup packet + if (epnum == 0 && total_transfer_size == 0) { + dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet)); + } + + if (direction == TUSB_DIR_IN) { + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; + } else { + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0; + } + } +} + +// Bank zero is for OUT and SETUP transactions. +/* USB_TRCPT0_0, USB_TRCPT0_1, USB_TRCPT0_2, +USB_TRCPT0_3, USB_TRCPT0_4, USB_TRCPT0_5, +USB_TRCPT0_6, USB_TRCPT0_7 */ +void USB_2_Handler(void) { + transfer_complete(TUSB_DIR_OUT); +} + +// Bank one is used for IN transactions. +/* USB_TRCPT1_0, USB_TRCPT1_1, USB_TRCPT1_2, +USB_TRCPT1_3, USB_TRCPT1_4, USB_TRCPT1_5, +USB_TRCPT1_6, USB_TRCPT1_7 */ +void USB_3_Handler(void) { + transfer_complete(TUSB_DIR_IN); +} + +#endif diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c new file mode 100644 index 000000000..ad5090eb0 --- /dev/null +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -0,0 +1,533 @@ +/**************************************************************************/ +/*! + @file dcd_nrf5x.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_NRF5X + +#include "nrf.h" +#include "nrf_power.h" +#include "nrf_usbd.h" +#include "nrf_clock.h" + +#include "device/dcd.h" + +// TODO remove later +#include "device/usbd.h" +#include "device/usbd_pvt.h" // to use defer function helper + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +enum +{ + // Max allowed by USB specs + MAX_PACKET_SIZE = 64, + + // Mask of all END event (IN & OUT) for all endpoints. ENDEPIN0-7, ENDEPOUT0-7, ENDISOIN, ENDISOOUT + EDPT_END_ALL_MASK = (0xff << USBD_INTEN_ENDEPIN0_Pos) | (0xff << USBD_INTEN_ENDEPOUT0_Pos) | + USBD_INTENCLR_ENDISOIN_Msk | USBD_INTEN_ENDISOOUT_Msk +}; + +// Transfer descriptor +typedef struct +{ + uint8_t* buffer; + uint16_t total_len; + volatile uint16_t actual_len; + uint8_t mps; // max packet size + + // nrf52840 will auto ACK OUT packet after DMA is done + // indicate packet is already ACK + volatile bool data_received; + +} xfer_td_t; + +// Data for managing dcd +static struct +{ + // All 8 endpoints including control IN & OUT (offset 1) + xfer_td_t xfer[8][2]; + + // Only one DMA can run at a time + volatile bool dma_running; +}_dcd; + +/*------------------------------------------------------------------*/ +/* Control / Bulk / Interrupt (CBI) Transfer + *------------------------------------------------------------------*/ + +// helper to start DMA +static void edpt_dma_start(volatile uint32_t* reg_startep) +{ + // Only one dma can be active + if ( _dcd.dma_running ) + { + if (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) + { + // If called within ISR, use usbd task to defer later + usbd_defer_func( (osal_task_func_t) edpt_dma_start, (void*) reg_startep, true ); + return; + } + else + { + // Otherwise simply block wait + while ( _dcd.dma_running ) { } + } + } + + _dcd.dma_running = true; + + (*reg_startep) = 1; + __ISB(); __DSB(); +} + +// DMA is complete +static void edpt_dma_end(void) +{ + TU_ASSERT(_dcd.dma_running, ); + _dcd.dma_running = false; +} + +// helper getting td +static inline xfer_td_t* get_td(uint8_t epnum, uint8_t dir) +{ + return &_dcd.xfer[epnum][dir]; +} + +/*------------- CBI OUT Transfer -------------*/ + +// Prepare for a CBI transaction OUT, call at the start +// Allow ACK incoming data +static void xact_out_prepare(uint8_t epnum) +{ + if ( epnum == 0 ) + { + NRF_USBD->TASKS_EP0RCVOUT = 1; + } + else + { + // Write zero value to SIZE register will allow hw to ACK (accept data) + // If it is not already done by DMA + NRF_USBD->SIZE.EPOUT[epnum] = 0; + } + + __ISB(); __DSB(); +} + +// Start DMA to move data from Endpoint -> RAM +static void xact_out_dma(uint8_t epnum) +{ + xfer_td_t* xfer = get_td(epnum, TUSB_DIR_OUT); + + uint8_t const xact_len = NRF_USBD->SIZE.EPOUT[epnum]; + + // Trigger DMA move data from Endpoint -> SRAM + NRF_USBD->EPOUT[epnum].PTR = (uint32_t) xfer->buffer; + NRF_USBD->EPOUT[epnum].MAXCNT = xact_len; + + edpt_dma_start(&NRF_USBD->TASKS_STARTEPOUT[epnum]); + + xfer->buffer += xact_len; + xfer->actual_len += xact_len; +} + +/*------------- CBI IN Transfer -------------*/ + +// Prepare for a CBI transaction IN, call at the start +// it start DMA to transfer data from RAM -> Endpoint +static void xact_in_prepare(uint8_t epnum) +{ + xfer_td_t* xfer = get_td(epnum, TUSB_DIR_IN); + + // Each transaction is up to Max Packet Size + uint8_t const xact_len = tu_min16(xfer->total_len - xfer->actual_len, xfer->mps); + + 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]); +} + +//--------------------------------------------------------------------+ +// Tinyusb DCD API +//--------------------------------------------------------------------+ +bool dcd_init (uint8_t rhport) +{ + (void) rhport; + return true; +} + +void dcd_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USBD_IRQn); +} + +void dcd_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USBD_IRQn); +} + +void dcd_set_address (uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + (void) dev_addr; + // Set Address is automatically update by hw controller +} + +void dcd_set_config (uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + // Nothing to do +} + +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); + + _dcd.xfer[epnum][dir].mps = desc_edpt->wMaxPacketSize.size; + + if ( dir == TUSB_DIR_OUT ) + { + NRF_USBD->INTENSET = BIT_(USBD_INTEN_ENDEPOUT0_Pos + epnum); + NRF_USBD->EPOUTEN |= BIT_(epnum); + }else + { + NRF_USBD->INTENSET = BIT_(USBD_INTEN_ENDEPIN0_Pos + epnum); + NRF_USBD->EPINEN |= BIT_(epnum); + } + __ISB(); __DSB(); + + 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_td_t* xfer = get_td(epnum, dir); + + xfer->buffer = buffer; + xfer->total_len = total_bytes; + xfer->actual_len = 0; + + // Control endpoint with zero-length packet --> status stage + if ( epnum == 0 && total_bytes == 0 ) + { + // Status Phase also require Easy DMA has to be free as well !!!! + edpt_dma_start(&NRF_USBD->TASKS_EP0STATUS); + edpt_dma_end(); + + // 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, false); + } + else if ( dir == TUSB_DIR_OUT ) + { + if ( xfer->data_received ) + { + // nrf52840 auto ACK OUT packet after DMA is done + // Data already received previously --> trigger DMA to copy to SRAM + xact_out_dma(epnum); + } + else + { + xact_out_prepare(epnum); + } + } + else + { + xact_in_prepare(epnum); + } + + return true; +} + +bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // control is never got halted + if ( ep_addr == 0 ) return false; + + uint8_t const epnum = tu_edpt_number(ep_addr); + return (tu_edpt_dir(ep_addr) == TUSB_DIR_IN ) ? NRF_USBD->HALTED.EPIN[epnum] : NRF_USBD->HALTED.EPOUT[epnum]; +} + +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + if ( tu_edpt_number(ep_addr) == 0 ) + { + NRF_USBD->TASKS_EP0STALL = 1; + }else + { + NRF_USBD->EPSTALL = (USBD_EPSTALL_STALL_Stall << USBD_EPSTALL_STALL_Pos) | ep_addr; + } + + __ISB(); __DSB(); +} + +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + if ( tu_edpt_number(ep_addr) ) + { + NRF_USBD->EPSTALL = (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | ep_addr; + __ISB(); __DSB(); + } +} + +bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + // USBD shouldn't check control endpoint state + if ( 0 == tu_edpt_number(ep_addr) ) return false; + + 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); + + return xfer->actual_len < xfer->total_len; +} + +/*------------------------------------------------------------------*/ +/* Interrupt Handler + *------------------------------------------------------------------*/ +void bus_reset(void) +{ + for(int i=0; i<8; i++) + { + NRF_USBD->TASKS_STARTEPIN[i] = 0; + NRF_USBD->TASKS_STARTEPOUT[i] = 0; + } + + NRF_USBD->TASKS_STARTISOIN = 0; + NRF_USBD->TASKS_STARTISOOUT = 0; + + tu_varclr(&_dcd); + _dcd.xfer[0][TUSB_DIR_IN].mps = MAX_PACKET_SIZE; + _dcd.xfer[0][TUSB_DIR_OUT].mps = MAX_PACKET_SIZE; +} + +void USBD_IRQHandler(void) +{ + uint32_t const inten = NRF_USBD->INTEN; + uint32_t int_status = 0; + + volatile uint32_t* regevt = &NRF_USBD->EVENTS_USBRESET; + + for(uint8_t i=0; i<USBD_INTEN_EPDATA_Pos+1; i++) + { + if ( BIT_TEST_(inten, i) && regevt[i] ) + { + int_status |= BIT_(i); + + // event clear + regevt[i] = 0; + __ISB(); __DSB(); + } + } + + /*------------- Interrupt Processing -------------*/ + if ( int_status & USBD_INTEN_USBRESET_Msk ) + { + bus_reset(); + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + if ( int_status & EDPT_END_ALL_MASK ) + { + // DMA complete move data from SRAM -> Endpoint + edpt_dma_end(); + } + + // Setup tokens are specific to the Control endpoint. + if ( int_status & USBD_INTEN_EP0SETUP_Msk ) + { + uint8_t const setup[8] = { + NRF_USBD->BMREQUESTTYPE , NRF_USBD->BREQUEST, NRF_USBD->WVALUEL , NRF_USBD->WVALUEH, + NRF_USBD->WINDEXL , NRF_USBD->WINDEXH , NRF_USBD->WLENGTHL, NRF_USBD->WLENGTHH + }; + + // nrf5x hw auto handle set address, there is no need to inform usb stack + tusb_control_request_t const * request = (tusb_control_request_t const *) setup; + + if ( !(TUSB_REQ_RCPT_DEVICE == request->bmRequestType_bit.recipient && + TUSB_REQ_TYPE_STANDARD == request->bmRequestType_bit.type && + TUSB_REQ_SET_ADDRESS == request->bRequest) ) + { + dcd_event_setup_received(0, setup, true); + } + } + + //--------------------------------------------------------------------+ + /* Control/Bulk/Interrupt (CBI) Transfer + * + * Data flow is: + * (bus) (dma) + * Host <-------> Endpoint <-------> RAM + * + * For CBI OUT: + * - Host -> Endpoint + * EPDATA (or EP0DATADONE) interrupted, check EPDATASTATUS.EPOUT[i] + * to start DMA. This step can occur automatically (without sw), + * which means data may or may not ready (data_received flag). + * - Endpoint -> RAM + * ENDEPOUT[i] interrupted, transaction complete, sw prepare next transaction + * + * For CBI IN: + * - RAM -> Endpoint + * ENDEPIN[i] interrupted indicate DMA is complete. HW will start + * to move daat to host + * - Endpoint -> Host + * EPDATA (or EP0DATADONE) interrupted, check EPDATASTATUS.EPIN[i]. + * Transaction is complete, sw prepare next transaction + * + * Note: in both Control In and Out of Data stage from Host <-> Endpoint + * EP0DATADONE will be set as interrupt source + */ + //--------------------------------------------------------------------+ + + /* CBI OUT: Endpoint -> SRAM (aka transaction complete) + * Note: Since nRF controller auto ACK next packet without SW awareness + * We must handle this stage before Host -> Endpoint just in case + * 2 event happens at once + */ + for(uint8_t epnum=0; epnum<8; epnum++) + { + if ( BIT_TEST_(int_status, USBD_INTEN_ENDEPOUT0_Pos+epnum)) + { + xfer_td_t* xfer = get_td(epnum, TUSB_DIR_OUT); + uint8_t const xact_len = NRF_USBD->EPOUT[epnum].AMOUNT; + + // Data in endpoint has been consumed + xfer->data_received = false; + + // Transfer complete if transaction len < Max Packet Size or total len is transferred + if ( (xact_len == xfer->mps) && (xfer->actual_len < xfer->total_len) ) + { + // Prepare for next transaction + xact_out_prepare(epnum); + }else + { + xfer->total_len = xfer->actual_len; + + // BULK/INT OUT complete + dcd_event_xfer_complete(0, epnum, xfer->actual_len, XFER_RESULT_SUCCESS, true); + } + } + + // Ended event for CBI IN : nothing to do + } + + // Endpoint <-> Host + if ( int_status & (USBD_INTEN_EPDATA_Msk | USBD_INTEN_EP0DATADONE_Msk) ) + { + uint32_t data_status = NRF_USBD->EPDATASTATUS; + nrf_usbd_epdatastatus_clear(data_status); + + // EP0DATADONE is set with either Control Out on IN Data + // Since EPDATASTATUS cannot be used to determine whether it is control OUT or IN. + // We will use BMREQUESTTYPE in setup packet to determine the direction + bool const is_control_in = (int_status & USBD_INTEN_EP0DATADONE_Msk) && (NRF_USBD->BMREQUESTTYPE & TUSB_DIR_IN_MASK); + bool const is_control_out = (int_status & USBD_INTEN_EP0DATADONE_Msk) && !(NRF_USBD->BMREQUESTTYPE & TUSB_DIR_IN_MASK); + + // CBI In: Endpoint -> Host (transaction complete) + for(uint8_t epnum=0; epnum<8; epnum++) + { + if ( BIT_TEST_(data_status, epnum ) || ( epnum == 0 && is_control_in) ) + { + xfer_td_t* xfer = get_td(epnum, TUSB_DIR_IN); + + xfer->actual_len += NRF_USBD->EPIN[epnum].MAXCNT; + + if ( xfer->actual_len < xfer->total_len ) + { + // prepare next transaction + xact_in_prepare(epnum); + } else + { + // Bulk/Int IN complete + dcd_event_xfer_complete(0, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, XFER_RESULT_SUCCESS, true); + } + } + } + + // CBI OUT: Host -> Endpoint + for(uint8_t epnum=0; epnum<8; epnum++) + { + if ( BIT_TEST_(data_status, 16+epnum ) || ( epnum == 0 && is_control_out) ) + { + xfer_td_t* xfer = get_td(epnum, TUSB_DIR_OUT); + + if (xfer->actual_len < xfer->total_len) + { + xact_out_dma(epnum); + }else + { + // Data overflow !!! Nah, nrf52840 will auto ACK OUT packet after DMA is done + // Mark this endpoint with data received + xfer->data_received = true; + } + } + } + } + + // SOF interrupt + if ( int_status & USBD_INTEN_SOF_Msk ) + { + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); + } +} + +#endif diff --git a/src/portable/nordic/nrf5x/hal_nrf5x.c b/src/portable/nordic/nrf5x/hal_nrf5x.c new file mode 100644 index 000000000..f0a0b9632 --- /dev/null +++ b/src/portable/nordic/nrf5x/hal_nrf5x.c @@ -0,0 +1,279 @@ +/**************************************************************************/ +/*! + @file hal_nrf5x.c + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_NRF5X + +#include "nrf.h" +#include "nrf_gpio.h" +#include "nrf_clock.h" +#include "nrf_usbd.h" +#include "nrf_drv_usbd_errata.h" + +#ifdef SOFTDEVICE_PRESENT +#include "nrf_sdm.h" +#include "nrf_soc.h" + +// TODO fully move to nrfx +enum { + NRFX_POWER_USB_EVT_DETECTED, /**< USB power detected on the connector (plugged in). */ + NRFX_POWER_USB_EVT_REMOVED, /**< USB power removed from the connector. */ + NRFX_POWER_USB_EVT_READY /**< USB power regulator ready. */ +}; +#else +#include "nrfx_power.h" +#endif + +#include "tusb_hal.h" +#include "device/dcd.h" + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +#define USB_NVIC_PRIO 7 + +void tusb_hal_nrf_power_event(uint32_t event); + +/*------------------------------------------------------------------*/ +/* HFCLK helper + *------------------------------------------------------------------*/ + +#ifdef SOFTDEVICE_PRESENT +// check if SD is present and enabled +static bool is_sd_enabled(void) +{ + uint8_t sd_en = false; + (void) sd_softdevice_is_enabled(&sd_en); + return sd_en; +} +#endif + +static bool hfclk_running(void) +{ +#ifdef SOFTDEVICE_PRESENT + if ( is_sd_enabled() ) + { + uint32_t is_running; + (void) sd_clock_hfclk_is_running(&is_running); + return (is_running ? true : false); + } +#endif + + return nrf_clock_hf_is_running(NRF_CLOCK_HFCLK_HIGH_ACCURACY); +} + +static void hfclk_enable(void) +{ + // already running, nothing to do + if ( hfclk_running() ) return; + +#ifdef SOFTDEVICE_PRESENT + if ( is_sd_enabled() ) + { + (void)sd_clock_hfclk_request(); + return; + } +#endif + + nrf_clock_event_clear(NRF_CLOCK_EVENT_HFCLKSTARTED); + nrf_clock_task_trigger(NRF_CLOCK_TASK_HFCLKSTART); +} + +static void hfclk_disable(void) +{ +#ifdef SOFTDEVICE_PRESENT + if ( is_sd_enabled() ) + { + (void)sd_clock_hfclk_release(); + return; + } +#endif + + nrf_clock_task_trigger(NRF_CLOCK_TASK_HFCLKSTOP); +} + +/*------------------------------------------------------------------*/ +/* Controller Start up Sequence (USBD 51.4 specs) + *------------------------------------------------------------------*/ +// tusb_hal_nrf_power_event must be called by SOC event handler +void tusb_hal_nrf_power_event (uint32_t event) +{ + switch ( event ) + { + case NRFX_POWER_USB_EVT_DETECTED: + if ( !NRF_USBD->ENABLE ) + { + /* Prepare for READY event receiving */ + nrf_usbd_eventcause_clear(NRF_USBD_EVENTCAUSE_READY_MASK); + + /* Enable the peripheral */ + // ERRATA 171, 187, 166 + + if ( nrf_drv_usbd_errata_187() ) + { + // CRITICAL_REGION_ENTER(); + if ( *((volatile uint32_t *) (0x4006EC00)) == 0x00000000 ) + { + *((volatile uint32_t *) (0x4006EC00)) = 0x00009375; + *((volatile uint32_t *) (0x4006ED14)) = 0x00000003; + *((volatile uint32_t *) (0x4006EC00)) = 0x00009375; + } + else + { + *((volatile uint32_t *) (0x4006ED14)) = 0x00000003; + } + // CRITICAL_REGION_EXIT(); + } + + if ( nrf_drv_usbd_errata_171() ) + { + // CRITICAL_REGION_ENTER(); + if ( *((volatile uint32_t *) (0x4006EC00)) == 0x00000000 ) + { + *((volatile uint32_t *) (0x4006EC00)) = 0x00009375; + *((volatile uint32_t *) (0x4006EC14)) = 0x000000C0; + *((volatile uint32_t *) (0x4006EC00)) = 0x00009375; + } + else + { + *((volatile uint32_t *) (0x4006EC14)) = 0x000000C0; + } + // CRITICAL_REGION_EXIT(); + } + + nrf_usbd_enable(); + + // Enable HFCLK + hfclk_enable(); + } + break; + + case NRFX_POWER_USB_EVT_READY: + /* Waiting for USBD peripheral enabled */ + while ( !(USBD_EVENTCAUSE_READY_Msk & NRF_USBD->EVENTCAUSE) ) { } + + nrf_usbd_eventcause_clear(USBD_EVENTCAUSE_READY_Msk); + nrf_usbd_event_clear(USBD_EVENTCAUSE_READY_Msk); + + if ( nrf_drv_usbd_errata_171() ) + { + // CRITICAL_REGION_ENTER(); + if ( *((volatile uint32_t *) (0x4006EC00)) == 0x00000000 ) + { + *((volatile uint32_t *) (0x4006EC00)) = 0x00009375; + *((volatile uint32_t *) (0x4006EC14)) = 0x00000000; + *((volatile uint32_t *) (0x4006EC00)) = 0x00009375; + } + else + { + *((volatile uint32_t *) (0x4006EC14)) = 0x00000000; + } + + // CRITICAL_REGION_EXIT(); + } + + if ( nrf_drv_usbd_errata_187() ) + { + // CRITICAL_REGION_ENTER(); + if ( *((volatile uint32_t *) (0x4006EC00)) == 0x00000000 ) + { + *((volatile uint32_t *) (0x4006EC00)) = 0x00009375; + *((volatile uint32_t *) (0x4006ED14)) = 0x00000000; + *((volatile uint32_t *) (0x4006EC00)) = 0x00009375; + } + else + { + *((volatile uint32_t *) (0x4006ED14)) = 0x00000000; + } + // CRITICAL_REGION_EXIT(); + } + + if ( nrf_drv_usbd_errata_166() ) + { + *((volatile uint32_t *) (NRF_USBD_BASE + 0x800)) = 0x7E3; + *((volatile uint32_t *) (NRF_USBD_BASE + 0x804)) = 0x40; + + __ISB(); + __DSB(); + } + + nrf_usbd_isosplit_set(USBD_ISOSPLIT_SPLIT_HalfIN); + + // Enable interrupt. SOF is used as CDC auto flush + NRF_USBD->INTENSET = USBD_INTEN_USBRESET_Msk | USBD_INTEN_USBEVENT_Msk | USBD_INTEN_EPDATA_Msk | + USBD_INTEN_EP0SETUP_Msk | USBD_INTEN_EP0DATADONE_Msk | USBD_INTEN_ENDEPIN0_Msk | USBD_INTEN_ENDEPOUT0_Msk; + + // Enable interrupt, Priorities 0,1,4,5 (nRF52) are reserved for SoftDevice + NVIC_SetPriority(USBD_IRQn, USB_NVIC_PRIO); + NVIC_ClearPendingIRQ(USBD_IRQn); + NVIC_EnableIRQ(USBD_IRQn); + + // Wait for HFCLK + while ( !hfclk_running() ) { } + + // Enable pull up + nrf_usbd_pullup_enable(); + break; + + case NRFX_POWER_USB_EVT_REMOVED: + if ( NRF_USBD->ENABLE ) + { + // Abort all transfers + + // Disable pull up + nrf_usbd_pullup_disable(); + + // Disable Interrupt + NVIC_DisableIRQ(USBD_IRQn); + + // disable all interrupt + NRF_USBD->INTENCLR = NRF_USBD->INTEN; + + nrf_usbd_disable(); + hfclk_disable(); + + dcd_event_bus_signal(0, DCD_EVENT_UNPLUGGED, true); + } + break; + + default: break; + } +} + +#endif diff --git a/src/portable/nordic/nrf5x/nrf_drv_usbd_errata.h b/src/portable/nordic/nrf5x/nrf_drv_usbd_errata.h new file mode 100644 index 000000000..4a76e7eaa --- /dev/null +++ b/src/portable/nordic/nrf5x/nrf_drv_usbd_errata.h @@ -0,0 +1,210 @@ +/** + * Copyright (c) 2017 - 2018, Nordic Semiconductor ASA + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic + * Semiconductor ASA integrated circuit in a product or a software update for + * such product, must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef NRF_DRV_USBD_ERRATA_H__ +#define NRF_DRV_USBD_ERRATA_H__ + +#include <stdbool.h> +/** + * @defgroup nrf_drv_usbd_errata Functions to check if selected PAN is present in current chip + * @{ + * @ingroup nrf_drv_usbd + * + * Functions here are checking the presence of an error in current chip. + * The checking is done at runtime based on the microcontroller version. + * This file is subject to removal when nRF51840 prototype support is removed. + */ + +#ifndef NRF_DRV_USBD_ERRATA_ENABLE +/** + * @brief The constant that informs if errata should be enabled at all + * + * If this constant is set to 0, all the Errata bug fixes will be automatically disabled. + */ +#define NRF_DRV_USBD_ERRATA_ENABLE 1 +#endif + +/** + * @brief Internal auxiliary function to check if the program is running on NRF52840 chip + * @retval true It is NRF52480 chip + * @retval false It is other chip + */ +static inline bool nrf_drv_usbd_errata_type_52840(void) +{ + return (*(uint32_t *)0x10000130UL == 0x8UL); +} + +/** + * @brief Internal auxiliary function to check if the program is running on Engineering A revision + * @retval true It is NRF52480 chip and it is Engineering A revision + * @retval false It is other chip + */ +static inline bool nrf_drv_usbd_errata_type_52840_eng_a(void) +{ + return (nrf_drv_usbd_errata_type_52840() && (*(uint32_t *)0x10000134UL == 0x0UL)); +} + +/** + * @brief Internal auxiliary function to check if the program is running on Engineering B revision + * @retval true It is NRF52480 chip and it is Engineering B revision + * @retval false It is other chip + */ +static inline bool nrf_drv_usbd_errata_type_52840_eng_b(void) +{ + return (nrf_drv_usbd_errata_type_52840() && (*(uint32_t *)0x10000134UL == 0x1UL)); +} + +/** + * @brief Internal auxiliary function to check if the program is running on Engineering C revision + * @retval true It is NRF52480 chip and it is Engineering C revision + * @retval false It is other chip + */ +static inline bool nrf_drv_usbd_errata_type_52840_eng_c(void) +{ + return (nrf_drv_usbd_errata_type_52840() && (*(uint32_t *)0x10000134UL == 0x2UL)); +} + +/** + * @brief Internal auxiliary function to check if the program is running on Engineering D revision + * @retval true It is NRF52480 chip and it is Engineering D revision + * @retval false It is other chip + */ +static inline bool nrf_drv_usbd_errata_type_52840_eng_d(void) +{ + return (nrf_drv_usbd_errata_type_52840() && (*(uint32_t *)0x10000134UL == 0x3UL)); +} + +/** + * @brief Function to check if chip requires errata 104 + * + * Errata: USBD: EPDATA event is not always generated. + * + * @retval true Errata should be implemented + * @retval false Errata should not be implemented + */ +static inline bool nrf_drv_usbd_errata_104(void) +{ + return (NRF_DRV_USBD_ERRATA_ENABLE && nrf_drv_usbd_errata_type_52840_eng_a()); +} + +/** + * @brief Function to check if chip requires errata 154 + * + * Errata: During setup read/write transfer USBD acknowledges setup stage without SETUP task. + * + * @retval true Errata should be implemented + * @retval false Errata should not be implemented + */ +static inline bool nrf_drv_usbd_errata_154(void) +{ + return (NRF_DRV_USBD_ERRATA_ENABLE && nrf_drv_usbd_errata_type_52840_eng_a()); +} + +/** + * @brief Function to check if chip requires errata 166 + * + * Errata: ISO double buffering not functional + * + * @retval true Errata should be implemented + * @retval false Errata should not be implemented + */ +static inline bool nrf_drv_usbd_errata_166(void) +{ + return (NRF_DRV_USBD_ERRATA_ENABLE && true); +} + +/** + * @brief Function to check if chip requires errata 171 + * + * Errata: USBD might not reach its active state. + * + * @retval true Errata should be implemented + * @retval false Errata should not be implemented + */ +static inline bool nrf_drv_usbd_errata_171(void) +{ + return (NRF_DRV_USBD_ERRATA_ENABLE && true); +} + +/** + * @brief Function to check if chip requires errata 187 + * + * Errata: USB cannot be enabled + * + * @retval true Errata should be implemented + * @retval false Errata should not be implemented + */ +static inline bool nrf_drv_usbd_errata_187(void) +{ + return (NRF_DRV_USBD_ERRATA_ENABLE && + (nrf_drv_usbd_errata_type_52840_eng_b() || + nrf_drv_usbd_errata_type_52840_eng_c() || + nrf_drv_usbd_errata_type_52840_eng_d()) + ); +} + +/** + * @brief Function to check if chip requires errata 199 + * + * Errata: USBD cannot receive tasks during DMA + * + * @retval true Errata should be implemented + * @retval false Errata should not be implemented + */ +static inline bool nrf_drv_usb_errata_199(void) +{ + return (NRF_DRV_USBD_ERRATA_ENABLE && true); +} + +/** + * @brief Function to check if chip requires errata 200 + * + * Errata: SIZE.EPOUT not writable + * + * @retval true Errata should be implemented + * @retval false Errata should not be implemented + */ +static inline bool nrf_drv_usbd_errata_200(void) +{ + return (NRF_DRV_USBD_ERRATA_ENABLE && nrf_drv_usbd_errata_type_52840_eng_a()); +} + +/** @} */ +#endif /* NRF_DRV_USBD_ERRATA_H__ */ diff --git a/src/portable/nxp/lpc11_13_15/dcd_lpc11_13_15.c b/src/portable/nxp/lpc11_13_15/dcd_lpc11_13_15.c new file mode 100644 index 000000000..c910bf1ec --- /dev/null +++ b/src/portable/nxp/lpc11_13_15/dcd_lpc11_13_15.c @@ -0,0 +1,403 @@ +/**************************************************************************/ +/*! + @file dcd_lpc11_13_15.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13XX) + +#include "chip.h" +#include "device/dcd.h" +#include "dcd_lpc11_13_15.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +// Number of endpoints +#define EP_COUNT 10 + +// only SRAM1 & USB RAM can be used for transfer +#define SRAM_REGION 0x20000000 + +/* Although device controller are the same. DMA of + * - LPC11u can only transfer up to nbytes = 64 + * - LPC13 can transfer nbytes = 1023 (maximum) + * - LPC15 can ??? + */ +enum { + DMA_NBYTES_MAX = (CFG_TUSB_MCU == OPT_MCU_LPC11UXX ? 64 : 1023) +}; + +enum { + INT_SOF_MASK = BIT_(30), + INT_DEVICE_STATUS_MASK = BIT_(31) +}; + +enum { + CMDSTAT_DEVICE_ADDR_MASK = BIT_(7 )-1, + CMDSTAT_DEVICE_ENABLE_MASK = BIT_(7 ), + CMDSTAT_SETUP_RECEIVED_MASK = BIT_(8 ), + CMDSTAT_DEVICE_CONNECT_MASK = BIT_(16), ///< reflect the softconnect only, does not reflect the actual attached state + CMDSTAT_DEVICE_SUSPEND_MASK = BIT_(17), + CMDSTAT_CONNECT_CHANGE_MASK = BIT_(24), + CMDSTAT_SUSPEND_CHANGE_MASK = BIT_(25), + CMDSTAT_RESET_CHANGE_MASK = BIT_(26), + CMDSTAT_VBUS_DEBOUNCED_MASK = BIT_(28), +}; + +typedef struct ATTR_PACKED +{ + // Bits 21:6 (aligned 64) used in conjunction with bit 31:22 of DATABUFSTART + volatile uint16_t buffer_offset; + + volatile uint16_t nbytes : 10 ; + uint16_t is_iso : 1 ; + uint16_t toggle_mode : 1 ; + uint16_t toggle_reset : 1 ; + uint16_t stall : 1 ; + uint16_t disable : 1 ; + volatile uint16_t active : 1 ; +}ep_cmd_sts_t; + +TU_VERIFY_STATIC( sizeof(ep_cmd_sts_t) == 4, "size is not correct" ); + +typedef struct +{ + uint16_t total_bytes; + uint16_t xferred_bytes; + + uint16_t nbytes; +}xfer_dma_t; + +// NOTE data will be transferred as soon as dcd get request by dcd_pipe(_queue)_xfer using double buffering. +// current_td is used to keep track of number of remaining & xferred bytes of the current request. +typedef struct +{ + // 256 byte aligned, 2 for double buffer (not used) + // Each cmd_sts can only transfer up to DMA_NBYTES_MAX bytes each + ep_cmd_sts_t ep[EP_COUNT][2]; + + xfer_dma_t dma[EP_COUNT]; + + ATTR_ALIGNED(64) uint8_t setup_packet[8]; +}dcd_data_t; + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ + +// EP list must be 256-byte aligned +CFG_TUSB_MEM_SECTION ATTR_ALIGNED(256) static dcd_data_t _dcd; + +static inline uint16_t get_buf_offset(void const * buffer) +{ + uint32_t addr = (uint32_t) buffer; + TU_ASSERT( (addr & 0x3f) == 0, 0 ); + return ( (addr >> 6) & 0xFFFFUL ) ; +} + +static inline uint8_t ep_addr2id(uint8_t endpoint_addr) +{ + return 2*(endpoint_addr & 0x0F) + ((endpoint_addr & TUSB_DIR_IN_MASK) ? 1 : 0); +} + +//--------------------------------------------------------------------+ +// CONTROLLER API +//--------------------------------------------------------------------+ +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); +} + +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; +} + +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + + LPC_USB->DEVCMDSTAT &= ~CMDSTAT_DEVICE_ADDR_MASK; + LPC_USB->DEVCMDSTAT |= dev_addr; +} + +bool dcd_init(uint8_t rhport) +{ + (void) rhport; + + LPC_USB->EPLISTSTART = (uint32_t) _dcd.ep; + LPC_USB->DATABUFSTART = SRAM_REGION; + + LPC_USB->INTSTAT = LPC_USB->INTSTAT; // clear all pending interrupt + LPC_USB->INTEN = INT_DEVICE_STATUS_MASK; + LPC_USB->DEVCMDSTAT |= CMDSTAT_DEVICE_ENABLE_MASK | CMDSTAT_DEVICE_CONNECT_MASK | + CMDSTAT_RESET_CHANGE_MASK | CMDSTAT_CONNECT_CHANGE_MASK | CMDSTAT_SUSPEND_CHANGE_MASK; + + NVIC_EnableIRQ(USB0_IRQn); + + return true; +} + +//--------------------------------------------------------------------+ +// DCD Endpoint Port +//--------------------------------------------------------------------+ +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + if ( tu_edpt_number(ep_addr) == 0 ) + { + // TODO cannot able to STALL Control OUT endpoint !!!!! FIXME try some walk-around + _dcd.ep[0][0].stall = _dcd.ep[1][0].stall = 1; + } + else + { + uint8_t const ep_id = ep_addr2id(ep_addr); + _dcd.ep[ep_id][0].stall = 1; + } +} + +bool dcd_edpt_stalled(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const ep_id = ep_addr2id(ep_addr); + return _dcd.ep[ep_id][0].stall; +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const ep_id = ep_addr2id(ep_addr); + + _dcd.ep[ep_id][0].stall = 0; + _dcd.ep[ep_id][0].toggle_reset = 1; + _dcd.ep[ep_id][0].toggle_mode = 0; +} + +bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) +{ + (void) rhport; + + // TODO not support ISO yet + if (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) return false; + + //------------- Prepare Queue Head -------------// + uint8_t ep_id = ep_addr2id(p_endpoint_desc->bEndpointAddress); + + // Check if endpoint is available + TU_ASSERT( _dcd.ep[ep_id][0].disable && _dcd.ep[ep_id][1].disable ); + + tu_memclr(_dcd.ep[ep_id], 2*sizeof(ep_cmd_sts_t)); + _dcd.ep[ep_id][0].is_iso = (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS); + + // Enable EP interrupt + LPC_USB->INTEN |= BIT_(ep_id); + + return true; +} + +bool dcd_edpt_busy(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const ep_id = ep_addr2id(ep_addr); + return _dcd.ep[ep_id][0].active; +} + +static void prepare_ep_xfer(uint8_t ep_id, uint16_t buf_offset, uint16_t total_bytes) +{ + uint16_t const nbytes = tu_min16(total_bytes, DMA_NBYTES_MAX); + + _dcd.dma[ep_id].nbytes = nbytes; + + _dcd.ep[ep_id][0].buffer_offset = buf_offset; + _dcd.ep[ep_id][0].nbytes = nbytes; + _dcd.ep[ep_id][0].active = 1; +} + +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) +{ + (void) rhport; + + uint8_t const ep_id = ep_addr2id(ep_addr); + + tu_varclr(&_dcd.dma[ep_id]); + _dcd.dma[ep_id].total_bytes = total_bytes; + + prepare_ep_xfer(ep_id, get_buf_offset(buffer), total_bytes); + + return true; +} + +//--------------------------------------------------------------------+ +// IRQ +//--------------------------------------------------------------------+ +static void bus_reset(void) +{ + tu_memclr(&_dcd, sizeof(dcd_data_t)); + + // disable all non-control endpoints on bus reset + for(uint8_t ep_id = 2; ep_id < EP_COUNT; ep_id++) + { + _dcd.ep[ep_id][0].disable = _dcd.ep[ep_id][1].disable = 1; + } + + _dcd.ep[0][1].buffer_offset = get_buf_offset(_dcd.setup_packet); + + LPC_USB->EPINUSE = 0; + LPC_USB->EPBUFCFG = 0; + LPC_USB->EPSKIP = 0xFFFFFFFF; + + LPC_USB->INTSTAT = LPC_USB->INTSTAT; // clear all pending interrupt + LPC_USB->DEVCMDSTAT |= CMDSTAT_SETUP_RECEIVED_MASK; // clear setup received interrupt + LPC_USB->INTEN = INT_DEVICE_STATUS_MASK | BIT_(0) | BIT_(1); // enable device status & control endpoints +} + +static void process_xfer_isr(uint32_t int_status) +{ + for(uint8_t ep_id = 0; ep_id < EP_COUNT; ep_id++ ) + { + if ( BIT_TEST_(int_status, ep_id) ) + { + ep_cmd_sts_t * ep_cs = &_dcd.ep[ep_id][0]; + xfer_dma_t* xfer_dma = &_dcd.dma[ep_id]; + + xfer_dma->xferred_bytes += xfer_dma->nbytes - ep_cs->nbytes; + + if ( (ep_cs->nbytes == 0) && (xfer_dma->total_bytes > xfer_dma->xferred_bytes) ) + { + // There is more data to transfer + // buff_offset has been already increased by hw to correct value for next transfer + prepare_ep_xfer(ep_id, ep_cs->buffer_offset, xfer_dma->total_bytes - xfer_dma->xferred_bytes); + } + else + { + xfer_dma->total_bytes = xfer_dma->xferred_bytes; + + uint8_t const ep_addr = (ep_id / 2) | ((ep_id & 0x01) ? TUSB_DIR_IN_MASK : 0); + + // TODO no way determine if the transfer is failed or not + dcd_event_xfer_complete(0, ep_addr, xfer_dma->xferred_bytes, XFER_RESULT_SUCCESS, true); + } + } + } +} + +void USB_IRQHandler(void) +{ + uint32_t const dev_cmd_stat = LPC_USB->DEVCMDSTAT; + + uint32_t int_status = LPC_USB->INTSTAT & LPC_USB->INTEN; + LPC_USB->INTSTAT = int_status; // Acknowledge handled interrupt + + if (int_status == 0) return; + + //------------- Device Status -------------// + if ( int_status & INT_DEVICE_STATUS_MASK ) + { + LPC_USB->DEVCMDSTAT |= CMDSTAT_RESET_CHANGE_MASK | CMDSTAT_CONNECT_CHANGE_MASK | CMDSTAT_SUSPEND_CHANGE_MASK; + if ( dev_cmd_stat & CMDSTAT_RESET_CHANGE_MASK) // bus reset + { + bus_reset(); + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + if (dev_cmd_stat & CMDSTAT_CONNECT_CHANGE_MASK) + { + // device disconnect + if (dev_cmd_stat & CMDSTAT_DEVICE_ADDR_MASK) + { + // debouncing as this can be set when device is powering + dcd_event_bus_signal(0, DCD_EVENT_UNPLUGGED, true); + } + } + + // TODO support suspend & resume + if (dev_cmd_stat & CMDSTAT_SUSPEND_CHANGE_MASK) + { + if (dev_cmd_stat & CMDSTAT_DEVICE_SUSPEND_MASK) + { // suspend signal, bus idle for more than 3ms + // Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration. + if (dev_cmd_stat & CMDSTAT_DEVICE_ADDR_MASK) + { + dcd_event_bus_signal(0, DCD_EVENT_SUSPENDED, true); + } + } + } +// else +// { // resume signal +// dcd_event_bus_signal(0, DCD_EVENT_RESUME, true); +// } +// } + } + + // Setup Receive + if ( BIT_TEST_(int_status, 0) && (dev_cmd_stat & CMDSTAT_SETUP_RECEIVED_MASK) ) + { + // Follow UM flowchart to clear Active & Stall on both Control IN/OUT endpoints + _dcd.ep[0][0].active = _dcd.ep[1][0].active = 0; + _dcd.ep[0][0].stall = _dcd.ep[1][0].stall = 0; + + LPC_USB->DEVCMDSTAT |= CMDSTAT_SETUP_RECEIVED_MASK; + + dcd_event_setup_received(0, _dcd.setup_packet, true); + + // keep waiting for next setup + _dcd.ep[0][1].buffer_offset = get_buf_offset(_dcd.setup_packet); + + // clear bit0 + int_status = BIT_CLR_(int_status, 0); + } + + // Endpoint transfer complete interrupt + process_xfer_isr(int_status); +} + +#endif + diff --git a/src/portable/nxp/lpc11_13_15/dcd_lpc11_13_15.h b/src/portable/nxp/lpc11_13_15/dcd_lpc11_13_15.h new file mode 100644 index 000000000..92946e346 --- /dev/null +++ b/src/portable/nxp/lpc11_13_15/dcd_lpc11_13_15.h @@ -0,0 +1,51 @@ +/**************************************************************************/
+/*!
+ @file dcd_lpc11_13_15.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_DCD_LPC11_13_15_H_
+#define _TUSB_DCD_LPC11_13_15_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_DCD_LPC11_13_15_H_ */
diff --git a/src/portable/nxp/lpc17_40/dcd_lpc17_40.c b/src/portable/nxp/lpc17_40/dcd_lpc17_40.c new file mode 100644 index 000000000..82d3c3cac --- /dev/null +++ b/src/portable/nxp/lpc17_40/dcd_lpc17_40.c @@ -0,0 +1,596 @@ +/**************************************************************************/ +/*! + @file dcd_lpc175x_6x.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC40XX) + +#include "device/dcd.h" +#include "dcd_lpc17_40.h" +#include "chip.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +#define DCD_ENDPOINT_MAX 32 + +typedef struct ATTR_ALIGNED(4) +{ + //------------- Word 0 -------------// + uint32_t next; + + //------------- Word 1 -------------// + uint16_t atle_mode : 2; // 00: normal, 01: ATLE (auto length extraction) + uint16_t next_valid : 1; + uint16_t : 1; ///< reserved + uint16_t isochronous : 1; // is an iso endpoint + uint16_t max_packet_size : 11; + + volatile uint16_t buflen; // bytes for non-iso, number of packets for iso endpoint + + //------------- Word 2 -------------// + volatile uint32_t buffer; + + //------------- Word 3 -------------// + volatile uint16_t retired : 1; // initialized to zero + volatile uint16_t status : 4; + volatile uint16_t iso_last_packet_valid : 1; + volatile uint16_t atle_lsb_extracted : 1; // used in ATLE mode + volatile uint16_t atle_msb_extracted : 1; // used in ATLE mode + volatile uint16_t atle_mess_len_position : 6; // used in ATLE mode + uint16_t : 2; + + volatile uint16_t present_count; // For non-iso : The number of bytes transferred by the DMA engine + // For iso : number of packets + + //------------- Word 4 -------------// + // uint32_t iso_packet_size_addr; // iso only, can be omitted for non-iso +}dma_desc_t; + +TU_VERIFY_STATIC( sizeof(dma_desc_t) == 16, "size is not correct"); // TODO not support ISO for now + +typedef struct +{ + // must be 128 byte aligned + volatile dma_desc_t* udca[DCD_ENDPOINT_MAX]; + + // TODO DMA does not support control transfer (0-1 are not used, offset to reduce memory) + dma_desc_t dd[DCD_ENDPOINT_MAX]; + + struct + { + uint8_t* out_buffer; + uint8_t out_bytes; + volatile bool out_received; // indicate if data is already received in endpoint + + uint8_t in_bytes; + } control; + +} dcd_data_t; + +CFG_TUSB_MEM_SECTION ATTR_ALIGNED(128) static dcd_data_t _dcd; + + +//--------------------------------------------------------------------+ +// SIE Command +//--------------------------------------------------------------------+ +static void sie_cmd_code (sie_cmdphase_t phase, uint8_t code_data) +{ + LPC_USB->DevIntClr = (DEV_INT_COMMAND_CODE_EMPTY_MASK | DEV_INT_COMMAND_DATA_FULL_MASK); + LPC_USB->CmdCode = (phase << 8) | (code_data << 16); + + uint32_t const wait_flag = (phase == SIE_CMDPHASE_READ) ? DEV_INT_COMMAND_DATA_FULL_MASK : DEV_INT_COMMAND_CODE_EMPTY_MASK; + while ((LPC_USB->DevIntSt & wait_flag) == 0) {} + + LPC_USB->DevIntClr = wait_flag; +} + +static void sie_write (uint8_t cmd_code, uint8_t data_len, uint8_t data) +{ + sie_cmd_code(SIE_CMDPHASE_COMMAND, cmd_code); + + if (data_len) + { + sie_cmd_code(SIE_CMDPHASE_WRITE, data); + } +} + +static uint8_t sie_read (uint8_t cmd_code) +{ + sie_cmd_code(SIE_CMDPHASE_COMMAND , cmd_code); + sie_cmd_code(SIE_CMDPHASE_READ , cmd_code); + return (uint8_t) LPC_USB->CmdData; +} + +//--------------------------------------------------------------------+ +// PIPE HELPER +//--------------------------------------------------------------------+ +static inline uint8_t ep_addr2idx(uint8_t ep_addr) +{ + return 2*(ep_addr & 0x0F) + ((ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0); +} + +static void set_ep_size(uint8_t ep_id, uint16_t max_packet_size) +{ + // follows example in 11.10.4.2 + LPC_USB->ReEp |= BIT_(ep_id); + LPC_USB->EpInd = ep_id; // select index before setting packet size + LPC_USB->MaxPSize = max_packet_size; + + while ((LPC_USB->DevIntSt & DEV_INT_ENDPOINT_REALIZED_MASK) == 0) {} + LPC_USB->DevIntClr = DEV_INT_ENDPOINT_REALIZED_MASK; +} + + +//--------------------------------------------------------------------+ +// CONTROLLER API +//--------------------------------------------------------------------+ +static void bus_reset(void) +{ + // step 7 : slave mode set up + LPC_USB->EpIntClr = 0xFFFFFFFF; // clear all pending interrupt + LPC_USB->DevIntClr = 0xFFFFFFFF; // clear all pending interrupt + LPC_USB->EpIntEn = 0x03UL; // control endpoint cannot use DMA, non-control all use DMA + LPC_USB->EpIntPri = 0x03UL; // fast for control endpoint + + // step 8 : DMA set up + LPC_USB->EpDMADis = 0xFFFFFFFF; // firstly disable all dma + LPC_USB->DMARClr = 0xFFFFFFFF; // clear all pending interrupt + LPC_USB->EoTIntClr = 0xFFFFFFFF; + LPC_USB->NDDRIntClr = 0xFFFFFFFF; + LPC_USB->SysErrIntClr = 0xFFFFFFFF; + + tu_memclr(&_dcd, sizeof(dcd_data_t)); +} + +bool dcd_init(uint8_t rhport) +{ + (void) rhport; + + //------------- user manual 11.13 usb device controller initialization -------------// + // step 6 : set up control endpoint + set_ep_size(0, CFG_TUD_ENDOINT0_SIZE); + set_ep_size(1, CFG_TUD_ENDOINT0_SIZE); + + bus_reset(); + + LPC_USB->DevIntEn = (DEV_INT_DEVICE_STATUS_MASK | DEV_INT_ENDPOINT_FAST_MASK | DEV_INT_ENDPOINT_SLOW_MASK | DEV_INT_ERROR_MASK); + LPC_USB->UDCAH = (uint32_t) _dcd.udca; + LPC_USB->DMAIntEn = (DMA_INT_END_OF_XFER_MASK /*| DMA_INT_NEW_DD_REQUEST_MASK*/ | DMA_INT_ERROR_MASK); + + sie_write(SIE_CMDCODE_DEVICE_STATUS, 1, 1); // connect + + // USB IRQ priority should be set by application previously + NVIC_ClearPendingIRQ(USB_IRQn); + NVIC_EnableIRQ(USB_IRQn); + + return TUSB_ERROR_NONE; +} + +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); +} + +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + sie_write(SIE_CMDCODE_SET_ADDRESS, 1, 0x80 | dev_addr); // 7th bit is : device_enable +} + +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + sie_write(SIE_CMDCODE_CONFIGURE_DEVICE, 1, 1); +} + +//--------------------------------------------------------------------+ +// CONTROL HELPER +//--------------------------------------------------------------------+ +static inline uint8_t byte2dword(uint8_t bytes) +{ + return (bytes + 3) / 4; // length in dwords +} + +static void control_ep_write(void const * buffer, uint8_t len) +{ + uint32_t const * buf32 = (uint32_t const *) buffer; + + LPC_USB->Ctrl = USBCTRL_WRITE_ENABLE_MASK; // logical endpoint = 0 + LPC_USB->TxPLen = (uint32_t) len; + + for (uint8_t count = 0; count < byte2dword(len); count++) + { + LPC_USB->TxData = *buf32; // NOTE: cortex M3 have no problem with alignment + buf32++; + } + + LPC_USB->Ctrl = 0; + + // select control IN & validate the endpoint + sie_write(SIE_CMDCODE_ENDPOINT_SELECT+1, 0, 0); + sie_write(SIE_CMDCODE_BUFFER_VALIDATE , 0, 0); +} + +static uint8_t control_ep_read(void * buffer, uint8_t len) +{ + LPC_USB->Ctrl = USBCTRL_READ_ENABLE_MASK; // logical endpoint = 0 + while ((LPC_USB->RxPLen & USBRXPLEN_PACKET_READY_MASK) == 0) {} // TODO blocking, should have timeout + + len = tu_min8(len, (uint8_t) (LPC_USB->RxPLen & USBRXPLEN_PACKET_LENGTH_MASK) ); + uint32_t *buf32 = (uint32_t*) buffer; + + for (uint8_t count=0; count < byte2dword(len); count++) + { + *buf32 = LPC_USB->RxData; + buf32++; + } + + LPC_USB->Ctrl = 0; + + // select control OUT & clear the endpoint + sie_write(SIE_CMDCODE_ENDPOINT_SELECT+0, 0, 0); + sie_write(SIE_CMDCODE_BUFFER_CLEAR , 0, 0); + + return len; +} + +//--------------------------------------------------------------------+ +// DCD Endpoint Port +//--------------------------------------------------------------------+ +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 ep_id = ep_addr2idx(p_endpoint_desc->bEndpointAddress); + + // Endpoint type is fixed to endpoint number + // 1: interrupt, 2: Bulk, 3: Iso and so on + switch ( p_endpoint_desc->bmAttributes.xfer ) + { + case TUSB_XFER_INTERRUPT: + TU_ASSERT((epnum % 3) == 1); + break; + + case TUSB_XFER_BULK: + TU_ASSERT((epnum % 3) == 2 || (epnum == 15)); + break; + + case TUSB_XFER_ISOCHRONOUS: + TU_ASSERT((epnum % 3) == 3 && (epnum != 15)); + break; + + default: + break; + } + + //------------- Realize Endpoint with Max Packet Size -------------// + set_ep_size(ep_id, p_endpoint_desc->wMaxPacketSize.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->retired = 1; // invalid at first + + sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS + ep_id, 1, 0); // clear all endpoint status + + return true; +} + +bool dcd_edpt_busy(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t ep_id = ep_addr2idx( ep_addr ); + return (_dcd.udca[ep_id] != NULL && !_dcd.udca[ep_id]->retired); +} + +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + if ( tu_edpt_number(ep_addr) == 0 ) + { + sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+0, 1, SIE_SET_ENDPOINT_STALLED_MASK | SIE_SET_ENDPOINT_CONDITION_STALLED_MASK); + }else + { + uint8_t ep_id = ep_addr2idx( ep_addr ); + sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+ep_id, 1, SIE_SET_ENDPOINT_STALLED_MASK); + } +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + uint8_t ep_id = ep_addr2idx(ep_addr); + + sie_write(SIE_CMDCODE_ENDPOINT_SET_STATUS+ep_id, 1, 0); +} + +bool dcd_edpt_stalled (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const ep_state = sie_read(SIE_CMDCODE_ENDPOINT_SELECT + ep_addr2idx(ep_addr)); + return (ep_state & SIE_SELECT_ENDPOINT_STALL_MASK) ? true : false; +} + +static bool control_xact(uint8_t rhport, uint8_t dir, uint8_t * buffer, uint8_t len) +{ + (void) rhport; + + if ( dir ) + { + _dcd.control.in_bytes = len; + control_ep_write(buffer, len); + }else + { + if ( _dcd.control.out_received ) + { + // Already received the DATA OUT packet + _dcd.control.out_received = false; + _dcd.control.out_buffer = NULL; + _dcd.control.out_bytes = 0; + + uint8_t received = control_ep_read(buffer, len); + dcd_event_xfer_complete(0, 0, received, XFER_RESULT_SUCCESS, true); + }else + { + _dcd.control.out_buffer = buffer; + _dcd.control.out_bytes = len; + } + } + + return true; +} + +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) +{ + // Control transfer is not DMA support, and must be done in slave mode + if ( tu_edpt_number(ep_addr) == 0 ) + { + return control_xact(rhport, tu_edpt_dir(ep_addr), buffer, (uint8_t) total_bytes); + } + else + { + uint8_t ep_id = ep_addr2idx(ep_addr); + dma_desc_t* dd = &_dcd.dd[ep_id]; + + // Prepare DMA descriptor + // Isochronous & max packet size must be preserved, Other fields of dd should be clear + uint16_t const ep_size = dd->max_packet_size; + uint8_t is_iso = dd->isochronous; + + tu_memclr(dd, sizeof(dma_desc_t)); + dd->isochronous = is_iso; + dd->max_packet_size = ep_size; + dd->buffer = (uint32_t) buffer; + dd->buflen = total_bytes; + + _dcd.udca[ep_id] = dd; + + if ( ep_id % 2 ) + { + // Clear EP interrupt before Enable DMA + LPC_USB->EpIntEn &= ~BIT_(ep_id); + LPC_USB->EpDMAEn = BIT_(ep_id); + + // endpoint IN need to actively raise DMA request + LPC_USB->DMARSet = BIT_(ep_id); + }else + { + // Enable DMA + LPC_USB->EpDMAEn = BIT_(ep_id); + } + + return true; + } +} + +//--------------------------------------------------------------------+ +// ISR +//--------------------------------------------------------------------+ + +// handle control xfer (slave mode) +static void control_xfer_isr(uint8_t rhport, uint32_t ep_int_status) +{ + // Control out complete + if ( ep_int_status & BIT_(0) ) + { + bool is_setup = sie_read(SIE_CMDCODE_ENDPOINT_SELECT+0) & SIE_SELECT_ENDPOINT_SETUP_RECEIVED_MASK; + + LPC_USB->EpIntClr = BIT_(0); + + if (is_setup) + { + uint8_t setup_packet[8]; + control_ep_read(setup_packet, 8); // TODO read before clear setup above + + dcd_event_setup_received(rhport, setup_packet, true); + } + else if ( _dcd.control.out_buffer ) + { + // software queued transfer previously + uint8_t received = control_ep_read(_dcd.control.out_buffer, _dcd.control.out_bytes); + + _dcd.control.out_buffer = NULL; + _dcd.control.out_bytes = 0; + + dcd_event_xfer_complete(rhport, 0, received, XFER_RESULT_SUCCESS, true); + }else + { + // hardware auto ack packet -> mark as received + _dcd.control.out_received = true; + } + } + + // Control In complete + if ( ep_int_status & BIT_(1) ) + { + LPC_USB->EpIntClr = BIT_(1); + dcd_event_xfer_complete(rhport, TUSB_DIR_IN_MASK, _dcd.control.in_bytes, XFER_RESULT_SUCCESS, true); + } +} + +// handle bus event signal +static void bus_event_isr(uint8_t rhport) +{ + uint8_t const dev_status = sie_read(SIE_CMDCODE_DEVICE_STATUS); + if (dev_status & SIE_DEV_STATUS_RESET_MASK) + { + bus_reset(); + dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, true); + } + + if (dev_status & SIE_DEV_STATUS_CONNECT_CHANGE_MASK) + { + // device is disconnected, require using VBUS (P1_30) + dcd_event_bus_signal(rhport, DCD_EVENT_UNPLUGGED, true); + } + + if (dev_status & SIE_DEV_STATUS_SUSPEND_CHANGE_MASK) + { + if (dev_status & SIE_DEV_STATUS_SUSPEND_MASK) + { + dcd_event_bus_signal(rhport, DCD_EVENT_SUSPENDED, true); + } + else + { + dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); + } + } +} + +// Helper to complete a DMA descriptor for non-control transfer +static void dd_complete_isr(uint8_t rhport, uint8_t ep_id) +{ + dma_desc_t* const dd = &_dcd.dd[ep_id]; + uint8_t result = (dd->status == DD_STATUS_NORMAL || dd->status == DD_STATUS_DATA_UNDERUN) ? XFER_RESULT_SUCCESS : XFER_RESULT_FAILED; + uint8_t const ep_addr = (ep_id / 2) | ((ep_id & 0x01) ? TUSB_DIR_IN_MASK : 0); + + dcd_event_xfer_complete(rhport, ep_addr, dd->present_count, result, true); +} + +// main USB IRQ handler +void hal_dcd_isr(uint8_t rhport) +{ + uint32_t const dev_int_status = LPC_USB->DevIntSt & LPC_USB->DevIntEn; + LPC_USB->DevIntClr = dev_int_status;// Acknowledge handled interrupt + + // Bus event + if (dev_int_status & DEV_INT_DEVICE_STATUS_MASK) + { + bus_event_isr(rhport); + } + + // Endpoint interrupt + uint32_t const ep_int_status = LPC_USB->EpIntSt & LPC_USB->EpIntEn; + + // Control Endpoint are fast + if (dev_int_status & DEV_INT_ENDPOINT_FAST_MASK) + { + // Note clear USBEpIntClr will also clear the setup received bit --> clear after handle setup packet + // Only clear USBEpIntClr 1 endpoint each, and should wait for CDFULL bit set + control_xfer_isr(rhport, ep_int_status); + } + + // non-control IN are slow + if (dev_int_status & DEV_INT_ENDPOINT_SLOW_MASK) + { + for ( uint8_t ep_id = 3; ep_id < DCD_ENDPOINT_MAX; ep_id += 2 ) + { + if ( BIT_TEST_(ep_int_status, ep_id) ) + { + LPC_USB->EpIntClr = BIT_(ep_id); + + // Clear Ep interrupt for next DMA + LPC_USB->EpIntEn &= ~BIT_(ep_id); + + dd_complete_isr(rhport, ep_id); + } + } + } + + // DMA transfer complete (RAM <-> EP) for Non-Control + // OUT: USB transfer is fully complete + // IN : UBS transfer is still on-going -> enable EpIntEn to know when it is complete + uint32_t const dma_int_status = LPC_USB->DMAIntSt & LPC_USB->DMAIntEn; + if (dma_int_status & DMA_INT_END_OF_XFER_MASK) + { + uint32_t const eot = LPC_USB->EoTIntSt; + LPC_USB->EoTIntClr = eot; // acknowledge interrupt source + + for ( uint8_t ep_id = 2; ep_id < DCD_ENDPOINT_MAX; ep_id++ ) + { + if ( BIT_TEST_(eot, ep_id) ) + { + if ( ep_id & 0x01 ) + { + // IN enable EpInt for end of usb transfer + LPC_USB->EpIntEn |= BIT_(ep_id); + }else + { + // OUT + dd_complete_isr(rhport, ep_id); + } + } + } + } + + // Errors + if ( (dev_int_status & DEV_INT_ERROR_MASK) || (dma_int_status & DMA_INT_ERROR_MASK) ) + { + uint32_t error_status = sie_read(SIE_CMDCODE_READ_ERROR_STATUS); + (void) error_status; + TU_BREAKPOINT(); + } +} + +#endif diff --git a/src/portable/nxp/lpc17_40/dcd_lpc17_40.h b/src/portable/nxp/lpc17_40/dcd_lpc17_40.h new file mode 100644 index 000000000..d6b76fcd1 --- /dev/null +++ b/src/portable/nxp/lpc17_40/dcd_lpc17_40.h @@ -0,0 +1,164 @@ +/**************************************************************************/ +/*! + @file dcd_lpc175x_6x.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#ifndef _TUSB_DCD_LPC175X_6X_H_ +#define _TUSB_DCD_LPC175X_6X_H_ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Register Interface +//--------------------------------------------------------------------+ + +//------------- USB Interrupt USBIntSt -------------// +//enum { +// DCD_USB_REQ_LOW_PRIO_MASK = BIT_(0), +// DCD_USB_REQ_HIGH_PRIO_MASK = BIT_(1), +// DCD_USB_REQ_DMA_MASK = BIT_(2), +// DCD_USB_REQ_NEED_CLOCK_MASK = BIT_(8), +// DCD_USB_REQ_ENABLE_MASK = BIT_(31) +//}; + +//------------- Device Interrupt USBDevInt -------------// +enum { + DEV_INT_FRAME_MASK = BIT_(0), + DEV_INT_ENDPOINT_FAST_MASK = BIT_(1), + DEV_INT_ENDPOINT_SLOW_MASK = BIT_(2), + DEV_INT_DEVICE_STATUS_MASK = BIT_(3), + DEV_INT_COMMAND_CODE_EMPTY_MASK = BIT_(4), + DEV_INT_COMMAND_DATA_FULL_MASK = BIT_(5), + DEV_INT_RX_ENDPOINT_PACKET_MASK = BIT_(6), + DEV_INT_TX_ENDPOINT_PACKET_MASK = BIT_(7), + DEV_INT_ENDPOINT_REALIZED_MASK = BIT_(8), + DEV_INT_ERROR_MASK = BIT_(9) +}; + +//------------- DMA Interrupt USBDMAInt-------------// +enum { + DMA_INT_END_OF_XFER_MASK = BIT_(0), + DMA_INT_NEW_DD_REQUEST_MASK = BIT_(1), + DMA_INT_ERROR_MASK = BIT_(2) +}; + +//------------- USBCtrl -------------// +enum { + USBCTRL_READ_ENABLE_MASK = BIT_(0), + USBCTRL_WRITE_ENABLE_MASK = BIT_(1), +}; + +//------------- USBRxPLen -------------// +enum { + USBRXPLEN_PACKET_LENGTH_MASK = (BIT_(10)-1), + USBRXPLEN_DATA_VALID_MASK = BIT_(10), + USBRXPLEN_PACKET_READY_MASK = BIT_(11), +}; + +//------------- SIE Command Code -------------// +typedef enum +{ + SIE_CMDPHASE_WRITE = 1, + SIE_CMDPHASE_READ = 2, + SIE_CMDPHASE_COMMAND = 5 +} sie_cmdphase_t; + +enum { + // device commands + SIE_CMDCODE_SET_ADDRESS = 0xd0, + SIE_CMDCODE_CONFIGURE_DEVICE = 0xd8, + SIE_CMDCODE_SET_MODE = 0xf3, + SIE_CMDCODE_READ_FRAME_NUMBER = 0xf5, + SIE_CMDCODE_READ_TEST_REGISTER = 0xfd, + SIE_CMDCODE_DEVICE_STATUS = 0xfe, + SIE_CMDCODE_GET_ERROR = 0xff, + SIE_CMDCODE_READ_ERROR_STATUS = 0xfb, + + // endpoint commands + SIE_CMDCODE_ENDPOINT_SELECT = 0x00, // + endpoint index + SIE_CMDCODE_ENDPOINT_SELECT_CLEAR_INTERRUPT = 0x40, // + endpoint index, should use USBEpIntClr instead + SIE_CMDCODE_ENDPOINT_SET_STATUS = 0x40, // + endpoint index + SIE_CMDCODE_BUFFER_CLEAR = 0xf2, + SIE_CMDCODE_BUFFER_VALIDATE = 0xfa +}; + +//------------- SIE Device Status (get/set from SIE_CMDCODE_DEVICE_STATUS) -------------// +enum { + SIE_DEV_STATUS_CONNECT_STATUS_MASK = BIT_(0), + SIE_DEV_STATUS_CONNECT_CHANGE_MASK = BIT_(1), + SIE_DEV_STATUS_SUSPEND_MASK = BIT_(2), + SIE_DEV_STATUS_SUSPEND_CHANGE_MASK = BIT_(3), + SIE_DEV_STATUS_RESET_MASK = BIT_(4) +}; + +//------------- SIE Select Endpoint Command -------------// +enum { + SIE_SELECT_ENDPOINT_FULL_EMPTY_MASK = BIT_(0), // 0: empty, 1 full. IN endpoint checks empty, OUT endpoint check full + SIE_SELECT_ENDPOINT_STALL_MASK = BIT_(1), + SIE_SELECT_ENDPOINT_SETUP_RECEIVED_MASK = BIT_(2), // clear by SIE_CMDCODE_ENDPOINT_SELECT_CLEAR_INTERRUPT + SIE_SELECT_ENDPOINT_PACKET_OVERWRITTEN_MASK = BIT_(3), // previous packet is overwritten by a SETUP packet + SIE_SELECT_ENDPOINT_NAK_MASK = BIT_(4), // last packet response is NAK (auto clear by an ACK) + SIE_SELECT_ENDPOINT_BUFFER1_FULL_MASK = BIT_(5), + SIE_SELECT_ENDPOINT_BUFFER2_FULL_MASK = BIT_(6) +}; + +typedef enum +{ + SIE_SET_ENDPOINT_STALLED_MASK = BIT_(0), + SIE_SET_ENDPOINT_DISABLED_MASK = BIT_(5), + SIE_SET_ENDPOINT_RATE_FEEDBACK_MASK = BIT_(6), + SIE_SET_ENDPOINT_CONDITION_STALLED_MASK = BIT_(7), +}sie_endpoint_set_status_mask_t; + +//------------- DMA Descriptor Status -------------// +enum { + DD_STATUS_NOT_SERVICED = 0, + DD_STATUS_BEING_SERVICED, + DD_STATUS_NORMAL, + DD_STATUS_DATA_UNDERUN, // short packet + DD_STATUS_DATA_OVERRUN, + DD_STATUS_SYSTEM_ERROR +}; + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_DCD_LPC175X_6X_H_ */ diff --git a/src/portable/nxp/lpc17_40/hal_lpc17_40.c b/src/portable/nxp/lpc17_40/hal_lpc17_40.c new file mode 100644 index 000000000..04aebf920 --- /dev/null +++ b/src/portable/nxp/lpc17_40/hal_lpc17_40.c @@ -0,0 +1,73 @@ +/**************************************************************************/ +/*! + @file hal_lpc175x_6x.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "common/tusb_common.h" + +#if (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC40XX) + +#include "chip.h" + +extern void hal_hcd_isr(uint8_t hostid); +extern void hal_dcd_isr(uint8_t rhport); + +void USB_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + hal_hcd_isr(0); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + hal_dcd_isr(0); + #endif +} + +//FIXME move later +void hcd_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USB_IRQn); +} + +void hcd_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USB_IRQn); +} + + +#endif diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c new file mode 100644 index 000000000..70b34d848 --- /dev/null +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -0,0 +1,390 @@ +/**************************************************************************/ +/*! + @file dcd_lpc43xx.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX) + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "tusb_hal.h" + +#include "device/dcd.h" +#include "dcd_lpc18_43.h" + +#include "chip.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +#define QHD_MAX 12 +#define QTD_NEXT_INVALID 0x01 + +typedef struct { + // Must be at 2K alignment + dcd_qhd_t qhd[QHD_MAX] ATTR_ALIGNED(64); + dcd_qtd_t qtd[QHD_MAX] ATTR_ALIGNED(32); +}dcd_data_t; + +#if (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) +CFG_TUSB_MEM_SECTION ATTR_ALIGNED(2048) static dcd_data_t dcd_data0; +#endif + +#if (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) +CFG_TUSB_MEM_SECTION ATTR_ALIGNED(2048) static dcd_data_t dcd_data1; +#endif + +static LPC_USBHS_T * const LPC_USB[2] = { LPC_USB0, LPC_USB1 }; + +static dcd_data_t* const dcd_data_ptr[2] = +{ +#if (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) + &dcd_data0, +#else + NULL, +#endif + +#if (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) + &dcd_data1 +#else + NULL +#endif +}; + +//--------------------------------------------------------------------+ +// CONTROLLER API +//--------------------------------------------------------------------+ +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + LPC_USB[rhport]->DEVICEADDR = (dev_addr << 25) | BIT_(24); +} + +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + // nothing to do +} + +/// follows LPC43xx User Manual 23.10.3 +static void bus_reset(uint8_t rhport) +{ + LPC_USBHS_T* lpc_usb = LPC_USB[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 bechanged from the control type to any other + // type (e.g. bulk). Leaving an unconfigured endpoint control will cause undefined behavior + // for the data PID tracking on the active endpoint. + + // USB0 has 5 but USB1 only has 3 non-control endpoints + for( int i=1; i < (rhport ? 6 : 4); i++) + { + lpc_usb->ENDPTCTRL[i] = (TUSB_XFER_BULK << 2) | (TUSB_XFER_BULK << 18); + } + + //------------- Clear All Registers -------------// + lpc_usb->ENDPTNAK = lpc_usb->ENDPTNAK; + lpc_usb->ENDPTNAKEN = 0; + lpc_usb->USBSTS_D = lpc_usb->USBSTS_D; + lpc_usb->ENDPTSETUPSTAT = lpc_usb->ENDPTSETUPSTAT; + lpc_usb->ENDPTCOMPLETE = lpc_usb->ENDPTCOMPLETE; + + while (lpc_usb->ENDPTPRIME); + lpc_usb->ENDPTFLUSH = 0xFFFFFFFF; + while (lpc_usb->ENDPTFLUSH); + + // read reset bit in portsc + + //------------- Queue Head & Queue TD -------------// + dcd_data_t* p_dcd = dcd_data_ptr[rhport]; + tu_memclr(p_dcd, sizeof(dcd_data_t)); + + //------------- Set up Control Endpoints (0 OUT, 1 IN) -------------// + p_dcd->qhd[0].zero_length_termination = p_dcd->qhd[1].zero_length_termination = 1; + p_dcd->qhd[0].max_package_size = p_dcd->qhd[1].max_package_size = CFG_TUD_ENDOINT0_SIZE; + p_dcd->qhd[0].qtd_overlay.next = p_dcd->qhd[1].qtd_overlay.next = QTD_NEXT_INVALID; + + p_dcd->qhd[0].int_on_setup = 1; // OUT only +} + +bool dcd_init(uint8_t rhport) +{ + LPC_USBHS_T* const lpc_usb = LPC_USB[rhport]; + dcd_data_t* p_dcd = dcd_data_ptr[rhport]; + + tu_memclr(p_dcd, sizeof(dcd_data_t)); + + lpc_usb->ENDPOINTLISTADDR = (uint32_t) p_dcd->qhd; // Endpoint List Address has to be 2K alignment + lpc_usb->USBSTS_D = lpc_usb->USBSTS_D; + lpc_usb->USBINTR_D = INT_MASK_USB | INT_MASK_ERROR | INT_MASK_PORT_CHANGE | INT_MASK_RESET | INT_MASK_SUSPEND | INT_MASK_SOF; + + lpc_usb->USBCMD_D &= ~0x00FF0000; // Interrupt Threshold Interval = 0 + lpc_usb->USBCMD_D |= BIT_(0); // connect + + return true; +} + +void dcd_int_enable(uint8_t rhport) +{ + NVIC_EnableIRQ(rhport ? USB1_IRQn : USB0_IRQn); +} + +void dcd_int_disable(uint8_t rhport) +{ + NVIC_DisableIRQ(rhport ? USB1_IRQn : USB0_IRQn); +} + +//--------------------------------------------------------------------+ +// 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) +{ + 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; + + if (data_ptr != NULL) + { + p_qtd->buffer[0] = (uint32_t) data_ptr; + for(uint8_t i=1; i<5; i++) + { + p_qtd->buffer[i] |= tu_align4k( p_qtd->buffer[i-1] ) + 4096; + } + } +} + +//--------------------------------------------------------------------+ +// 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); + + if ( epnum == 0) + { + // Stall both Control IN and OUT + LPC_USB[rhport]->ENDPTCTRL[epnum] |= ( (ENDPTCTRL_MASK_STALL << 16) || (ENDPTCTRL_MASK_STALL << 0) ); + }else + { + LPC_USB[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_MASK_STALL << (dir ? 16 : 0); + } +} + +bool dcd_edpt_stalled (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); + + return LPC_USB[rhport]->ENDPTCTRL[epnum] & (ENDPTCTRL_MASK_STALL << (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 + LPC_USB[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_MASK_TOGGLE_RESET << ( dir ? 16 : 0 ); + LPC_USB[rhport]->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_MASK_STALL << ( dir ? 16 : 0)); +} + +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; + + // USB0 has 5, USB1 has 3 non-control endpoints + TU_ASSERT( epnum <= (rhport ? 3 : 5) ); + + //------------- Prepare Queue Head -------------// + dcd_qhd_t * p_qhd = &dcd_data_ptr[rhport]->qhd[ep_idx]; + 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->qtd_overlay.next = QTD_NEXT_INVALID; + + // Enable EP Control + LPC_USB[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_MASK_ENABLE | ENDPTCTRL_MASK_TOGGLE_RESET) << (dir ? 16 : 0); + + return true; +} + +bool dcd_edpt_busy(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 ep_idx = 2*epnum + dir; + + dcd_qtd_t * p_qtd = &dcd_data_ptr[rhport]->qtd[ep_idx]; + + return p_qtd->active; +// return !p_qhd->qtd_overlay.halted && p_qhd->qtd_overlay.active; +} + +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); + uint8_t const ep_idx = 2*epnum + dir; + + 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(LPC_USB[rhport]->ENDPTSETUPSTAT & BIT_(0)) {} + } + + dcd_qhd_t * p_qhd = &dcd_data_ptr[rhport]->qhd[ep_idx]; + dcd_qtd_t * p_qtd = &dcd_data_ptr[rhport]->qtd[ep_idx]; + + //------------- 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 + + // start transfer + LPC_USB[rhport]->ENDPTPRIME = BIT_( ep_idx2bit(ep_idx) ) ; + + return true; +} + +//--------------------------------------------------------------------+ +// ISR +//--------------------------------------------------------------------+ +void hal_dcd_isr(uint8_t rhport) +{ + LPC_USBHS_T* const lpc_usb = LPC_USB[rhport]; + + uint32_t const int_enable = lpc_usb->USBINTR_D; + uint32_t const int_status = lpc_usb->USBSTS_D & int_enable; + lpc_usb->USBSTS_D = int_status; // Acknowledge handled interrupt + + if (int_status == 0) return;// disabled interrupt sources + + + if (int_status & INT_MASK_RESET) + { + bus_reset(rhport); + dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, true); + } + + if (int_status & INT_MASK_SUSPEND) + { + if (lpc_usb->PORTSC1_D & PORTSC_SUSPEND_MASK) + { + // Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration. + if ((lpc_usb->DEVICEADDR >> 25) & 0x0f) + { + dcd_event_bus_signal(rhport, DCD_EVENT_SUSPENDED, true); + } + } + } + + // TODO disconnection does not generate interrupt !!!!!! +// if (int_status & INT_MASK_PORT_CHANGE) +// { +// if ( !(lpc_usb->PORTSC1_D & PORTSC_CURRENT_CONNECT_STATUS_MASK) ) +// { +// dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_UNPLUGGED }; +// dcd_event_handler(&event, true); +// } +// } + + if (int_status & INT_MASK_USB) + { + uint32_t const edpt_complete = lpc_usb->ENDPTCOMPLETE; + lpc_usb->ENDPTCOMPLETE = edpt_complete; // acknowledge + + dcd_data_t* const p_dcd = dcd_data_ptr[rhport]; + + if (lpc_usb->ENDPTSETUPSTAT) + { + //------------- Set up Received -------------// + // 23.10.10.2 Operational model for setup transfers + lpc_usb->ENDPTSETUPSTAT = lpc_usb->ENDPTSETUPSTAT;// acknowledge + + dcd_event_setup_received(rhport, (uint8_t*) &p_dcd->qhd[0].setup_request, true); + } + + if ( edpt_complete ) + { + for(uint8_t ep_idx = 0; ep_idx < QHD_MAX; ep_idx++) + { + if ( 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_ptr[rhport]->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 (int_status & INT_MASK_SOF) + { + dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); + } + + if (int_status & INT_MASK_NAK) {} + if (int_status & INT_MASK_ERROR) TU_ASSERT(false, ); +} + +#endif diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.h b/src/portable/nxp/lpc18_43/dcd_lpc18_43.h new file mode 100644 index 000000000..faf0e3b0f --- /dev/null +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.h @@ -0,0 +1,156 @@ +/**************************************************************************/ +/*! + @file dcd_lpc43xx.h + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +/** \ingroup group_dcd + * \defgroup group_dcd_lpc143xx LPC43xx + * @{ */ + +#ifndef _TUSB_DCD_LPC43XX_H_ +#define _TUSB_DCD_LPC43XX_H_ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +/*---------- ENDPTCTRL ----------*/ +enum { + ENDPTCTRL_MASK_STALL = BIT_(0), + ENDPTCTRL_MASK_TOGGLE_INHIBIT = BIT_(5), ///< used for test only + ENDPTCTRL_MASK_TOGGLE_RESET = BIT_(6), + ENDPTCTRL_MASK_ENABLE = BIT_(7) +}; + +/*---------- USBCMD ----------*/ +enum { + USBCMD_MASK_RUN_STOP = BIT_(0), + USBCMD_MASK_RESET = BIT_(1), + USBCMD_MASK_SETUP_TRIPWIRE = BIT_(13), + USBCMD_MASK_ADD_QTD_TRIPWIRE = BIT_(14) ///< This bit is used as a semaphore to ensure the to proper addition of a new dTD to an active (primed) endpoint’s linked list. This bit is set and cleared by software during the process of adding a new dTD +}; +// Interrupt Threshold bit 23:16 + +/*---------- USBSTS, USBINTR ----------*/ +enum { + INT_MASK_USB = BIT_(0), + INT_MASK_ERROR = BIT_(1), + INT_MASK_PORT_CHANGE = BIT_(2), + INT_MASK_RESET = BIT_(6), + INT_MASK_SOF = BIT_(7), + INT_MASK_SUSPEND = BIT_(8), + INT_MASK_NAK = BIT_(16) +}; + +//------------- PORTSC -------------// +enum { + PORTSC_CURRENT_CONNECT_STATUS_MASK = BIT_(0), + PORTSC_FORCE_PORT_RESUME_MASK = BIT_(6), + PORTSC_SUSPEND_MASK = BIT_(7) +}; + +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 : 0 ; + + // 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 -------------// + uint16_t expected_bytes; + uint8_t reserved[2]; +} dcd_qtd_t; + +TU_VERIFY_STATIC( sizeof(dcd_qtd_t) == 32, "size is not correct"); + +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 : 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; + + // 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; + + //--------------------------------------------------------------------+ + /// 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. + //--------------------------------------------------------------------+ + uint8_t reserved[16]; +} dcd_qhd_t; + +TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct"); + + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_DCD_LPC43XX_H_ */ + +/** @} */ diff --git a/src/portable/nxp/lpc18_43/hal_lpc18_43.c b/src/portable/nxp/lpc18_43/hal_lpc18_43.c new file mode 100644 index 000000000..ef3977995 --- /dev/null +++ b/src/portable/nxp/lpc18_43/hal_lpc18_43.c @@ -0,0 +1,74 @@ +/**************************************************************************/ +/*! + @file hal_lpc43xx.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb.h" + +#if (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX) + +#include "chip.h" + +extern void hal_dcd_isr(uint8_t rhport); +extern void hal_hcd_isr(uint8_t hostid); + +#if CFG_TUSB_RHPORT0_MODE +void USB0_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + hal_hcd_isr(0); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + hal_dcd_isr(0); + #endif +} +#endif + +#if CFG_TUSB_RHPORT1_MODE +void USB1_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + hal_hcd_isr(1); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + hal_dcd_isr(1); + #endif +} +#endif + +#endif diff --git a/src/portable/nxp/lpc18_43/hcd_lpc18_43.c b/src/portable/nxp/lpc18_43/hcd_lpc18_43.c new file mode 100644 index 000000000..092030056 --- /dev/null +++ b/src/portable/nxp/lpc18_43/hcd_lpc18_43.c @@ -0,0 +1,62 @@ +/**************************************************************************/ +/*! + @file hcd_lpc18_43.c + @author hathach (tinyusb.org) + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2018, hathach (tinyusb.org) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + This file is part of the tinyusb stack. +*/ +/**************************************************************************/ + +#include "tusb_option.h" + +#if TUSB_OPT_HOST_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX) + +#include "chip.h" + +// LPC18xx and 43xx use EHCI driver + +void hcd_int_enable(uint8_t rhport) +{ + NVIC_EnableIRQ(rhport ? USB1_IRQn : USB0_IRQn); +} + +void hcd_int_disable(uint8_t rhport) +{ + NVIC_DisableIRQ(rhport ? USB1_IRQn : USB0_IRQn); +} + +uint32_t hcd_ehci_register_addr(uint8_t rhport) +{ + return (uint32_t) (rhport ? &LPC_USB1->USBCMD_H : &LPC_USB0->USBCMD_H ); +} + +#endif diff --git a/src/portable/readme.md b/src/portable/readme.md new file mode 100644 index 000000000..a3e8557dc --- /dev/null +++ b/src/portable/readme.md @@ -0,0 +1,4 @@ +To port tinyusb to support new MCU you need to implement all API in the +- tusb_hal.h (mandatory for both device and host stack) +- device/dcd.h for device stack +- host/hcd.h for host stack diff --git a/src/tusb.c b/src/tusb.c new file mode 100644 index 000000000..4f7996664 --- /dev/null +++ b/src/tusb.c @@ -0,0 +1,92 @@ +/**************************************************************************/
+/*!
+ @file tusb.c
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#include "tusb_option.h"
+
+#if TUSB_OPT_HOST_ENABLED || TUSB_OPT_DEVICE_ENABLED
+#define _TINY_USB_SOURCE_FILE_
+
+#include "tusb.h"
+
+static bool _initialized = false;
+
+// TODO clean up
+#if TUSB_OPT_DEVICE_ENABLED
+#include "device/usbd_pvt.h"
+#endif
+
+bool tusb_init(void)
+{
+ // skip if already initialized
+ if (_initialized) return true;
+
+#if TUSB_OPT_HOST_ENABLED
+ TU_VERIFY( usbh_init() ); // init host stack
+#endif
+
+#if TUSB_OPT_DEVICE_ENABLED
+ TU_VERIFY ( usbd_init() ); // init device stack
+#endif
+
+ _initialized = true;
+
+ return TUSB_ERROR_NONE;
+}
+
+#if CFG_TUSB_OS == OPT_OS_NONE
+void tusb_task(void)
+{
+ #if TUSB_OPT_HOST_ENABLED
+ usbh_task(NULL);
+ #endif
+
+ #if TUSB_OPT_DEVICE_ENABLED
+ usbd_task(NULL);
+ #endif
+}
+#endif
+
+
+/*------------------------------------------------------------------*/
+/* Debug
+ *------------------------------------------------------------------*/
+#if CFG_TUSB_DEBUG
+char const* const tusb_strerr[TUSB_ERROR_COUNT] = { ERROR_TABLE(ERROR_STRING) };
+#endif
+
+#endif // host or device enabled
diff --git a/src/tusb.h b/src/tusb.h new file mode 100644 index 000000000..4d65c80e1 --- /dev/null +++ b/src/tusb.h @@ -0,0 +1,141 @@ +/**************************************************************************/
+/*!
+ @file tusb.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_H_
+#define _TUSB_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// INCLUDE
+//--------------------------------------------------------------------+
+#include "common/tusb_common.h"
+#include "tusb_hal.h"
+#include "osal/osal.h"
+#include "common/tusb_fifo.h"
+
+//------------- HOST -------------//
+#if TUSB_OPT_HOST_ENABLED
+ #include "host/usbh.h"
+
+ #if HOST_CLASS_HID
+ #include "class/hid/hid_host.h"
+ #endif
+
+ #if CFG_TUH_MSC
+ #include "class/msc/msc_host.h"
+ #endif
+
+ #if CFG_TUH_CDC
+ #include "class/cdc/cdc_host.h"
+ #endif
+
+ #if CFG_TUSB_HOST_CUSTOM_CLASS
+ #include "class/custom_host.h"
+ #endif
+
+#endif
+
+//------------- DEVICE -------------//
+#if TUSB_OPT_DEVICE_ENABLED
+ #include "device/usbd.h"
+
+ #if CFG_TUD_HID
+ #include "class/hid/hid_device.h"
+ #endif
+
+ #if CFG_TUD_CDC
+ #include "class/cdc/cdc_device.h"
+ #endif
+
+ #if CFG_TUD_MSC
+ #include "class/msc/msc_device.h"
+ #endif
+
+ #if CFG_TUD_CUSTOM_CLASS
+ #include "class/custom/custom_device.h"
+ #endif
+#endif
+
+
+//--------------------------------------------------------------------+
+// APPLICATION API
+//--------------------------------------------------------------------+
+/** \ingroup group_application_api
+ * @{ */
+
+// Initialize device/host stack according to tusb_config.h
+// return true if success
+bool tusb_init(void);
+
+#if CFG_TUSB_OS == OPT_OS_NONE
+/** \brief Run all tinyusb's internal tasks (e.g host task, device task).
+ * \note This function is only required when using no RTOS (\ref CFG_TUSB_OS == OPT_OS_NONE). All the stack functions
+ * & callback are invoked within this function. This should be called periodically within the mainloop
+ *
+ @code
+ int main(void)
+ {
+ your_init_code();
+ tusb_init();
+
+ // other config code
+
+ while(1) // the mainloop
+ {
+ your_application_code();
+
+ tusb_task(); // handle tinyusb event, task etc ...
+ }
+ }
+ @endcode
+ *
+ */
+void tusb_task(void);
+#endif
+
+/** @} */
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_H_ */
+
diff --git a/src/tusb_hal.h b/src/tusb_hal.h new file mode 100644 index 000000000..e02ff480d --- /dev/null +++ b/src/tusb_hal.h @@ -0,0 +1,64 @@ +/**************************************************************************/
+/*!
+ @file hal.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_HAL_H_
+#define _TUSB_HAL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// INCLUDES
+//--------------------------------------------------------------------+
+#include "common/tusb_common.h"
+
+//--------------------------------------------------------------------+
+// HAL API
+//--------------------------------------------------------------------+
+
+// Only required to implement if using No RTOS (osal_none)
+// TODO could be remove
+uint32_t tusb_hal_millis(void);
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _TUSB_HAL_H_ */
+
diff --git a/src/tusb_option.h b/src/tusb_option.h new file mode 100644 index 000000000..8b2e59b17 --- /dev/null +++ b/src/tusb_option.h @@ -0,0 +1,238 @@ +/**************************************************************************/
+/*!
+ @file tusb_option.h
+ @author hathach (tinyusb.org)
+
+ @section LICENSE
+
+ Software License Agreement (BSD License)
+
+ Copyright (c) 2013, hathach (tinyusb.org)
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holders nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+#ifndef _TUSB_OPTION_H_
+#define _TUSB_OPTION_H_
+
+#define TUSB_VERSION_YEAR 00
+#define TUSB_VERSION_MONTH 00
+#define TUSB_VERSION_WEEK 0
+#define TUSB_VERSION_NAME "alpha"
+#define TUSB_VERSION XSTRING_(TUSB_VERSION_YEAR) "." XSTRING_(TUSB_VERSION_MONTH)
+
+/** \defgroup group_mcu Supported MCU
+ * \ref CFG_TUSB_MCU must be defined to one of these
+ * @{ */
+#define OPT_MCU_LPC11UXX 1 ///< NXP LPC11Uxx
+
+#define OPT_MCU_LPC13XX 3 ///< NXP LPC13xx
+#define OPT_MCU_LPC175X_6X 4 ///< NXP LPC175x, LPC176x
+#define OPT_MCU_LPC177X_8X 5 ///< NXP LPC177x, LPC178x
+#define OPT_MCU_LPC18XX 6 ///< NXP LPC18xx
+#define OPT_MCU_LPC40XX 7 ///< NXP LPC40xx
+#define OPT_MCU_LPC43XX 8 ///< NXP LPC43xx
+
+#define OPT_MCU_NRF5X 100 ///< Nordic nRF5x series
+
+#define OPT_MCU_SAMD21 200 ///< MicroChip SAMD21
+#define OPT_MCU_SAMD51 201 ///< MicroChip SAMD51
+/** @} */
+
+/** \defgroup group_supported_os Supported RTOS
+ * \ref CFG_TUSB_OS must be defined to one of these
+ * @{ */
+#define OPT_OS_NONE 1 ///< No RTOS
+#define OPT_OS_FREERTOS 2 ///< FreeRTOS
+#define OPT_OS_MYNEWT 3 ///< Mynewt OS
+/** @} */
+
+
+// Allow to use command line to change the config name/location
+#ifndef CFG_TUSB_CONFIG_FILE
+ #define CFG_TUSB_CONFIG_FILE "tusb_config.h"
+#endif
+
+#include CFG_TUSB_CONFIG_FILE
+
+/** \addtogroup group_configuration
+ * @{ */
+
+//--------------------------------------------------------------------
+// CONTROLLER
+// Only 1 roothub port can be configured to be device and/or host.
+// tinyusb does not support dual devices or dual host configuration
+//--------------------------------------------------------------------
+/** \defgroup group_mode Controller Mode Selection
+ * \brief CFG_TUSB_CONTROLLER_N_MODE must be defined with these
+ * @{ */
+#define OPT_MODE_NONE 0x00 ///< Disabled
+#define OPT_MODE_DEVICE 0x01 ///< Device Mode
+#define OPT_MODE_HOST 0x02 ///< Host Mode
+#define OPT_MODE_HIGH_SPEED 0x10 ///< High speed
+/** @} */
+
+#ifndef CFG_TUSB_RHPORT0_MODE
+ #define CFG_TUSB_RHPORT0_MODE OPT_MODE_NONE
+#endif
+
+#ifndef CFG_TUSB_RHPORT1_MODE
+ #define CFG_TUSB_RHPORT1_MODE OPT_MODE_NONE
+#endif
+
+#if ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST)) || \
+ ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE))
+ #error "tinyusb does not support same modes on more than 1 roothub port"
+#endif
+
+// Which roothub port is configured as host
+#define TUH_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST) ? 1 : -1) )
+#define TUSB_OPT_HOST_ENABLED ( TUH_OPT_RHPORT >= 0 )
+
+// Which roothub port is configured as device
+#define TUD_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : -1) )
+
+#if TUD_OPT_RHPORT == 0
+#define TUD_OPT_HIGH_SPEED ( CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED )
+#else
+#define TUD_OPT_HIGH_SPEED ( CFG_TUSB_RHPORT1_MODE & OPT_MODE_HIGH_SPEED )
+#endif
+
+#define TUSB_OPT_DEVICE_ENABLED ( TUD_OPT_RHPORT >= 0 )
+
+
+//--------------------------------------------------------------------+
+// COMMON OPTIONS
+//--------------------------------------------------------------------+
+/**
+ determines the debug level for the stack
+ - Level 3: TBD
+ - Level 2: TBD
+ - Level 1: Print out if Assert failed. STATIC_VAR is NULL --> accessible when debugging
+ - Level 0: no debug information is generated
+*/
+#ifndef CFG_TUSB_DEBUG
+ #define CFG_TUSB_DEBUG 0
+ #warning CFG_TUSB_DEBUG is not defined, default value is 0
+#endif
+
+// place data in accessible RAM for usb controller
+#ifndef CFG_TUSB_MEM_SECTION
+#define CFG_TUSB_MEM_SECTION
+#endif
+
+#ifndef CFG_TUSB_MEM_ALIGN
+#define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4)
+#endif
+
+#ifndef CFG_TUSB_OS
+#define CFG_TUSB_OS OPT_OS_NONE
+#endif
+
+//--------------------------------------------------------------------
+// DEVICE OPTIONS
+//--------------------------------------------------------------------
+#if TUSB_OPT_DEVICE_ENABLED
+
+ #ifndef CFG_TUD_ENDOINT0_SIZE
+ #define CFG_TUD_ENDOINT0_SIZE 64
+ #endif
+
+ #ifndef CFG_TUD_CTRL_BUFSIZE
+ #define CFG_TUD_CTRL_BUFSIZE 256
+ #endif
+
+ #ifndef CFG_TUD_DESC_AUTO
+ #define CFG_TUD_DESC_AUTO 0
+ #endif
+
+ #ifndef CFG_TUD_CDC
+ #define CFG_TUD_CDC 0
+ #endif
+
+ #ifndef CFG_TUD_MSC
+ #define CFG_TUD_MSC 0
+ #endif
+
+ #ifndef CFG_TUD_HID_KEYBOARD
+ #define CFG_TUD_HID_KEYBOARD 0
+ #endif
+
+ #ifndef CFG_TUD_HID_MOUSE
+ #define CFG_TUD_HID_MOUSE 0
+ #endif
+
+ #ifndef CFG_TUD_HID_KEYBOARD_BOOT
+ #define CFG_TUD_HID_KEYBOARD_BOOT 0
+ #endif
+
+ #ifndef CFG_TUD_HID_MOUSE_BOOT
+ #define CFG_TUD_HID_MOUSE_BOOT 0
+ #endif
+
+#endif // TUSB_OPT_DEVICE_ENABLED
+
+//--------------------------------------------------------------------
+// HOST OPTIONS
+//--------------------------------------------------------------------
+#if TUSB_OPT_HOST_ENABLED
+ #ifndef CFG_TUSB_HOST_DEVICE_MAX
+ #define CFG_TUSB_HOST_DEVICE_MAX 1
+ #warning CFG_TUSB_HOST_DEVICE_MAX is not defined, default value is 1
+ #endif
+
+ //------------- HUB CLASS -------------//
+ #if CFG_TUH_HUB && (CFG_TUSB_HOST_DEVICE_MAX == 1)
+ #error there is no benefit enable hub with max device is 1. Please disable hub or increase CFG_TUSB_HOST_DEVICE_MAX
+ #endif
+
+ //------------- HID CLASS -------------//
+ #define HOST_CLASS_HID ( CFG_TUH_HID_KEYBOARD + CFG_TUH_HID_MOUSE + CFG_TUSB_HOST_HID_GENERIC )
+
+ #ifndef CFG_TUSB_HOST_ENUM_BUFFER_SIZE
+ #define CFG_TUSB_HOST_ENUM_BUFFER_SIZE 256
+ #endif
+
+ //------------- CLASS -------------//
+#endif // TUSB_OPT_HOST_ENABLED
+
+
+//------------------------------------------------------------------
+// Configuration Validation
+//------------------------------------------------------------------
+
+#if (CFG_TUSB_OS != OPT_OS_NONE) && !defined (CFG_TUD_TASK_PRIO)
+ #error CFG_TUD_TASK_PRIO need to be defined (hint: use the highest if possible)
+#endif
+
+#if CFG_TUD_ENDOINT0_SIZE > 64
+ #error Control Endpoint Max Packet Size cannot be larger than 64
+#endif
+
+#endif /* _TUSB_OPTION_H_ */
+
+/** @} */
|
