~linux device-driven USB host and device driver

Source: Internet
Author: User

    • If I can't accompany you to the end
    • Do you regret that we were holding hands
    • If I hadn't met you
    • Now, I
    • Where to stay
    • All love is an adventure.
    • That would be willingly.
    • Waiting for all the suspense in our lives
    • My passionately devoted lover.
    • She's my lover.
    • The love she gave me was like
    • The morning with the dew
    • How I want to give her my true
    • My dearly Beloved.
    • I want to be lonely for her
    • Like the night is deep

This chapter from the host side angle to see the USB host controller driver and device driver from the host side of the point of view, the need to write USB drivers include host controller driver and device driver, USB host Controller Driver program is inserted into the USB device, and USB The device driver controls how the device communicates with the host as a slave device.

1. Linux USB Drive Hierarchy

1.1 Host side and device side USB drive

USB uses a tree topology, with only one host controller on each bus that coordinates the communication between the host and the device, and the device cannot proactively send any messages to the host.

1.2 Device, configuration, port, end Point

In the logical organization of USB devices, there are 4 levels of devices, configurations, interfaces, and endpoints, each USB device provides different levels of configuration information, can contain one or more configurations, different configurations make the device exhibit different functional combinations, configuration consists of multiple interfaces, the interface consists of multiple endpoints, Represents a basic function that is a USB device driver-controlled object, as a relationship between USB devices, configurations, interfaces, and endpoints.

Device descriptors: General information about the device, such as the vendor ID, Product ID, and revision ID, the supported device classes, subclasses and applicable protocols, and the maximum packet size for the default endpoint. In the Linux kernel, the USB device is described by the usb_device structure, and the USB device descriptor is defined as the usb_device_descriptor structure, with the following code:

struct USB Device Descriptor   {       _ _u8 blength;//Descriptor Length       _ _u8 bdescriptortype;//Descriptor Type Number          _ _le16 bcdusb;//u SB Version Number       _ _u8 bdeviceclass;//usb assigned device Class Code       _ _u8 bdevicesubclass;//USB assigned Subclass Code       _ _u8 Bdeviceprotocol; USB Assigned Protocol Code       _ _u8 bMaxPacketSize0;//endpoint0 Maximum Packet size        _ _LE16 Idvendor;//Manufacturer number          _ _le16 idproduct;//Product Code 
   _ _le16 Bcddevice; Device Factory Number           _ _u8  imanufacturer;//The index of the manufacturer string          _ _u8  iproduct;//The Index of the product string          _ _u8  Iserialnumber; The index of the device serial number string       _ _u8 bnumconfigurations;//number of possible configurations   

Configuration descriptors: The number of interfaces in this configuration, the supported suspend and resume capabilities, and the power requirements. The USB configuration is described in the kernel using the USB_HOST_CONFIG structure, and the USB configuration descriptor is defined as the struct usb_config_descriptor, with the following code:

struct USB Config descriptor  {     _ _u8 blength;//Descriptor Length     _ _u8 bdescriptortype;//Descriptor Type Number     _ _le16 wtotallengt H Configure the size of all data returned by     _u8 bnuminterfaces;/////configuration of the number of interfaces supported     _ _U8 bconfigurationvalue; The parameter values     required for the//set configuration command _ _u8  iconfiguration;//The index value of the configured string _     _ U8 bmattributes;//selection of power supply mode      _ _u8 bmaxpower;//The maximum current that the device extracts from the bus  

Interface descriptors: interface classes, subclasses, and applicable protocols, number of interface alternate configurations, and number of endpoints. The USB interface is described in the kernel using the USB_INTERFACE structure, and the USB interface descriptor is defined as the struct usb_interface_descriptor, with the following code:

struct USB Interface Descriptor       {        _ _u8 blength;            Descriptor Length        _ _u8 bdescriptortype;//Descriptor Type        _ _ U8 Binterfacenumber;     Interface Number        _ _u8 balternatesetting;//Alternate Interface Descriptor number        _ _u8 bnumendpoints;        The number of end points used by the interface, not including the endpoint 0                  _ _ U8 Binterfaceclass;      Interface Type                  _ _ U8 Binterfacesubclass;//Interface Subtype                 _ _ U8 Binterfaceprotocol;//interface followed by the protocol          _ _ U8  iinterface; The string index value of the interface      

Endpoint Descriptor: The endpoint address, direction, and type, the maximum supported packet size, and, if the endpoint of the break type, also includes the polling frequency. In the Linux kernel, the U SB endpoint is described using the USB_HOST_ENDPOINT structure, and the USB endpoint descriptor is defined as the Usb_ endpoint_ descriptor struct, with the following code:

struct USB Endpoint Descriptor       {        _ _u8 blength;//Descriptor Length        _ _u8 bdescriptortype;//Descriptor Type        _ _u8  bendpoint Address; Endpoint Address: 0-bit is the endpoint number, the 7th bit is the direction (0-out,1-in)               _ _ U8 bmattributes;//Endpoint properties: Bit[0:1] with a value of 00 for control, 01 for synchronization, 02 for bulk, and 03 for _                 _ Le16 wmaxpacketsize; The size of the maximum packet received or sent by this endpoint                _ _u8 binterval;      Polling the time interval for the data delivery endpoint//For the end of the bulk transfer, and for the endpoint that controls the transfer, this domain must be 1//for the endpoint that is being transferred, the domain                             value is                             1~255                _ _u8 Brefresh;        _ _u8 bsynchaddress;      

String descriptors: In other descriptors, string indexes are provided for some fields, which are used to retrieve descriptive strings that can be provided in multiple languages. String descriptors are optional, some devices have, and some do not, and string descriptors correspond to the Usb_string_ descriptor struct, whose code is as follows:

struct USB String Descriptor       {         _ _u8 blength;//Descriptor Length         _ _u8 bdescriptortype;//Descriptor Type         _ _le16 wdata [1];
   /* encoded with Utf-16le */       

2 USB Host Drive

