Linux USB驱动详解

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshowhtml

也欢迎你们转载本篇文章。分享知识,造福人民,实现咱们中华民族伟大复兴!linux

               

 

原文地址:http://blog.csdn.net/chenjin_zhong/article/details/6329316web

1.Linux usb设备驱动框架数组

USB是通用串行总线的总称,Linux内核几乎支持全部的usb设备,包括键盘,鼠标,打印机,modem,扫描仪。Linux的usb驱动分为主机驱动与gadget驱动。前者是设备链接到计算机上,经过主机驱动扫描usb设备,控制所链接的设备。而gadget驱动通常用于嵌入式设备,gadget驱动用于控制嵌入式设备。Linux的usb驱动两种类型图以下:网络

  

左侧是usb的主机驱动,右侧是gadget驱动。下面着重介绍一下usb的主机驱动:数据结构

(1)usb主机控制器-直接与硬件设备交互。app

(2)usb core-向usb设备驱动提供API以及usb主机控制器驱动的程序。使用usb core所提供的函数,宏来完成数据处理的功能。框架

(3)usb设备驱动,即usb接口驱动,通常所说的usb驱动指的是usb接口驱动less

  

2.usb系统的组成部分electron

usb系统通常由三个部分组成,主机,一个或多个usb hub,以及与之些hub链接的usb设备。

(1)主机

在任何的usb系统中仅有一个主机,主机系统中的usb接口即上图中的主机控制器,主机控制器可由硬件,软件或固件组成。主机主要负责:

a.检测usb设备的链接与拆除

b.管理主机与usb设备之间的控制流

c.管理主机与usb设备之间的数据流

d.收集状态和活动的统计

e.为链接的usb设备提供电源

 

 

(2)usb设备

全部的usb设备都是经过地址来存取的,这个地址在链接或枚举时分配。usb设备对usb系统来讲是端点的集合,一组端点实现一个接口。设备端点是usb设备中惟一可寻址的部分。它是主机与设备之间通讯流的结束点。一系列的相互独立的端点构成了usb逻辑设备。每一个端点支持流进设备或者是流出设备。

主机与设备端点上的usb数据传输是经过管道的方式。

 

(3)hub

全部的usb device都链接在hub端口上。

 

 

 

3. usb传输模式

 

(1)控制传输模式(Control)

控制传输模式支持双向传输,用来处理从usb主机端口到usb设备端口的数据传输,用于控制指令,设备状态查询以及确认命令。

 

(2)等时传输方式(lsochronous)

等时传输是一种周期性的连续性的意向传输模式,一般用于对时间有着密切关系的信息的传输,对准确性要求不高,但对时间要求极为敏感的设备,如视频,音频的传输。

 

(3)中断传输模式(Interrupt)

中断传输模式用于非周期性的,天然发生的,数据量小的传输,数据传输的方向是从设备到主机。如usb键盘和鼠标

 

(4)批量传输模式(bulk)

批量传输模式是一种单向的,用于大量数据传输的模式,该方式用来传输正确无误的数据。一般打印机,扫描仪,数码相机以这种方式与主机链接

 

 

4. usb设备组成

(1)一个usb设备由能够有一个或多个配置

(2)一个配置一般能够有一个或多个接口

(3)一个接口一般能够有一个或多个端点

一般所尽的usb设备驱动是指接口驱动,即一个接口对应一个驱动。

因此Linux usb设备有四大描述符,分别为设备描述符,配置描述符,接口描述符,端点描述符。下面看一个这几个描述符的相关数据结构:

 

 

struct usb_device_descriptor

{
      _u8 bLength;  //此描述符的字节数
      _u8  bDescriptorType; //描述符的种类为设备
      _u16 bcdUSB;  //此设备与描述符兼容的usb设备说明版本号(BCD码)
      _u8   bDeviceClass; //设备类码
      _u8   bDeviceSubClass; //设备子类码
      _u8   bDeviceProtocol; //协议码
      _u8   bMaxPacketSize0; //端点0的最大包大小
      _u16 idVendor; //厂商标志
      _u16  idProduct; //产品标志
      _u16 bcdDevice; //设备发行号
      _u8   iManufacturer; //描述厂商的字串索引

      _u8   iProduct; //描述产品信息的字串索引

