# USB note ## USB protocol In most USB controller ICs, the protocol part would be taken care of by the controller. Each USB transaction consists of a - Token Packet (header defining what it expects to follow), an - Optional Data Packet, (containing the payload) and a - Status Packet (Used to acknoledge tansactions and to provide a means of error correction) One Transaction: |Token | Data(Optional) | Status | | -------- | --------|--------| ## Common USB Packet fields Data on USB bus is transmitted **LSB** first - Sync All packets must start with a sync field. The sync field is **8 bits** long at low and full speed or **32 bits** long for high speed and is used to synchronise the clock of the receiver with that of the transmitter. The last two bits indicate where the PID fields starts. - PID PID stands for Packet ID. This field is used to identify the type of packet that is being sent. The following table shows the possible values. | Group | PID Value | Packet Identifier | | -------- | -------- | -------- | | Token | 0001 | OUT token | | | 1001 | In Token | | | 0101 | SOF Token | | | 1101 | SETUP Token | | Group | 0011 | DATA0 | | | 1011 | DATA1 | | | 0111 | DATA2 | | | 1111 | MDATA | | Handshake | 0010 | ACK Handshake | | | 1010 | NAK Hnadshake | | | 1110 | STALL Handshake | | | 0110 | NYET(No response yet)| | Special | 1100 | PREamble | | | 1100 | ERR | | | 1000 | Split | | | 0100 | Pint | There are 4 bits to the PID, however to insure it is received correctly, the 4 bits are complemented and repeated, making an 8 bit PID in total. The resulting format is shown below. | PID0 | PID1 | PID2 | PID3 | nPID0 | nPID1 | nPID2 | nPID3 | | -------- | --------| --------|-------- | --------| --------|--------| --------| - ADDR The address field specifies which device the packet is designated for. Being 7 bits in length allows for **127** devices to be supported. **Address 0 is not valid**, as any device which is not yet assigned an address must respond to packets sent to address zero. - ENDP The endpoint field is made up of 4 bits, allowing 16 possible endpoints. Low speed devices, however can only have 2 additional endpoints on top of the default pipe. (4 endpoints max) - CRC Cyclic Redundancy Checks are performed on the data within the packet payload. All token packets have a 5 bit CRC while data packets have a 16 bit CRC. - EOP End of packet. Signalled by a Single Ended Zero (SE0) for approximately 2 bit times followed by a J for 1 bit time. ## USB Packet Types - Token Packets There are three types of token packets, - In: Informs the USB device that the host wishes to read information. - Out: Informs the USB device that the host wishes to send information. - Setup: Used to begin control transfers. Token Packets must conform to the following format, | Sync | PID | ADDR | ENDP | CRC5 | EOP | | ------- | -------| --------| -------- | ------- | -------| - Data Packets There are two types of data packets each capable of transmitting up to 1024 bytes of data. - Data0 - Data1 High Speed mode defines another two data PIDs, DATA2 and MDATA. Data packets have the following format, | Sync | PID | Data | CRC16 | EOP | | -------- | --------| --------|-------- | --------| - Handshake Packets There are three type of handshake packets which consist simply of the PID - ACK - Acknowledgment that the packet has been successfully received. - NAK - Reports that the device temporary cannot send or received data. Also used during interrupt transactions to inform the host there is no data to send. - STALL - The device finds its in a state that it requires intervention from the host. Handshake Packets have the following format, | Sync | PID | EOP | | -------- | --------|--------| - Start of Frame Packets The SOF packet consisting of an 11-bit frame number is sent by the host every 1ms ± 500ns on a full speed bus or every 125 µs ± 0.0625 µs on a high speed bus. | Sync | PID | Frame Number | CRC5 | EOP | | -------- | --------| --------|-------- | --------| ## Endpoint Endpoints can be described as sources or sinks of data. As the bus is host centric, endpoints occur at the end of the communications channel at the USB function. At the software layer, your device driver may send a packet to your devices EP1 for example. As the data is flowing out from the host, it will end up in the EP1 OUT buffer. Your firmware will then at its leisure read this data. If it wants to return data, the function cannot simply write to the bus as the bus is controlled by the host. Therefore it writes data to EP1 IN which sits in the buffer until such time when the host sends a IN packet to that endpoint requesting the data. Endpoints can also be seen as the interface between the hardware of the function device and the firmware running on the function device. All devices must support endpoint **zero**. This is the endpoint which receives all of the devices control and status requests during enumeration and throughout the duration while the device is operational on the bus. ## Pipe A pipe is a logical connection between the host and endpoint(s). Pipes will also have a set of parameters associated with them such as how much bandwidth is allocated to it, what transfer type (Control, Bulk, Iso or Interrupt) it uses, a direction of data flow and maximum packet/buffer sizes. USB defines two types of pipes: - Stream Pipes No defined USB format Data flows sequentially and has a pre-defined direction, either in or out. Stream pipes will support bulk, isochronous and interrupt transfer types. Stream pipes can either be controlled by the host or device. - Message Pipes Have a defined USB format Host controlled, which are initiated by a request sent from the host. Data is then transferred in the desired direction, dictated by the request. Therefore message pipes allow data to flow in both directions but will only support control transfers. ## Endpoint Type - Type: - Control transfers Control transfers are typically used for command and status operations Essential to set up a USB device with all enumeration functions being performed using control transfers. Packet length: low speed devices must be 8 bytes, high speed devices allow a packet size of 8, 16, 32 or 64 bytes and full speed devices must have a packet size of 64 bytes. A control transfer can have up to three stages: 1. Setup Stage The setup token is sent first which contains the address and endpoint number. The data packet is sent next and always has a PID type of data0 and includes a setup packet which details the type of request. We detail the setup packet later. The last packet is a handshake used for acknowledging successful receipt or to indicate an error. If the function successfully receives the setup data (CRC and PID etc OK) it responds with ACK, otherwise it ignores the data and doesn’t send a handshake packet. ![](https://i.imgur.com/aREZzFV.png) 2. Data Stage (Optional) Consists of one or multiple IN or OUT transfers. The setup request indicates the amount of data to be transmitted in this stage. If it exceeds the maximum packet size, data will be sent in multiple transfers each being the maximum packet length except for the last packet. ![](https://i.imgur.com/dJFlXeF.png) When the host is ready to receive control data it issues an IN Token. If the function receives the IN token with an error e.g. the PID doesn't match the inverted PID bits, then it ignores the packet. If the token was received correctly, the device can either reply with a DATA packet containing the control data to be sent, a stall packet indicating the endpoint has had a error or a NAK packet indicating to the host that the endpoint is working, but temporarily has no data to send. When the host needs to send the device a control data packet, it issues an OUT token followed by a data packet containing the control data as the payload.If any part of the OUT token or data packet is corrupt then the function ignores the packet. If the function's endpoint buffer was empty and it has clocked the data into the endpoint buffer it issues an ACK informing the host it has successfully received the data. If the endpoint buffer is not empty due to processing of the previous packet, then the function returns a NAK. However if the endpoint has had a error and its halt bit has been set, it returns a STALL. 3. Status Stage Reports the status of the overall request and this once again varies due to direction of transfer. Status reporting is always performed by the function. If the host sent IN token(s) during the data stage to receive data, then the host must acknowledge the successful recept of this data. This is done by the host sending an OUT token followed by a zero length data packet. The function can now report its status in the handshaking stage. An ACK indicates the function has completed the command is now ready to accept another command. If an error occurred during the processing of this command, then the function will issue a STALL. However if the function is still processing, it returns a NAK indicating to the host to repeat the status stage later. If the host sent OUT token(s) during the data stage to transmit data, the function will acknowledge the successful recept of data by sending a zero length packet in response to an IN token. However if an error occurred, it should issue a STALL or if it is still busy processing data, it should issue a NAK asking the host to retry the status phase later. ![](https://i.imgur.com/L3NitEx.png) **Example of control transfer: the Host wants to request a device descriptor during enumeration** The host will send the Setup token telling the function that the following packet is a Setup packet. The Address field will hold the address of the device the host is requesting the descriptor from. The endpoint number should be zero, specifying the default pipe. The host will then send a DATA0 packet. This will have an 8 byte payload which is the Device Descriptor Request as outlined in Chapter 9 of the USB Specification. The USB function then acknowledges the setup packet has been read correctly with no errors. If the packet was received corrupt, the device just ignores this packet. The host will then resend the packet after a short delay. ![](https://i.imgur.com/up7j2eH.png) The above three packets represent the first USB transaction. The USB device will now decode the 8 bytes received, and determine if it was a device descriptor request. The device will then attempt to send the Device Descriptor, which will be the next USB transaction. ![](https://i.imgur.com/HgquC3b.png) In this case, we assume that the maximum payload size is 8 bytes. The host sends the IN token, telling the device it can now send data for this endpoint. As the maximum packet size is 8 bytes, we must split up the 12 byte device descriptor into chunks to send. Each chunk must be 8 bytes except for the last transaction. The host acknowledges every data packet we send it. Once the device descriptor is sent, a status transaction follows. If the transactions were successful, the host will send a zero length packet indicating the overall transaction was successful. The function then replies to this zero length packet indicating its status. ![](https://i.imgur.com/ZNhbo0P.png) USB OUT transfer illustration ![](https://i.imgur.com/v9CneuB.png) SETUP tokens are unique to CONTROL transfers. They preface eight bytes of data from which the peripheral decodes host device requests. At full-speed, start of frame (SOF) tokens occur once per millisecond. At high speed, each frame contains eight SOF tokens, each denoting a 125-µs microframe. Four handshake PIDs indicate the status of a USB transfer: ACK (Acknowledge) means 'success'; the data is received error-free. NAK (Negative Acknowledge) means 'busy, try again.' STALL means that something is wrong (probably as a result of miscommunication or lack of cooperation between the host and device software). A device sends the STALL handshake to indicate that it does not understand a device request, that something went wrong on the peripheral end, or that the host tried to access a resource that was not there. It is similar to HALT, but better, because USB provides a way to recover from a stall. NYET (Not Yet) has the same meaning as ACK the data was received error-free but also indicates that the endpoint is not yet ready to receive another OUT transfer. NYET PIDs occur only in high-speed mode. A PRE (Preamble) PID precedes a low-speed (1.5 Mbps) USB transmission ![](https://i.imgur.com/o3cudH0.png) ![](https://i.imgur.com/swaREXh.png) - Interrupt transfers * Guaranteed Latency * Stream Pipe - Unidirectional * Error detection and next period retry. * IN: The host will periodically poll the interrupt endpoint. This rate of polling is specified in the endpoint descriptor * OUT: When the host wants to send the device interrupt data, it issues an OUT token followed by a data packet containing the interrupt data. ![](https://i.imgur.com/m528lIQ.png) - Isochronous transfers * Guaranteed access to USB bandwidth. * Bounded latency. * Stream Pipe - Unidirectional * Error detection via CRC, but no retry or guarantee of delivery. * Full & high speed modes only. * No data toggling. - Bulk transfers Bulk transfers can be used for large bursty data. Such examples could include a print-job sent to a printer or an image generated from a scanner. Bulk transfers provide error correction in the form of a **CRC16** field on the data payload and error detection/re-transmission mechanisms ensuring data is transmitted and received without error. Bulk transfers will use spare un-allocated bandwidth on the bus after all other transactions have been allocated. If the bus is busy with isochronous and/or interrupt then bulk data may slowly trickle over the bus. As a result Bulk transfers should only be used for **time insensitive** communication as there is no guarantee of latency. 1. Used to transfer large bursty data. 2. Error detection via CRC, with guarantee of delivery. 3. No guarantee of bandwidth or minimum latency. 4. Stream Pipe - Unidirectional 5. Full & high speed modes only For full speed endpoints, the maximum bulk packet size is either 8, 16, 32 or 64 bytes long. For high speed endpoints, the maximum packet size can be up to 512 bytes long. If the data payload falls short of the maximum packet size, it doesn't need to be padded with zeros. A bulk transfer is considered complete when it has transferred the exact amount of data requested, transferred a packet less than the maximum endpoint size, or transferred a zero-length packet. ![](https://i.imgur.com/b0xL1c2.png) ## USB Descriptors All USB devices have a hierarchy of descriptors which describe to the host information such as what the device is, who makes it, what version of USB it supports, how many ways it can be configured, the number of endpoints and their types etc The more common USB descriptors are: * Device Descriptors * Configuration Descriptors * Interface Descriptors * Endpoint Descriptors * String Descriptors ![](https://i.imgur.com/hNidU1M.png) USB devices can only have **one device descriptor**. The device descriptor includes information such as what USB revision the device complies to, the Product and Vendor IDs used to load the appropriate drivers and the number of possible configurations the device can have. The number of configurations indicate how many configuration descriptors branches are to follow. The configuration descriptor specifies values such as the amount of power this particular configuration uses, if the device is self or bus powered and the number of interfaces it has. When a device is enumerated, the host reads the device descriptors and can make a decision of which configuration to enable. It can only enable one configuration at a time. While USB offers this flexibility, very few devices have more than 1 configuration. The interface descriptor could be seen as a header or grouping of the endpoints into a functional group performing a single feature of the device. For example you could have a multi-function fax/scanner/printer device. Interface descriptor one could describe the endpoints of the fax function, Interface descriptor two the scanner function and Interface descriptor three the printer function. Unlike the configuration descriptor, there is no limitation as to having only one interface enabled at a time. A device could have 1 or many interface descriptors enabled at once. * Device Descriptors A USB device can only have one device descriptor. It specifies some basic, yet important information about the device such as the supported USB version, maximum packet size, vendor and product IDs and the number of possible configurations the device can have. ![](https://i.imgur.com/Fem8cLq.png) ***bcdUSB*** field reports the highest version of USB the device supports. The value is in binary coded decimal with a format of 0xJJMN where JJ is the major version number, M is the minor version number and N is the sub minor version number. e.g. USB 2.0 is reported as 0x0200, USB 1.1 as 0x0110 and USB 1.0 as 0x0100. The ***bcdDevice*** has the same format than the ***bcdUSB*** and is used to provide a device version number. This value is assigned by the developer. * Configuration Descriptors The configuration descriptor specifies how the device is powered, what the maximum power consumption is, the number of interfaces it has. Therefore it is possible to have two configurations, one for when the device is bus powered and another when it is mains powered. ![](https://i.imgur.com/pkasRy1.png) ***bMaxPower*** defines the maximum power the device will drain from the bus. This is in 2mA units, thus a maximum of approximately 500mA can be specified. The specification allows a high powered bus powered device to drain no more than 500mA from Vbus. If a device loses external power, then it must not drain more than indicated in ***bMaxPower***. It should fail any operation it cannot perform without external power. * Interface Descriptors The interface descriptor could be seen as a header or grouping of the endpoints into a functional group performing a single feature of the device. ![](https://i.imgur.com/WJeNbtl.png) ***bInterfaceNumber*** indicates the index of the interface descriptor. This should be zero based, and incremented once for each new interface descriptor. ***bAlternativeSetting*** can be used to specify alternative interfaces. These alternative interfaces can be selected with the Set Interface request. ***bNumEndpoints*** indicates the number of endpoints used by the interface. This value should exclude endpoint zero and is used to indicate the number of endpoint descriptors to follow. ***bInterfaceClass***, ***bInterfaceSubClass*** and ***bInterfaceProtocol*** can be used to specify supported classes (e.g. HID, communications, mass storage etc.) This allows many devices to use class drivers preventing the need to write specific drivers for your device. ***iInterface*** allows for a string description of the interface. * Endpoint Descriptors Endpoint descriptors are used to describe endpoints other than endpoint zero. Endpoint zero is always assumed to be a control endpoint and is configured before any descriptors are even requested. ![](https://i.imgur.com/laZbTfl.png) * String Descriptors String descriptors provide human readable information and are optional. If they are not used, any string index fields of descriptors must be set to zero indicating there is no string descriptor available. ![](https://i.imgur.com/BLptD4G.png) The above String Descriptor shows the format of String Descriptor Zero. The host should read this descriptor to determine what languages are available. If a language is supported, it can then be referenced by sending the language ID in the wIndex field of a Get Descriptor(String) request. All subsequent strings take on the format below, ![](https://i.imgur.com/cCtViHC.png) ## Setup Packet Each request starts with a 8 byte long Setup Packet which has the following format ![](https://i.imgur.com/hI29aIr.png) ## Transaction ![](https://i.imgur.com/9g3iikj.png) ## Frame ![](https://i.imgur.com/wMdy8nW.png) ## USB 3.0 versus USB 2.0 ![](https://i.imgur.com/OB1xJXL.png) ![](https://i.imgur.com/DoqzYOx.png) ## Reference Link [USB in a nutshell](https://www.beyondlogic.org/usbnutshell/usb1.shtml) [淺談 USB 通訊架構之定義(一)](http://fred-zone.blogspot.com/2009/08/usb.html) [淺談 USB 通訊架構之定義(二)](http://fred-zone.blogspot.com/2009/08/usb_10.html) [USB簡介 6](http://pollos-blog.blogspot.com/2014/07/usb-6.html) [USB 列舉教學,詳解](https://wwssllabcd.github.io/blog/2012/11/28/usb-emulation/) [Cypress USB](https://www.cypress.com/file/124386/download) ###### tags: `USB` `HID`