  USB host controllers are available in 3 sizes: OHCI (Open Host controller Interface), UHCI (Universal hosts controller Interface) and EHCI (Enhanced host Co Ntroller Interface).

2.1 Host Controller Driver

In the Linux kernel, the USB_HCD structure is used to describe the USB host controller driver, which contains the "housework" information of the USB host controller, the hardware resources, the status description and the Hc_driver for operating the host controller, and its code is as follows:

struct USB HCD {/* manage "housework" */struct USB bus self; const CHAR *product desc; /* Product/Vendor String */char IRQ DESCR [24]; /* driver + bus # */struct timer list RH timer; /* Root Hub Polling */struct URB *status urb; /* Current STATUS URB */* Hardware Information/status */const struct HC driver *driver;                                 /* Hardware-specific hook function */* flag to be maintained */unsigned long flags;               #define HCD flag HW ACCESSIBLE 0x00000001 #define HCD FLAG SAW IRQ 0x00000002 unsigned rh_registered:1; /* Root hub registration?                                 */* The use of the next logo is only an "equity", and when all Hcds support the new root hub polling mechanism, the */unsigned uses new polling:1 will be removed; Unsigned poll rh:1; /* Poll root hub status? */unsigned poll pending:1; /* Status has changed? */int IRQ; /* The Assigned IRQ */
void _ _iomem *regs; /* Device memory and I/O */u64 rsrc start; /* Memory and I/O resource start position */U64 rsrc Len; /* Memory and I/O resource length */unsigned power budget; /* MA, 0 = unrestricted */#define HCD buffer pools 4 struct DMA pool *POOL[HCD buffer pools]; int state; #define ACTIVE 0x01 #define SUSPEND 0x04 #define TRANSIENT 0X80 #define HC State HALT 0 #define HC State RUNNING (ACTIVE) #define HC State quiescing (suspend| Transient| ACTIVE) #define HC State RESUMING (suspend| TRANSIENT) #define HC State SUSPENDED (SUSPEND) #define HC was RUNNING (state) & ACTIVE) #define HC is SUSPENDED (state) & SUSPEND/*/Host Controller-driven private data */
unsigned long HCD priv [0] attribute ((aligned (sizeof (unsigned long))); };

The following functions are used to create HCD in Linux:

struct usb hcd *usb Create HCD (conststruct HC driver *driver,                                          struct C6>char

The following functions are used to add and remove:

int usb add HCD (struct usb HCD *intlongvoid USB Remove HCD (struct USB HCD *

2.2 OHCI Host Controller Driver

The OHCI HCD driver is an instance of the HCD driver, which defines a OHCI_HCD structure that can be used to convert USB_HCD and OHCI_HCD using the following inline function:

struct ohci hcd *hcd to OHCI (struct usb HCD *HCD);    struct usb hcd *ohci to HCD (conststruct

Getting OHCI_HCD from USB_HCD only obtains "private" data, and USB_HCD from OHCI_HCD is derived from struct members by container_of (), using the following function to initialize the OHCI host controller:

int OHCI init (struct

The following functions are used to open, stop, and reset the OHCI controller, respectively:

int ohci run (struct ohci hcd *void ohci stop (struct usb HCD *V OID OHCI USB reset (struct ohci hcd *ohci);

3 USB Device Driver

3.1 USB device drives the overall structure

The following device classes are available

    • Audio Device class.
    • Communication Equipment class.
    • HID (Human-machine interface) device class.
    • Displays the device class.
    • Mass storage device class.
    • Power Device class.
    • Print the device class.
    • The Hub device class.

The Linux kernel assigns the appropriate device number to various USB devices, and the USB device file system (Usbdevfs,linux 2.6 to USBFS, or USB file system) is provided in the kernel, and it is generated dynamically, similar to/proc. By adding the following line to the/etc/fstab file:

or enter a command:

Mount-t Usbfs None/proc/bus/usb

USB Device file system can be mounted.

In addition, the Sysfs file system also contains a description of the USB-related information, but is limited to the interface level. The USB device and USB interface are represented as separate USB devices in the SYSFS, with the following directory naming rules:

Root hub-Hub port number (-Hub port number-... ): Configure. Interface.

3.2 USB Request block (URB)

USB Request block (USB requests block,urb) is a USB device driver used to describe the communication with the USB device basic carrier and core data structure, very similar to the network device driver in the SK_BUFF structure, is the USB host and device Communication "Radio", URB structure , the code is as follows:

struct URB {/* Private: Fields accessible only by USB core and host controller */struct KREF kref;/*urb citation With Count */Spinlock T lock; /* URB lock */void *hcpriv; /* Host Controller private data */int bandwidth; /* Int/iso The requested bandwidth */atomic t use count; /* Concurrent Transfer count */U8 reject; /* Transmission will fail */* Public: Fields that can be driven using */struct list head URB list; /* List header */struct USB device *dev; /* Associated USB device */unsigned int pipe; /* Pipe information */INT status; /* Current Status of URB */unsigned int transfer flags; /* URB Short not OK | ...*/ 

void *transfer buffer; /* buffer to send data to device or receive data from device */

DMA addr T Transfer DMA; /* buffer used to transfer data to the device in DMA mode */

int transfer buffer Length;/*transfer buffer or transfer DMA points to the size of the buffers */

int actual length; /* The actual length of the data sent or received after the URB is finished */

unsigned char *setup packet; /* Pointer to the settings packet that controls URB */

DMA addr T Setup DMA; /* Control the DMA buffer of the URB settings packet */

int start frame; /* used to set or return the initial frame in transmission */

int number of packets; /* Medium-time buffer data transmission at equal time */
int interval; /* Urb The interval to be polled (valid for medium and URB) */

int error count; /* Number of transmission errors */
void *context; /* Completion Function Context */

USB complete T complete; /* Called when URB is fully transmitted or an error occurs.

struct USB ISO packet descriptor ISO frame DESC[0];
/* A single URB can define multiple equal-time transmissions at one time, describing each of the transmission of equal time */

};

Each endpoint in a USB device processes a URB queue, and the typical life cycle of a URB has the following processes before the queue is emptied:

    1. Created by a USB device driver
    2. Initialized, assigned to a specific endpoint of a particular USB device
    3. USB device driver submitted to USB
    4. Submit the USB host controller driver specified by the USB core.
    5. is handled by the USB host controller and is transmitted once to the USB device.
    6. USB Host Controller driver notifies USB device driver when URB is complete

3.3 Simple batch and control URB

1) usb_bulk_msg ()

The Usb_bulk_msg () function creates a USB bulk URB and sends it to a specific device, which is synchronous and waits until the URB is complete before returning. The prototype of the USB_BULK_MSG () function is:

int USB bulk msg (structintvoidintint *actual length,  int

If the function call succeeds, returns 0; otherwise, 1 negative error values are returned.

2) usb_control_msg () function

The Usb_control_msg () function is similar to the usb_bulk_msg () function, but it provides the ability to drive and end USB control information rather than bulk information, and the prototype of the function is:

int USB control msg (structint  pipe,        void *int timeout); Dev points to the USB device to which the control message is sent, the pipe is the endpoint of the USB device to which the message is to be sent, request is the USB request value for this control message, and RequestType is the USB request type for this control message, and//value is the USB Value, index is the USB message index value for this control message, which points to the data buffer to be sent or received                 , size

3) probing and disconnecting functions

In the probe function of USB device driver Usb_driver structure, the following work should be done:

    • Probe the device's endpoint address, buffer size, and initialize any data structures that might be used to control the USB device.
    • Save the initialized data structure to the interface device
    • Registering a USB device

The invocation of the probe function occurs when the USB device is installed and the USB core considers the driver to correspond to the installed USB device (Usb_driver's id_table member is at this point), while the call to the Disconnect function occurs when the driver no longer controls the device for a variety of reasons. The calls to both functions are made in the kernel thread.

4) USB Skeleton Program

The driver/usb/usb-skeleton.c file in the source code of the Linux kernel provides us with one of the most basic USB drivers, the USB skeleton program, which can be seen as the simplest example of a USB device driver. Although USB driver drivers vary widely, skeleton programs are original aim. I don't have a lot of introductions here.

All rights reserved, reprint please specify reprint address: http://www.cnblogs.com/lihuidashen/p/4521915.html

~linux device-driven USB host and device driver

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.