      _u8  iSerialNumber; //描述设备序列号信息的字串索引
      _u8  bNumConfigurations;//此设备支持的配置数

  }_attribute_ ((packed));

 

设备类码的典型值以下:

 

#define USB_CLASS_PER_INTERFACE 0

#define USB_CLAS_AUDIO 1     //声音设备

#define USB_CLASS_COMM 2   // 调制解调器,网卡,ISDN链接

#define USB_CLASS_HID  3    //HID设备,如鼠标,键盘

#define USB_CLASS_PHYSICAL 5 //物理设备

#define USB_CLASS_STILL_IMAGE 6 //静止图像捕捉设备

#define USB_CLASS_PRINTER 7//打印机

#define USB_CLASS_MASS_STORAGE //8 批量存储设备

#define USB_CLASS_HUB 9   //USB HUBS

#define USB_CLASS_CSCID 0x0B  //智能卡

#define USB_CLASS_VIDEO 0X0E //视频设备,如网络摄像头

#define USB_CLASS_VENDOR_SPEC 0xFF //厂商自定义的设备

 

  struct usb_config_descriptor{

 

 _u8 bLength ;//此描述符的字节数

_u8 bDescriptorType; //配置描述符类型

_u16 wTotalLength; //此配置信息的总长(包括配置,接口,端点和设备类型及厂商定义的描述符)

_u8 bNumInterfaces; //此配置所支持的接口数

_u8 bConfigurationValue ;//在setConfiguration()请求中用做参数来选定此配置

_u8 iConfiguration; //描述此配置的字串描述符索引

_u8 bmAttributes; //电源配置特性

_u8 bMaxpowe;r //此配置下的总线电源耗电量

}_attribute_ ((packed));

 

 

配置描述符给出了usb设备配置信息,以及此配置下的接口数。每一个接口可能的独立操做。

 

 

 

struct usb_interface_descriptor{

 

_u8 bLength ;//此描述符的字节数

_u8 bDescriptorType;//接口描述符类

_u8 bInterfacNumber;//接口号,当前配置所支持的接口数组索引,从0开始

_u8 bNumEndpoints ;//此接口用的端点数量,若是是0,说明此接口只有缺省控制通道

_u8 bAlernateSetting;//可选设备的索引值

_u8 bInterfaceClass;// 类值,0值做为未来保留使用若是是0FFH,此接口由厂商说明

_u8 bInterfaceSubClass;//子类码

_u8 bInterfaceProtocol;//协议码

_u8 iInterface;//描述此接口的字串描述符索引

 

}_attribute_ ((packed));

 

struct usb_endpoint_descriptor{

_u8 bLength ;//此描述符的字节数

_u8 bDescriptorType;//端点描述符类

_u8 bEndpointAddress;此描述符所描述的端点的地址

_u8 bmAtrributes;//所指定的端点的特性,若是是00=控制传送,01=等时传送,10=批传送,11=中断传送

_u8 wMaxPacketSize;//当前配置下端点可以发送与接收的最大数据包大小

_u8 bInterval;//轮询数据传送端点的时间间隙

_u8 bRefresh

_u8 bSynchAddress

}_attribute_ ((packed));

 

以上给出了usb中的设备描述符,配置描述符,接口描述符和端点描述符。

 

 

5. usb设备驱动的几个重要的数据结构

 

usb_driver,usb_device,usb_bus.

 

 

/**
788* stru ctusb_driver - identifiesU SB interface driver tou sbcore
789* @name: The driver name shou ld beu niqu e amongU SB drivers,
790*      and shou ld normally be the same as the modu le name.
791* @probe: Called to see if the driver is willing to manage a particu lar
792*      interface on a device.  If it is, probe retu rns zero andu ses
793*     u sb_set_intfdata() to associate driver-specific data with the
794*      interface.  It may alsou seu sb_set_interface() to specify the
795*      appropriate altsetting.  Ifu nwilling to manage the interface,
796*      retu rn -ENODEV, if genu ine IO errors occu red, an appropriate
797*      negative errno valu e.
798* @disconnect: Called when the interface is no longer accessible,u su ally
799*      becau se its device has been (or is being) disconnected or the
800*      driver modu le is beingu nloaded.
801* @u nlocked_ioctl:U sed for drivers that want to talk tou serspace throu gh
802*      the "u sbfs" filesystem.  This lets devices provide ways to
803*      expose information tou ser space regardless of where they
804*      do (or don't) showu p otherwise in the filesystem.
805* @su spend: Called when the device is going to be su spended by the system.
806* @resu me: Called when the device is being resu med by the system.
807* @reset_resu me: Called when the su spended device has been reset instead
808*      of being resu med.
809* @pre_reset: Called byu sb_reset_device() when the device
810*      is abou t to be reset.
811* @post_reset: Called byu sb_reset_device() after the device
812*      has been reset
813* @id_table:U SB driversu se ID table to su pport hotplu gging.
814*      Export this with MODU LE_DEVICE_TABLE(u sb,...).  This mu st be set
815*      or you r driver's probe fu nction will never get called.
816* @dynids:u sed internally to hold the list of dynamically added device
817*      ids for this driver.
818* @drvwrap: Driver-model core stru ctu re wrapper.
819* @no_dynamic_id: if set to 1, theU SB core will not allow dynamic ids to be
820*      added to this driver by preventing the sysfs file from being created.
821* @su pports_au tosu spend: if set to 0, theU SB core will not allow au tosu spend
822*      for interfaces bou nd to this driver.
823* @soft_u nbind: if set to 1, theU SB core will not killU RBs and disable
824*      endpoints before calling the driver's disconnect method.
825*
826*U SB interface drivers mu st provide a name, probe() and disconnect()
827* methods, and an id_table.  Other driver fields are optional.
828*
829* The id_table isu sed in hotplu gging.  It holds a set of descriptors,
830* and specialized data may be associated with each entry.  That table
831* isu sed by bothu ser and kernel mode hotplu gging su pport.
832*
833* The probe() and disconnect() methods are called in a context where
834* they can sleep, bu t they shou ld avoid abu sing the privilege.  Most
835* work to connect to a device shou ld be done when the device is opened,
836* andu ndone at the last close.  The disconnect code needs to address
837* concu rrency issu es with respect to open() and close() methods, as
838* well as forcing all pending I/O requ ests to complete (byu nlinking
839* them as necessary, and blockingu ntil theu nlinks complete).
840*/
841stru ctusb_driver{
842         const char *name;
843
844         int (*probe) (stru ct u sb_interface*intf,
845                       const stru ctu sb_device_id*id);
846
847         void (*disconnect) (stru ct u sb_interface*intf);
848
849         int (*u nlocked_ioctl) (stru ctu sb_interface*intf,u nsigned intcode,
850                         void *bu f);
851
852         int (*su spend) (stru ct u sb_interface *intf,pm_message_tmessage);
853         int (*resu me) (stru ct u sb_interface *intf);
854         int (*reset_resu me)(stru ctu sb_interface*intf);
855
856         int (*pre_reset)(stru ct u sb_interface*intf);
857         int (*post_reset)(stru ctu sb_interface*intf);
858
859         const stru ctu sb_device_id*id_table;
860
861         stru ctu sb_dynidsdynids;
862         stru ctu sbdrv_wrapdrvwrap;
863        u nsigned int no_dynamic_id:1;
864        u nsigned int su pports_au tosu spend:1;
865        u nsigned int soft_u nbind:1;
866};

 

usb_driver中的probe函数扫描链接到主机上的usb设备,而且注册usb接口驱动。

 

disconnect函数是当usb设备移除时调用。

 

 

/*
310* Allocated per bu s (tree of devices) we have:
311*/
312stru ctu sb_bu s {
313         stru ctdevice *controller ;     /* host/master side hardware */
314         int bu snu m;                    /* Bu s nu mber (in order of reg) */
315         const char *bu s_name;          /* stable id (PCI slot_name etc) */
316        u 8u ses_dma;                   /* Does the host controlleru se DMA? */
317        u 8u ses_pio_for_control;       /*
318                                         * Does the host controlleru se PIO
319                                         * for control transfers?
320                                         */
321        u 8 otg_port;                   /* 0, or nu mber of OTG/HNP port */
322        u nsigned is_b_host:1;          /* tru e du ring some HNP roleswitches */
323        u nsigned b_hnp_enable:1;       /* OTG: did A-Host enable HNP? */
324        u nsignedsg_tablesize ;         /* 0 or largest nu mber of sg list entries */
325
326         int devnu m_next;               /* Next open device nu mber in
327                                         * rou nd-robin allocation */
328
329         stru ctu sb_devmap  devmap;      /* device address allocation map */
330         stru ctusb_device * root_hu b;   /* Root hu b */
331         stru ctu sb_bu s *hs_companion;  /* Companion EHCI bu s, if any */
332         stru ctlist_head bu s_list;     /* list of bu sses */
333
334         int bandwidth_allocated;       /* on this bu s: how mu ch of the time
335                                         * reserved for periodic (intr/iso)
336                                         * requ ests isu sed, on average?
337                                         *U nits: microseconds/frame.
338                                         * Limits: Fu ll/low speed reserve 90%,
339                                         * while high speed reserves 80%.
340                                         */
341         int bandwidth_int_reqs;        /* nu mber of Interru pt requ ests */
342         int bandwidth_isoc_reqs;       /* nu mber of Isoc. requ ests */
343
344#ifdef CONFIG_USB_DEVICE FS
345         stru ctdentry *u sbfs_dentry;   /*u sbfs dentry entry for the bu s */
346#endif
347
348#ifdefined (CONFIG_U SB_MON) ||defined(CONFIG_U SB_MON_MODU LE)
349         stru ctmon_bu s *mon_bu s ;       /* non-nu ll when associated */
350         int monitored;                 /* non-zero when monitored */
351#endif
352};
353

 

 

**
370* stru ctusb_device - kernel's representation of aU SB device
371* @devnu m: device nu mber; address on aU SB bu s
372* @devpath: device ID string foru se in messages (e.g., /port/...)
373* @rou te: tree topology hex string foru se with xHCI
374* @state: device state: configu red, not attached, etc.
375* @speed: device speed: high/fu ll/low (or error)
376* @tt: Transaction Translator info;u sed with low/fu ll speed dev, highspeed hu b
377* @ttport: device port on that tt hu b
378* @toggle: one bit for each endpoint, with ([0] = IN, [1] = OU T) endpoints
379* @parent: ou r hu b,u nless we're the root
380* @bu s: bu s we're part of
381* @ep0: endpoint 0 data (defau lt control pipe)
382* @dev: generic device interface
383* @descriptor:U SB device descriptor
384* @config: all of the device's configs
385* @actconfig: the active configu ration
386* @ep_in: array of IN endpoints
387* @ep_ou t: array of OU T endpoints
388* @rawdescriptors: raw descriptors for each config
389* @bu s_mA: Cu rrent available from the bu s
390* @portnu m: parent port nu mber (origin 1)
391* @level: nu mber ofU SB hu b ancestors
392* @can_su bmit:U RBs may be su bmitted
393* @persist_enabled: U SB_PERSIST enabled for this device
394* @have_langid: whether string_langid is valid
395* @au thorized: policy has said we canu se it;
396*      (u ser space) policy determines if we au thorize this device to be
397*     u sed or not. By defau lt, wiredU SB devices are au thorized.
398*      WU SB devices are not,u ntil we au thorize them fromu ser space.
399*      FIXME -- complete doc
400* @au thenticated: Crypto au thentication passed
401* @wu sb: device is WirelessU SB
402* @string_langid: langu age ID for strings
403* @produ ct: iProdu ct string, if present (static)
404* @manu factu rer: iManu factu rer string, if present (static)
405* @serial: iSerialNu mber string, if present (static)
406* @filelist:u sbfs files that are open to this device
407* @u sb_classdev:U SB class device that was created foru sbfs device
408*      access fromu serspace
409* @u sbfs_dentry:u sbfs dentry entry for the device
410* @maxchild: nu mber of ports if hu b
411* @children: child devices -U SB devices that are attached to this hu b
412* @qu irks: qu irks of the whole device
413* @u rbnu m: nu mber ofU RBs su bmitted for the whole device
414* @active_du ration: total time device is not su spended
415* @connect_time: time device was first connected
416* @do_remote_wakeu p:  remote wakeu p shou ld be enabled
417* @reset_resu me: needs reset instead of resu me
418* @wu sb_dev: if this is a WirelessU SB device, link to the WU SB
419*      specific data for the device.
420* @slot_id: Slot ID assigned by xHCI
421*
422* Notes:
423*U sbcore drivers shou ld not setu sbdev->state directly.  Insteadu se
424*u sb_set_device_state().
425*/
426stru ctusb_device{
427         int             devnu m;
428         char            devpath[16];
429        u 32             rou te;
430         enu musb_device _state  state;
431         enu musb_device _speed  speed;
432
433         stru ctu sb_tt   *tt;
434         int             ttport;
435
436        u nsigned inttoggle[2];
437
438         stru ctusb_device*parent;
439         stru ctu sb_bu s*bu s;
440         stru ctu sb_host_endpointep0;
441
442         stru ctdevicedev;
443
444         stru ctusb_device _descriptordescriptor;
445         stru ctu sb_host_config*config;
446
447         stru ctu sb_host_config*actconfig;
448         stru ctu sb_host_endpoint*ep_in[16];
449         stru ctu sb_host_endpoint*ep_ou t[16];
450
451         char **rawdescriptors;
452
453        u nsigned short bu s_mA;
454        u 8portnu m;
455        u 8level;
456
457        u nsigned can_su bmit:1;
458        u nsigned persist_enabled:1;
459        u nsigned have_langid:1;
460        u nsigned au thorized:1;
461        u nsigned au thenticated:1;
462        u nsigned wu sb:1;
463         int string_langid;
464
465        /* static strings from the device */
466         char *produ ct;
467         char *manu factu rer;
468         char *serial;
469
470         stru ctlist_headfilelist;
471#ifdef CONFIG_USB_DEVICE _CLASS
472         stru ctdevice*u sb_classdev;
473#endif
474#ifdef CONFIG_USB_DEVICE FS
475         stru ctdentry*u sbfs_dentry;
476#endif
477
478         int maxchild;
479         stru ctusb_device*children[U SB_MAXCHILDREN];
480
481        u 32qu irks;
482        atomic_tu rbnu m;
483
484        u nsigned long active_du ration;
485
486#ifdefCONFIG_PM
487        u nsigned long connect_time;
488
489        u nsigned do_remote_wakeu p:1;
490        u nsigned reset_resu me:1;
491#endif
492         stru ctwu sb_dev*wu sb_dev;
493         int slot_id;
494};
495#defineto_usb_device(d)container_of(d, stru ctusb_device,dev)
496
497static inline stru ctusb_device*interface_to_u sbdev(stru ctu sb_interface*intf)
498{
499         retu rnto_usb_device(intf->dev.parent);
500}
501

 

以上三个结构体分别是usb_driver,usb_bus,usb_device设备结构体。

 

 

 

usb_interface结构体:

 

struct usb_interface{
160        /* array of alternate settings for this interface,
161         * stored in no particular order */
162         structusb_host_interface*altsetting;
163
164         structusb_host_interface*cur_altsetting;     /* the currently
165                                         * active alternate setting */
166         unsigned num_altsetting;       /* number of alternate settings */
167
168        /* If there is an interface association descriptor then it will list
169         * the associated interfaces */
170         structusb_interface_assoc_descriptor*intf_assoc;
171
172         intminor;                     /* minor number this interface is
173                                         * bound to */
174         enumusb_interface_conditioncondition;        /* state of binding */
175         unsigned sysfs_files_created:1;/* the sysfs attributes exist */
176         unsigned ep_devs_created:1;    /* endpoint "devices" exist */
177         unsigned unregistering:1;      /* unregistration is in progress */
178         unsigned needs_remote_wakeup:1;/* driver requires remote wakeup */
179         unsigned needs_altsetting0:1;  /* switch to altsetting 0 is pending */
180         unsigned needs_binding:1;      /* needs delayed unbind/rebind */
181         unsigned reset_running:1;
182         unsigned resetting_device:1;   /* true: bandwidth alloc after reset */
183
184         structdevicedev;             /* interface specific device info */
185         structdevice*usb_dev;
186        atomic_tpm_usage_cnt;         /* usage counter for autosuspend */
187         structwork_structreset_ws;   /* for resets in atomic context */
188};

 struct usb_host_interface *altsetting包含了usb interface的全部可选设置。

 struct usb_host _interface *cur_altsetting是usb interface的当前可选设置。

 

下面看一个struct usb_host_interface

 

 

/* host-side wrapper for one interface setting's parsed descriptors */