基于s3c6410 otg controller的gadget driver及usb枚举分 析

一.简介

       一个完整的USB系统由两部分构成,即usb主机(usb host)和usb设备(usb device)。usb主机通常是指我们的pc机、具有host controller的嵌入式设备;像u盘、usb鼠标、键盘属于usb设备,具有otg controller的usb设备,它即可工作在host模式又可以工作在device模式,模式之间通过HNP协议来进行转换,如我们平时比较常用的智能手机,当它连接到电脑上时,工作在device模式,电脑可以像u盘一样对手机里的存储空间进行操作,而当把SD卡或其它外设接到手机上时,手机就可以对SD卡等外设进行操作,这个时候它就工作在host模式。
       由于USB系统由两部组成,所以usb驱动也由相应两部分组成。主机侧驱动主要由应用层驱动,用于管理hub和hcd的usb core层驱动,主机控制器驱动这三部分组成,应用层驱动主要是通过usb的基本数据通信结构urb对usb设备进行操作,这类驱动是针对某一个usb接口写的,所以也叫作usb 接口驱动,通常在主机端驱动人员要写的就是这类驱动。usb core驱动里包含一个守护进程,通常进程是休眠的,当usb port上产生变化,usb root hub监控到其端口上有设备插入或拔出,它就会去唤醒守护进程,然后运行usb设备的枚举,进而运行后面操作。主机控制器驱动里包含两部分,一部分是和usb接口标准相关的驱动,一部分是和控制器本身相关的,其中和接口标准相关的驱动占主要部分。主机控制器接口标准分三类:ohci,uhci和ehci,不同的生产产家有着不同的usb标准,一个usb控制器生产出来时就已经决定了其标准类型,像inter生产的通常是uhci标准的,而像本文中要用到的s3c6410是采用ohci标准的,不同标准的usb设备之间软件和硬件上分工不同,像uhci设备它在硬件逻辑上比较简单,而软件实现上比较复杂,而ohci在硬件实现上比较复杂,软件上比较简单。要完成一个usb控制器驱动无非是运用内核里各种usb 标准的API。
        在usb设备侧,驱动由三层组成:Upper Layers,gadget drivers, device controller drivers, upper layers属于应用层,通过gadget drivers来使用和控制device controllers,gadget drivers使用gadget API,实现与具体硬件无关,device controller drivers提供gadget API,实现gadget ops和endpoint ops,具体的可参考<Linux-USB Gadget API Framework>.
        不管是在主机侧还是设备侧,一个usb device它主要可由配置,接口,端口三部分表示,在主机侧它们分别由usb_host_config, usb_inferface,usb_host_endpoint表示,而设备侧由 usb_configuration,usb_function表示。配置,像我们现在的智能手机它可以用来拍照也可以用来当U盘,这两种就属于不同的配置,一个usb设备它可能包含多个配置,在使用某些功能前必需选择好相应的配置;一个配置由多个接口组成 ,一个接口表示一个功能,一个接口里可以包含多个接口设置,每个接口设置里包含与实现某一功能相关的端口,配置,接口和端口结构示意如图1所示。

 图1 配置,接口和端口结构示意图

      当一个usb设备插入到host端时,主机端的root hub通过轮训监控或中断方式来触发usb枚举,当usb设备通过枚举后,通过usb总线找到与其配置驱动,然后usb设备才能正常工作,这个枚举过程由主机和设备共同完成,对于没有运行操作系统的usb设备,生产产家已经把设备侧枚举所需过程固化在设备里,驱动工程师可不用去关心设备枚举,他们只需要完成usb 接口驱动程序。但对于有运行操作系统的usb设备就完全不一样了,驱动工程师不仅要实现usb设备功能驱动,还得实现与主机枚举过程相对应的驱动,如主机在对usb设备进行复位操作后,主机会发usb请求去设置usb设备的地址,相应的usb设备侧必须实现设备地址机制,并返回0长度usb请求,做为收到数据ACK,当主机要获取usb设备各种描述符或设置各种配置时,usb设备侧也要实现相应操作。本文主机为pc机,设备以samsung s3c6410 的otg controller为控制器,驱动为zero_driver,通过对zero_driver分析,尽量掌握gadget 驱动系统框架及设备侧枚举过程。

二. usb枚举过程分析

      usb设备主要有6种状态:attached,powered,default,address,configured,suspend.当root hub监测到有设备插入时,将其设置为attached和powered态,然后复位hub port,将其设置成default,复位成功后设置usb设备地址,获取设备、配置描述符,最后选择并设置合适的usb配置。usb请求都是由usb主机发起的,usb设备只是被动响应主机的请求,不会主动向主机发送任何usb请求,以6410为控制器的设备枚举设备侧程序流程大致如图2,图3所示。


图2 以s3c6410为设备控制器的usb枚举过程设备侧程序流程1


图3  以s3c6410为设备控制器的usb枚举过程设备侧程序流程2

如图2,由于usb设备处理被动地位,不能主动去发送数据,所有的请求都是由主机发起,而usb设备在接收到来自主机的请求后,产生接收数据中断,在中断处理程序中,通过不同的请求类型响应不同操作。

三.程序分析

       在响应host端的枚举过程前,device侧要先把device controller和gadget driver注册到系统中,否则device侧不会对host请求做出任务反映,这点在<usb gadget api for linux>里的3.1 driver life cycle讲得比较清楚,所以在讲枚举过程前要先分析device controller和gadget driver注册到系统过程,下面几个数据结构是device侧经常用到,在这里简单介绍一下:
struct usb_gadget_driver:用来存放gadget驱动;
struct usb_request:用来存放usb device侧usb请求数据;
struct usb_gadget:用来表示一个usb设备侧设备;
struct usb_gadget_ops:gadget API函数接口,和设备控制器相关;
struct usb_ep_ops:用于操作usb设备endpoint函数接口,和设备控制器相关。
struct usb_composite_driver:复合型设备驱动;
struct usb_composite_dev:复合型设备;

1. usb device controller注册

s3c6410 otg controller driver通过平台注册方式注册,当平台驱动和平台设备通过platform_match时,就会调用s3c_hsotg_probe.
[html]  view plain copy
  1. static int __devinit s3c_hsotg_probe(struct platform_device *pdev)  
  2. {  
  3.     struct s3c_hsotg_plat *plat = pdev->dev.platform_data;  
  4.     struct device *dev = &pdev->dev;  
  5.     struct s3c_hsotg *hsotg;  
  6.     struct resource *res;  
  7.     int epnum;  
  8.     int ret;  
  9.   
  10.     if (!plat)  
  11.         plat = &s3c_hsotg_default_pdata;  
  12.   
  13.     hsotg = kzalloc(sizeof(struct s3c_hsotg) +  
  14.             sizeof(struct s3c_hsotg_ep) * S3C_HSOTG_EPS,  
  15.             GFP_KERNEL);  
  16.     if (!hsotg) {  
  17.         dev_err(dev, "cannot get memory\n");  
  18.         return -ENOMEM;  
  19.     }  
  20.   
  21.     hsotg->dev = dev;  
  22.     hsotg->plat = plat;  
  23.   
  24.     hsotg->clk = clk_get(&pdev->dev, "otg");  
  25.     if (IS_ERR(hsotg->clk)) {  
  26.         dev_err(dev, "cannot get otg clock\n");  
  27.         ret = PTR_ERR(hsotg->clk);  
  28.         goto err_mem;  
  29.     }  
  30.   
  31.     platform_set_drvdata(pdev, hsotg);  
  32.   
  33.     res = platform_get_resource(pdev, IORESOURCE_MEM, 0);  
  34.     if (!res) {  
  35.         dev_err(dev, "cannot find register resource 0\n");  
  36.         ret = -EINVAL;  
  37.         goto err_clk;  
  38.     }  
  39.   
  40.     hsotg->regs_res = request_mem_region(res->start, resource_size(res),  
  41.                          dev_name(dev));  
  42.     if (!hsotg->regs_res) {  
  43.         dev_err(dev, "cannot reserve registers\n");  
  44.         ret = -ENOENT;  
  45.         goto err_clk;  
  46.     }  
  47.   
  48.     hsotg->regs = ioremap(res->start, resource_size(res));  
  49.     if (!hsotg->regs) {  
  50.         dev_err(dev, "cannot map registers\n");  
  51.         ret = -ENXIO;  
  52.         goto err_regs_res;  
  53.     }  
  54.   
  55.     ret = platform_get_irq(pdev, 0);  
  56.     if (ret < 0) {  
  57.         dev_err(dev, "cannot find IRQ\n");  
  58.         goto err_regs;  
  59.     }  
  60.   
  61.     hsotg->irq = ret;  
  62.   
  63.     ret = request_irq(ret, s3c_hsotg_irq, 0, dev_name(dev), hsotg);  
  64.     if (ret < 0) {  
  65.         dev_err(dev, "cannot claim IRQ\n");  
  66.         goto err_regs;  
  67.     }  
  68.   
  69.     dev_info(dev, "regs %p, irq %d\n", hsotg->regs, hsotg->irq);  
  70.   
  71.     device_initialize(&hsotg->gadget.dev);  
  72.   
  73.     dev_set_name(&hsotg->gadget.dev, "gadget");  
  74.   
  75.     hsotg->gadget.is_dualspeed = 1;  
  76.     hsotg->gadget.ops = &s3c_hsotg_gadget_ops;  
  77.     hsotg->gadget.name = dev_name(dev);  
  78.   
  79.     hsotg->gadget.dev.parent = dev;  
  80.     hsotg->gadget.dev.dma_mask = dev->dma_mask;  
  81.   
  82.     /* setup endpoint information */  
  83.   
  84.     INIT_LIST_HEAD(&hsotg->gadget.ep_list);  
  85.     hsotg->gadget.ep0 = &hsotg->eps[0].ep;  
  86.   
  87.     /* allocate EP0 request */  
  88.   
  89.     hsotg->ctrl_req = s3c_hsotg_ep_alloc_request(&hsotg->eps[0].ep,  
  90.                              GFP_KERNEL);  
  91.     if (!hsotg->ctrl_req) {  
  92.         dev_err(dev, "failed to allocate ctrl req\n");  
  93.         goto err_regs;  
  94.     }  
  95.   
  96.     /* reset the system */  
  97.   
  98.     clk_enable(hsotg->clk);  
  99.   
  100.     s3c_hsotg_gate(pdev, true);  
  101.   
  102.     s3c_hsotg_otgreset(hsotg);  
  103.     s3c_hsotg_corereset(hsotg);  
  104.     s3c_hsotg_init(hsotg);  
  105.   
  106.     /* initialise the endpoints now the core has been initialised */  
  107.     for (epnum = 0; epnum < S3C_HSOTG_EPS; epnum++)  
  108.         s3c_hsotg_initep(hsotg, &hsotg->eps[epnum], epnum);  
  109.   
  110.     ret = usb_add_gadget_udc(&pdev->dev, &hsotg->gadget);  
  111.     if (ret)  
  112.         goto err_add_udc;  
  113.   
  114.     s3c_hsotg_create_debug(hsotg);  
  115.   
  116.     s3c_hsotg_dump(hsotg);  
  117.   
  118.     our_hsotg = hsotg;  
  119.     return 0;  
  120.   
  121. err_add_udc:  
  122.     s3c_hsotg_gate(pdev, false);  
  123.     clk_disable(hsotg->clk);  
  124.     clk_put(hsotg->clk);  
  125.   
  126. err_regs:  
  127.     iounmap(hsotg->regs);  
  128.   
  129. err_regs_res:  
  130.     release_resource(hsotg->regs_res);  
  131.     kfree(hsotg->regs_res);  
  132. err_clk:  
  133.     clk_put(hsotg->clk);  
  134. err_mem:  
  135.     kfree(hsotg);  
  136.     return ret;  
  137. }  

s3c_hsotg_probe主要分为3个部分内容:
第一部分由12-67行,主要用于申请内存、中断资源,并映射内存、申请中断。
第二部分69-108行,主要实现用gadget结构,各endpoint初始化,并为endpoint0申请用于接收host请求的usb request数据结构.
第三部分110行,通过 usb_add_gadget_udc 把gadget设备注册到系统中,系统中有一个udc_list,专门用于管理通过usb_add_gadget_udc注册到系统的struct usb_udc.

2.usb composite driver和gadget driver注册

  根据usb协议5.3.2节定义"A device that has multiple interfaces controlled independently of each other is referred to as a composite device",如果一个usb设备由多个相互独立控制接口构成,则做复合型usb设备,具体可参考<http://www.cygnal.org/ubb/Forum9/HTML/001050.html>这里有对composite device进行比较详细说明。由于复合型设备由各个独立的接口组成,一个接口对应一个功能驱动,对于一个新的复合型设备,就没必要开发一个完整驱动,完全可以直接使用现有的接口驱动,所以复合型设备有利于usb设备驱动开发。
    目前,内核中提供了usb_composite_driver和usb_composite_dev用表征一个复合型驱动和设备,除此之外,内核还提供了像usb_add_config,usb_add_function等接口用来添加一个设备的配置和功能接口。
    本文将以内核中比较简单的zero_driver来对composite框架进行分析,zero是用来测试主机控制器驱动的设备侧驱动,主机端一般用usb_test,usb_skeleton模块,zero模块包含两种配置,一个是回环传输,它有两个端口(endpoint),一个是in,一个是out,in用来接收host端数据,out用来将host收到的数据转发给host;另一个配置是source/sink传输,它也有两个端口sink和source,sink是用来接收来自 host端口数据,而source则用来发送数据给host,发数的数据要么全0或由算法得到。

[html]  view plain copy
  1. static struct usb_composite_driver zero_driver = {  
  2.     .name       = "zero",  
  3.     .dev        = &device_desc,  
  4.     .strings    = dev_strings,  
  5.     .max_speed  = USB_SPEED_SUPER,  
  6.     .unbind     = zero_unbind,  
  7.     .suspend    = zero_suspend,  
  8.     .resume     = zero_resume,  
  9. };  
            zero_driver中dev定义了初始的usb设备描述符,之后会在zero_bind中补全其它参量,在usb枚举的过程中会将这个完整的设备描述符发送回给host。
           strings定义了struct usb_gadget_string结构数组,里而包含了生产产家,产品编号及序列号等信息。
        composite设备驱动由usb_composite_probe注册,usb_composite_unregister接口卸载。

[html]  view plain copy
  1. static int __init init(void)  
  2. {  
  3.     return usb_composite_probe(&zero_driver, zero_bind);  
  4. }  
  5. module_init(init);  
  6.   
  7. static void __exit cleanup(void)  
  8. {  
  9.     usb_composite_unregister(&zero_driver);  
  10. }  
  11. module_exit(cleanup);  
         usb_composite_probe接口定义如下,它有两个型参,一个是usb_composite_driver,一个是 composite驱动的回调函数,回调函数工作主要有:通过usb_add_config来添加usb配置,补全设备描述符,获取设备ID,具体后面用到时再分析,接下来先看usb_composite_probe函数。
[html]  view plain copy
  1. int usb_composite_probe(struct usb_composite_driver *driver,  
  2.                    int (*bind)(struct usb_composite_dev *cdev))  
  3. {  
  4.     if (!driver || !driver->dev || !bind || composite)  
  5.         return -EINVAL;  
  6.   
  7.     if (!driver->name)  
  8.         driver->name = "composite";  
  9.     if (!driver->iProduct)  
  10.         driver->iProduct = driver->name;  
  11.     composite_driver.function =  (char *) driver->name;  
  12.     composite_driver.driver.name = driver->name;  
  13.     composite_driver.speed = min((u8)composite_driver.speed,  
  14.                      (u8)driver->max_speed);  
  15.     composite = driver;  
  16.     composite_gadget_bind = bind;  
  17.   
  18.     return usb_gadget_probe_driver(&composite_driver, composite_bind);  
  19. }  
       usb_composite_probe用来将usb_composite_driver注册到composite driver框架中,这里通过一个composite变量用来保存composite driver,composite_gadget_bind保存bind,并通过composite driver中的些变量来补全一个usb_gadget_driver composite_driver.之前简介里有提到过,gadget设备侧程序主要由gadget driver和device controller driver组成 ,这里这个composite_driver就是device controller driver上面的那与硬件无关的那一层,composite_driver定义如下:
[html]  view plain copy
  1. static struct usb_gadget_driver composite_driver = {  
  2. #ifdef CONFIG_USB_GADGET_SUPERSPEED  
  3.     .speed      = USB_SPEED_SUPER,  
  4. #else  
  5.     .speed      = USB_SPEED_HIGH,  
  6. #endif  
  7.   
  8.     .unbind     = composite_unbind,  
  9.   
  10.     .setup      = composite_setup,  
  11.     .disconnect = composite_disconnect,  
  12.   
  13.     .suspend    = composite_suspend,  
  14.     .resume     = composite_resume,  
  15.   
  16.     .driver = {  
  17.         .owner      = THIS_MODULE,  
  18.     },  
  19. };  
      composite_driver中的setup函数最为重要,简介中曾经说过,device controller driver用来完成和硬件相关的设备或回应,如设置usb设备地址,ACK应答之类机制。但像获取设备描述符,设置配置,设置接口等机制并没有实现,这些请求的处理机制就是在这个setup里完成的。
      usb_gadget_driver由usb_gadget_probe_driver和usb_gadget_unregister_dirver完成。usb_gadget_probe_driver除了包含gadget driver外,还包括了gadget驱动中的回调函数composite_bind.
[html]  view plain copy
  1. int usb_gadget_probe_driver(struct usb_gadget_driver *driver,  
  2.         int (*bind)(struct usb_gadget *))  
  3. {  
  4.     struct usb_udc      *udc = NULL;  
  5.     int         ret;  
  6.   
  7.     if (!driver || !bind || !driver->setup)  
  8.         return -EINVAL;  
  9.   
  10.     mutex_lock(&udc_lock);  
  11.     list_for_each_entry(udc, &udc_list, list) {  
  12.         /* For now we take the first one */  
  13.         if (!udc->driver)  
  14.             goto found;  
  15.     }  
  16.   
  17.     pr_debug("couldn't find an available UDC\n");  
  18.     mutex_unlock(&udc_lock);  
  19.     return -ENODEV;  
  20.   
  21. found:  
  22.     dev_dbg(&udc->dev, "registering UDC driver [%s]\n",  
  23.             driver->function);  
  24.   
  25.     udc->driver = driver;  
  26.     udc->dev.driver = &driver->driver;  
  27.   
  28.     if (udc_is_newstyle(udc)) {  
  29.         ret = bind(udc->gadget);  
  30.         if (ret)  
  31.             goto err1;  
  32.         ret = usb_gadget_udc_start(udc->gadget, driver);  
  33.         if (ret) {  
  34.             driver->unbind(udc->gadget);  
  35.             goto err1;  
  36.         }  
  37.         usb_gadget_connect(udc->gadget);  
  38.     } else {  
  39.   
  40.         ret = usb_gadget_start(udc->gadget, driver, bind);  
  41.         if (ret)  
  42.             goto err1;  
  43.   
  44.     }  
  45.   
  46.     kobject_uevent(&udc->dev.kobj, KOBJ_CHANGE);  
  47.     mutex_unlock(&udc_lock);  
  48.     return 0;  
  49.   
  50. err1:  
  51.     dev_err(&udc->dev, "failed to start %s: %d\n",  
  52.             udc->driver->function, ret);  
  53.     udc->driver = NULL;  
  54.     udc->dev.driver = NULL;  
  55.     mutex_unlock(&udc_lock);  
  56.     return ret;  
  57. }  
        这前在讲device controller 注册时讲过,通过usb_add_gadget_udc注册device controller时,linux系统是通过一个struct usb_udc结构的udc_list列表中进行管理设备控制器的,struct usb_udc结构如下:
[html]  view plain copy
  1. struct usb_udc {  
  2.     struct usb_gadget_driver    *driver;  
  3.     struct usb_gadget       *gadget;  
  4.     struct device           dev;  
  5.     struct list_head        list;  
  6. };  
           driver用于表示一个udc驱动,而 list就是用来加入到udc_list列表的入口变量。
           在 usb_gadget_probe_driver中的11-15行,对udc_list 列表进行遍历,查看是否有udc控制器没有添加相对应的驱动,如果找不到说明系统中没有注册udc或每个udc都有相应的驱动。
        如果udc列表中有某个udc没有驱动,则将usb_gadgett_driver和相应udc关联在一起。
        28-44行通过判断usb device controller实现模式为选择运行程序,由于版本兼容原因,操作控制器硬件的ops里包含了新的和旧的操作接口。
[html]  view plain copy
  1.        int  (*udc_start)(struct usb_gadget *, struct usb_gadget_driver *);  
  2. int (*udc_stop)(struct usb_gadget *, struct usb_gadget_driver *);  
  3. /* Those two are deprecated */  
  4. int (*start)(struct usb_gadget_driver *, int (*bind)(struct usb_gadget *));  
  5. int (*stop)(struct usb_gadget_driver *);  
         其中,udc_start 和udc_stop为新版本操作接口 ,而start 和stop老版本操作接口。
         由于本文所采用的内核是老版本的接口,所以会运行下面usb_gadget_start函数。
         usb_gadget_start函数将会以gadget_driver和composite_bind为参数调用usb device controller的ops中的start回调函数,在注册usb device controller时就定义了ops 的start回调函数为s3c_hsotg_start
         如果usb_gadget_start运行正常则通过object_uevent来通知用户发生了KOBJ_CHANGE事件,用户空间中的udev程序就会采取相应操作。
         s3c_hsotg_start函数里主要是涉及低层寄存器控制,在这里就不去深入研究了,composite_bind将会在s3c_hsotg_start中被调用。
 
[html]  view plain copy
  1. static int composite_bind(struct usb_gadget *gadget)  
  2. {  
  3.     struct usb_composite_dev    *cdev;  
  4.     int             status = -ENOMEM;  
  5.   
  6.     cdev = kzalloc(sizeof *cdev, GFP_KERNEL);  
  7.     if (!cdev)  
  8.         return status;  
  9.   
  10.     spin_lock_init(&cdev->lock);  
  11.     cdev->gadget = gadget;  
  12.     set_gadget_data(gadget, cdev);  
  13.     INIT_LIST_HEAD(&cdev->configs);  
  14.   
  15.     /* preallocate control response and buffer */  
  16.     cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);  
  17.     if (!cdev->req)  
  18.         goto fail;  
  19.     cdev->req->buf = kmalloc(USB_BUFSIZ, GFP_KERNEL);  
  20.     if (!cdev->req->buf)  
  21.         goto fail;  
  22.     cdev->req->complete = composite_setup_complete;  
  23.     gadget->ep0->driver_data = cdev;  
  24.   
  25.     cdev->bufsiz = USB_BUFSIZ;  
  26.     cdev->driver = composite;  
  27.   
  28.     /*  
  29.      * As per USB compliance update, a device that is actively drawing  
  30.      * more than 100mA from USB must report itself as bus-powered in  
  31.      * the GetStatus(DEVICE) call.  
  32.      */  
  33.     if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)  
  34.         usb_gadget_set_selfpowered(gadget);  
  35.   
  36.     /* interface and string IDs start at zero via kzalloc.  
  37.      * we force endpoints to start unassigned; few controller  
  38.      * drivers will zero ep->driver_data.  
  39.      */  
  40.     usb_ep_autoconfig_reset(cdev->gadget);  
  41.   
  42.     /* composite gadget needs to assign strings for whole device (like  
  43.      * serial number), register function drivers, potentially update  
  44.      * power state and consumption, etc  
  45.      */  
  46.     status = composite_gadget_bind(cdev);  
  47.     if (status < 0)  
  48.         goto fail;  
  49.   
  50.     cdev->desc = *composite->dev;  
  51.   
  52.     /* standardized runtime overrides for device ID data */  
  53.     if (idVendor)  
  54.         cdev->desc.idVendor = cpu_to_le16(idVendor);  
  55.     if (idProduct)  
  56.         cdev->desc.idProduct = cpu_to_le16(idProduct);  
  57.     if (bcdDevice)  
  58.         cdev->desc.bcdDevice = cpu_to_le16(bcdDevice);  
  59.   
  60.     /* string overrides */  
  61.     if (iManufacturer || !cdev->desc.iManufacturer) {  
  62.         if (!iManufacturer && !composite->iManufacturer &&  
  63.             !*composite_manufacturer)  
  64.             snprintf(composite_manufacturer,  
  65.                  sizeof composite_manufacturer,  
  66.                  "%s %s with %s",  
  67.                  init_utsname()->sysname,  
  68.                  init_utsname()->release,  
  69.                  gadget->name);  
  70.   
  71.         cdev->manufacturer_override =  
  72.             override_id(cdev, &cdev->desc.iManufacturer);  
  73.     }  
  74.   
  75.     if (iProduct || (!cdev->desc.iProduct && composite->iProduct))  
  76.         cdev->product_override =  
  77.             override_id(cdev, &cdev->desc.iProduct);  
  78.   
  79.     if (iSerialNumber)  
  80.         cdev->serial_override =  
  81.             override_id(cdev, &cdev->desc.iSerialNumber);  
  82.   
  83.     /* has userspace failed to provide a serial number? */  
  84.     if (composite->needs_serial && !cdev->desc.iSerialNumber)  
  85.         WARNING(cdev, "userspace failed to provide iSerialNumber\n");  
  86.   
  87.     /* finish up */  
  88.     status = device_create_file(&gadget->dev, &dev_attr_suspended);  
  89.     if (status)  
  90.         goto fail;  
  91.   
  92.     INFO(cdev, "%s ready\n", composite->name);  
  93.     return 0;  
  94.   
  95. fail:  
  96.     composite_unbind(gadget);  
  97.     return status;  
  98. }  
         在将gadget driver和usb device controller联系在一起后,composite_bind将会生成一个composite dev数据结构,并对其进行初始化,然后申请用于回复endpoint0的控制端口的usb request资源,最后调用composite回调函数zero_bind用来为composite usb device 添加配置。
         第6-8行为composite dev结构申请空间。
         第10-13行初始化composite dev中自旋锁,对向列表头等。
         第16-23行,申请用于回复endpoint0控制口的usb请求资源,这个请求用来回复host端获取设备描述符,配置描述符等需要返回数据的usb请求,并为usb请求申请用于存放发送数据内存空间,为usb请求回调函数赋值,当usb请求被发送出去后就会调用回调函数来通知usb请求发出者.
         第26行,把之前保存在composite里的composite_driver赋值给cdev->driver。
         第46行,调用usb_composite_driver回调函数zero_bind。
         第47行,把复合型设备描述符保存在cdev的desc里。
         第52-57行,如果在加载模块时指定了生产产家ID,产口ID和设备版本号,则用指定的值来代替原来的值。
         第60-80行,用于设置设备描述符中的iManufacturer,iProduct和iSerialNumber,如果没有设置这几个变量的index,则通过override_id来获取ID,本文已经在zero_driver中的zero_bind获取了。
         第84-85行,如果设置在usb_composite_driver设置了need_serial项,则需要用户空间提供usb设备的serial id,如果没有提供则发出warn。
         第88行,通过device_create_file生成一个用生查询usb设备是否suspend状态的设备属性函数。
         如果假设zero_bind运行正常,还有下面创建设备文件也正常,则 一个gadget设备准备工作都已经完成 ,gadget设备可以与host设备进行通信 。
         在讲具体的枚举过程之前,先完成对zero_bind函数里面分析。
      
[html]  view plain copy
  1. static int __init zero_bind(struct usb_composite_dev *cdev)  
  2. {  
  3.     int         gcnum;  
  4.     struct usb_gadget   *gadget = cdev->gadget;  
  5.     int         id;  
  6.   
  7.     /* Allocate string descriptor numbers ... note that string  
  8.      * contents can be overridden by the composite_dev glue.  
  9.      */  
  10.     id = usb_string_id(cdev);  
  11.     if (id < 0)  
  12.         return id;  
  13.     strings_dev[STRING_MANUFACTURER_IDX].id = id;  
  14.     device_desc.iManufacturer = id;  
  15.   
  16.     id = usb_string_id(cdev);  
  17.     if (id < 0)  
  18.         return id;  
  19.     strings_dev[STRING_PRODUCT_IDX].id = id;  
  20.     device_desc.iProduct = id;  
  21.   
  22.     id = usb_string_id(cdev);  
  23.     if (id < 0)  
  24.         return id;  
  25.     strings_dev[STRING_SERIAL_IDX].id = id;  
  26.     device_desc.iSerialNumber = id;  
  27.   
  28.     setup_timer(&autoresume_timer, zero_autoresume, (unsigned long) cdev);  
  29.   
  30.     /* Register primary, then secondary configuration.  Note that  
  31.      * SH3 only allows one config...  
  32.      */  
  33.     if (loopdefault) {  
  34.         loopback_add(cdev, autoresume != 0);  
  35.         sourcesink_add(cdev, autoresume != 0);  
  36.     } else {  
  37.         sourcesink_add(cdev, autoresume != 0);  
  38.         loopback_add(cdev, autoresume != 0);  
  39.     }  
  40.   
  41.     gcnum = usb_gadget_controller_number(gadget);  
  42.     if (gcnum >= 0)  
  43.         device_desc.bcdDevice = cpu_to_le16(0x0200 + gcnum);  
  44.     else {  
  45.         /* gadget zero is so simple (for now, no altsettings) that  
  46.          * it SHOULD NOT have problems with bulk-capable hardware.  
  47.          * so just warn about unrcognized controllers -- don't panic.  
  48.          *  
  49.          * things like configuration and altsetting numbering  
  50.          * can need hardware-specific attention though.  
  51.          */  
  52.         pr_warning("%s: controller '%s' not recognized\n",  
  53.             longname, gadget->name);  
  54.         device_desc.bcdDevice = cpu_to_le16(0x9999);  
  55.     }  
  56.   
  57.   
  58.     INFO(cdev, "%s, version: " DRIVER_VERSION "\n", longname);  
  59.   
  60.     snprintf(manufacturer, sizeof manufacturer, "%s %s with %s",  
  61.         init_utsname()->sysname, init_utsname()->release,  
  62.         gadget->name);  
  63.   
  64.     return 0;  
  65. }  
       zero_bind主要用于设置设备描述符中bcdDevice,iManufacturer,iProduct及iSerialNumber,然后通过loopback_add和sourcesink_add添加usb配置。
       10-14行,通过usb_string_id来为生产产家获取一个 ID,在usb_composite_dev中的next_string_id专门用来管理string ID,只要next_string_id小于254就可以合法获取string ID,获取到stringID后把它保存到usb设备描述符里的iManufacturer及复合设备结构中的strings里。
       16-20行,用于获取产品ID,并存入设备描述符和复合设备结构中的strings里。
       22-26行,用于获取设备系列号,并存入相应结构中。
       28行,设备一个timer_list定时器,用于设备suspend和resume这里不深入分析。
       34-39行通过loopback_add和sourcesink_add添加usb配置,前面有提到过,loopback配置用来将从host 接收到的数据发送给host,而sourcesink配置则是在接收到host数据后,向host发送全0或算法生成的数据,两者只是在发送回给host的数据存在差别,这里只对其中的loopback进行分析, sourcesind_add就不深入研究了。
       41-55行根据device controller类型来获取设备版本号,如果device controller没有匹配项,则将设备版本号设置成0X9999.
[html]  view plain copy
  1. int __init loopback_add(struct usb_composite_dev *cdev, bool autoresume)  
  2. {  
  3.     int id;  
  4.   
  5.     /* allocate string ID(s) */  
  6.     id = usb_string_id(cdev);  
  7.     if (id < 0)  
  8.         return id;  
  9.     strings_loopback[0].id = id;  
  10.   
  11.     loopback_intf.iInterface = id;  
  12.     loopback_driver.iConfiguration = id;  
  13.   
  14.     /* support autoresume for remote wakeup testing */  
  15.     if (autoresume)  
  16.         sourcesink_driver.bmAttributes |= USB_CONFIG_ATT_WAKEUP;  
  17.   
  18.     /* support OTG systems */  
  19.     if (gadget_is_otg(cdev->gadget)) {  
  20.         loopback_driver.descriptors = otg_desc;  
  21.         loopback_driver.bmAttributes |= USB_CONFIG_ATT_WAKEUP;  
  22.     }  
  23.   
  24.     return usb_add_config(cdev, &loopback_driver, loopback_bind_config);  
  25. }  
       loopback_add主要是完成loopback这个配置描述符里的配置ID设置,并通过usb_add_config向usb设备添加loopback_driver这个配置。
       6-12行用于获取配置的ID,并保存到配置描述符中。
       15-16行,如果usb设备这个配置支持唤醒功能,则在usb_configuration时的bmAttributes里wakeup置位。
       19-22行,如果支持otg功能,则还需要添加otg 描述符。
       24行通过usb_add_config添加loopback_driver配置,loopback_driver定义如下:
[html]  view plain copy
  1. static struct usb_configuration loopback_driver = {  
  2.     .label      = "loopback",  
  3.     .strings    = loopback_strings,  
  4.     .bConfigurationValue = 2,  
  5.     .bmAttributes   = USB_CONFIG_ATT_SELFPOWER,  
  6.     /* .iConfiguration = DYNAMIC */  
  7. };  
        label为配置名字,strings里用于申明配置功能的string,bConfigurationValue用来表示当前配置值,在USB枚举时就能通过选择合适的配置值来设备usb设备的配置,bmAttributes用来表明配置的特性,如自供电,远程唤醒等。
      用usb_add_config添加配置时,需要三个参数,usb_composite_dev结构cdev, usb配置loopback_driver和配置的回调函数loopback_bind_config.
[html]  view plain copy
  1. int usb_add_config(struct usb_composite_dev *cdev,  
  2.         struct usb_configuration *config,  
  3.         int (*bind)(struct usb_configuration *))  
  4. {  
  5.     int             status = -EINVAL;  
  6.     struct usb_configuration    *c;  
  7.   
  8.     DBG(cdev, "adding config #%u '%s'/%p\n",  
  9.             config->bConfigurationValue,  
  10.             config->label, config);  
  11.   
  12.     if (!config->bConfigurationValue || !bind)  
  13.         goto done;  
  14.   
  15.     /* Prevent duplicate configuration identifiers */  
  16.     list_for_each_entry(c, &cdev->configs, list) {  
  17.         if (c->bConfigurationValue == config->bConfigurationValue) {  
  18.             status = -EBUSY;  
  19.             goto done;  
  20.         }  
  21.     }  
  22.   
  23.     config->cdev = cdev;  
  24.     list_add_tail(&config->list, &cdev->configs);  
  25.   
  26.     INIT_LIST_HEAD(&config->functions);  
  27.     config->next_interface_id = 0;  
  28.   
  29.     status = bind(config);  
  30.     if (status < 0) {  
  31.         list_del(&config->list);  
  32.         config->cdev = NULL;  
  33.     } else {  
  34.         unsigned    i;  
  35.   
  36.         DBG(cdev, "cfg %d/%p speeds:%s%s%s\n",  
  37.             config->bConfigurationValue, config,  
  38.             config->superspeed ? " super" : "",  
  39.             config->highspeed ? " high" : "",  
  40.             config->fullspeed  
  41.                 ? (gadget_is_dualspeed(cdev->gadget)  
  42.                     ? " full"  
  43.                     : " full/low")  
  44.                 : "");  
  45.   
  46.         for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {  
  47.             struct usb_function *f = config->interface[i];  
  48.   
  49.             if (!f)  
  50.                 continue;  
  51.             DBG(cdev, "  interface %d = %s/%p\n",  
  52.                 i, f->name, f);  
  53.         }  
  54.     }  
  55.   
  56.     /* set_alt(), or next bind(), sets up  
  57.      * ep->driver_data as needed.  
  58.      */  
  59.     usb_ep_autoconfig_reset(cdev->gadget);  
  60.   
  61. done:  
  62.     if (status)  
  63.         DBG(cdev, "added config '%s'/%u --> %d\n", config->label,  
  64.                 config->bConfigurationValue, status);  
  65.     return status;  
  66. }  
usb_add_config用来向复合型usb设备添加一个usb配置,并对配置进行初始化,最后调用配置的回调函数loopback_bind_config向当前配置添加usb接口。
在配置描述符中的bConfigurationValue用来表示配置值,一个复合型设备有可能包含多个配置,配置之间通过这个bConfigurationValue来区别。第12-21行,在添加配置前会先判断配置值和回调函数是否已经设置,然后再通过遍历复合设备中配置列表来判断当前配置是否已经添加到设备,如果已经添加就会返回busy错误,以防止向设备添加同一配置值的配置。
23-24行,配置和复合设备进行相互绑定,复合设备结构中有专门用于管理设备配置的双向列表,把当前配置加入到双向列表中。
25-27行,对配置结构中function列表头和用于管理当前配置接口ID变量进行初始化。
29行,调用配置回调函数loopback_bind_config,向配置中添加usb接口(usb_function,在usb中,一个接口对应一个功能)。

[html]  view plain copy
  1. static int __init loopback_bind_config(struct usb_configuration *c)  
  2. {  
  3.     struct f_loopback   *loop;  
  4.     int         status;  
  5.   
  6.     loop = kzalloc(sizeof *loop, GFP_KERNEL);  
  7.     if (!loop)  
  8.         return -ENOMEM;  
  9.   
  10.     loop->function.name = "loopback";  
  11.     loop->function.descriptors = fs_loopback_descs;  
  12.     loop->function.bind = loopback_bind;  
  13.     loop->function.unbind = loopback_unbind;  
  14.     loop->function.set_alt = loopback_set_alt;  
  15.     loop->function.disable = loopback_disable;  
  16.   
  17.     status = usb_add_function(c, &loop->function);  
  18.     if (status)  
  19.         kfree(loop);  
  20.     return status;  
  21. }  

loopback_bind_config用来向当前配置添加接口功能,它先申请了一个f_loopback数据结构,里面包含了usb的接口和端口,然后对接口一些函数接口进行初始化,最后调用usb_add_function把接口添加到配置中。在接口的操作函数接口中,bind和set_alt相对比较重要,在usb_add_function中会调用bind来完成某个接口中各端口(endpoint)的初始化,而在枚举过程中设置接口USB请求就是通过这个接口实现。

[html]  view plain copy
  1. int usb_add_function(struct usb_configuration *config,  
  2.         struct usb_function *function)  
  3. {  
  4.     int value = -EINVAL;  
  5.   
  6.     DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",  
  7.             function->name, function,  
  8.             config->label, config);  
  9.   
  10.     if (!function->set_alt || !function->disable)  
  11.         goto done;  
  12.   
  13.     function->config = config;  
  14.     list_add_tail(&function->list, &config->functions);  
  15.   
  16.     /* REVISIT *require* function->bind? */  
  17.     if (function->bind) {  
  18.         value = function->bind(config, function);  
  19.         if (value < 0) {  
  20.             list_del(&function->list);  
  21.             function->config = NULL;  
  22.         }  
  23.     } else  
  24.         value = 0;  
  25.   
  26.     /* We allow configurations that don't work at both speeds.  
  27.      * If we run into a lowspeed Linux system, treat it the same  
  28.      * as full speed ... it's the function drivers that will need  
  29.      * to avoid bulk and ISO transfers.  
  30.      */  
  31.     if (!config->fullspeed && function->descriptors)  
  32.         config->fullspeed = true;  
  33.     if (!config->highspeed && function->hs_descriptors)  
  34.         config->highspeed = true;  
  35.     if (!config->superspeed && function->ss_descriptors)  
  36.         config->superspeed = true;  
  37.   
  38. done:  
  39.     if (value)  
  40.         DBG(config->cdev, "adding '%s'/%p --> %d\n",  
  41.                 function->name, function, value);  
  42.     return value;  
  43. }  
usb_add_function主要用来绑定配置和接口,然后调用接口中bind函数。
13-14行,配置和接口相互绑定,将接口添加到配置里用于管理接口的双向列表中。
17-24行,哪里在接口操作函数中定义了bind函数,则调用bind函数,如调用失败则将绑定的配置和接口分开。
31-36行,根据接口中定义的各种速度的接口和字符串标识来确定当前配置所支持速度。
[html]  view plain copy
  1. static int __init  
  2. loopback_bind(struct usb_configuration *c, struct usb_function *f)  
  3. {  
  4.     struct usb_composite_dev *cdev = c->cdev;  
  5.     struct f_loopback   *loop = func_to_loop(f);  
  6.     int         id;  
  7.   
  8.     /* allocate interface ID(s) */  
  9.     id = usb_interface_id(c, f);  
  10.     if (id < 0)  
  11.         return id;  
  12.     loopback_intf.bInterfaceNumber = id;  
  13.   
  14.     /* allocate endpoints */  
  15.   
  16.     loop->in_ep = usb_ep_autoconfig(cdev->gadget, &fs_loop_source_desc);  
  17.     if (!loop->in_ep) {  
  18. autoconf_fail:  
  19.         ERROR(cdev, "%s: can't autoconfigure on %s\n",  
  20.             f->name, cdev->gadget->name);  
  21.         return -ENODEV;  
  22.     }  
  23.     loop->in_ep->driver_data = cdev;  /* claim */  
  24.   
  25.     loop->out_ep = usb_ep_autoconfig(cdev->gadget, &fs_loop_sink_desc);  
  26.     if (!loop->out_ep)  
  27.         goto autoconf_fail;  
  28.     loop->out_ep->driver_data = cdev; /* claim */  
  29.   
  30.     /* support high speed hardware */  
  31.     if (gadget_is_dualspeed(c->cdev->gadget)) {  
  32.         hs_loop_source_desc.bEndpointAddress =  
  33.                 fs_loop_source_desc.bEndpointAddress;  
  34.         hs_loop_sink_desc.bEndpointAddress =  
  35.                 fs_loop_sink_desc.bEndpointAddress;  
  36.         f->hs_descriptors = hs_loopback_descs;  
  37.     }  
  38.   
  39.     /* support super speed hardware */  
  40.     if (gadget_is_superspeed(c->cdev->gadget)) {  
  41.         ss_loop_source_desc.bEndpointAddress =  
  42.                 fs_loop_source_desc.bEndpointAddress;  
  43.         ss_loop_sink_desc.bEndpointAddress =  
  44.                 fs_loop_sink_desc.bEndpointAddress;  
  45.         f->ss_descriptors = ss_loopback_descs;  
  46.     }  
  47.   
  48.     DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",  
  49.         (gadget_is_superspeed(c->cdev->gadget) ? "super" :  
  50.          (gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full")),  
  51.             f->name, loop->in_ep->name, loop->out_ep->name);  
  52.     return 0;  
  53. }  
loopback_bind主要用于配置接口中的端口。
一个usb配置有可能包含多个接口,可能用接口号来表示不同的接口,前面讲过配置中有一个专门用来管理接口号的变量next_interface_id,9-12行,用于获取一个接口号并把它存入到接口描述符中。
第16-23和25-28行,分别 调用usb_ep_autoconfig函数,从gadget的ep_list找到in和out端口;
在usb接口数据结构中有三个指针数组descriptors,hs_descriptors, ss_descriptors,它们分别用来存放三种不同速度的接口和端口描述符指针头,descriptors用来存放全速接口和端口描述符指针头,而hs_descriptors用来保存高速指针头,ss_descriptors则用来保存超速指针头。
第31-37行,判断该usb设备是否支持高速传输,如果支持将高速端口描述符中的bEndpointAddress设置成和全速一样,bEndpointAddress用来描述端口传输方向和端口号,这个和传输速度无关,所以都设置成一样的。
第40-46行,判断该usb设备是否支持超高速传输,如果支持超高速端口描述符中的bEndpointAddress设置成和全速一样。
[html]  view plain copy
  1. struct usb_ep *usb_ep_autoconfig(  
  2.     struct usb_gadget       *gadget,  
  3.     struct usb_endpoint_descriptor  *desc  
  4. )  
  5. {  
  6.     return usb_ep_autoconfig_ss(gadget, desc, NULL);  
  7. }  
usb_ep_autoconfig函数是从gadget里的ep_list找到与所给端口描述符相匹配的端口,函数里面实际上是调用usb_ep_autoconfig_ss来实现端口匹配的。

[html]  view plain copy
  1. struct usb_ep *usb_ep_autoconfig_ss(  
  2.     struct usb_gadget       *gadget,  
  3.     struct usb_endpoint_descriptor  *desc,  
  4.     struct usb_ss_ep_comp_descriptor *ep_comp  
  5. )  
  6. {  
  7.     struct usb_ep   *ep;  
  8.     u8      type;  
  9.   
  10.     type = desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;  
  11.   
  12.     /* First, apply chip-specific "best usage" knowledge.  
  13.      * This might make a good usb_gadget_ops hook ...  
  14.      */  
  15.     if (gadget_is_net2280 (gadget) && type == USB_ENDPOINT_XFER_INT) {  
  16.         /* ep-e, ep-f are PIO with only 64 byte fifos */  
  17.         ep = find_ep (gadget, "ep-e");  
  18.         if (ep && ep_matches(gadget, ep, desc, ep_comp))  
  19.             return ep;  
  20.         ep = find_ep (gadget, "ep-f");  
  21.         if (ep && ep_matches(gadget, ep, desc, ep_comp))  
  22.             return ep;  
  23.   
  24.     } else if (gadget_is_goku (gadget)) {  
  25.         if (USB_ENDPOINT_XFER_INT == type) {  
  26.             /* single buffering is enough */  
  27.             ep = find_ep(gadget, "ep3-bulk");  
  28.             if (ep && ep_matches(gadget, ep, desc, ep_comp))  
  29.                 return ep;  
  30.         } else if (USB_ENDPOINT_XFER_BULK == type  
  31.                 && (USB_DIR_IN & desc->bEndpointAddress)) {  
  32.             /* DMA may be available */  
  33.             ep = find_ep(gadget, "ep2-bulk");  
  34.             if (ep && ep_matches(gadget, ep, desc,  
  35.                           ep_comp))  
  36.                 return ep;  
  37.         }  
  38.   
  39. #ifdef CONFIG_BLACKFIN  
  40.     } else if (gadget_is_musbhdrc(gadget)) {  
  41.         if ((USB_ENDPOINT_XFER_BULK == type) ||  
  42.             (USB_ENDPOINT_XFER_ISOC == type)) {  
  43.             if (USB_DIR_IN & desc->bEndpointAddress)  
  44.                 ep = find_ep (gadget, "ep5in");  
  45.             else  
  46.                 ep = find_ep (gadget, "ep6out");  
  47.         } else if (USB_ENDPOINT_XFER_INT == type) {  
  48.             if (USB_DIR_IN & desc->bEndpointAddress)  
  49.                 ep = find_ep(gadget, "ep1in");  
  50.             else  
  51.                 ep = find_ep(gadget, "ep2out");  
  52.         } else  
  53.             ep = NULL;  
  54.         if (ep && ep_matches(gadget, ep, desc, ep_comp))  
  55.             return ep;  
  56. #endif  
  57.     }  
  58.   
  59.     /* Second, look at endpoints until an unclaimed one looks usable */  
  60.     list_for_each_entry (ep, &gadget->ep_list, ep_list) {  
  61.         if (ep_matches(gadget, ep, desc, ep_comp))  
  62.             return ep;  
  63.     }  
  64.   
  65.     /* Fail */  
  66.     return NULL;  
  67. }  
usb_ep_autoconfig_ss函数有三个形参,分别是表示usb设备侧设备gadget,端口描述符desc和专门用于描述超高速端口特性(usb 3.0里才有)的ep_comp,它首先通过匹配设备控制器芯片和端口传输类型来选择端口,如没有找到则在gadget的ep_list列表中寻找ep,并通过ep_matches匹配,如果找到相匹配的endpoint就返回该端口,否则返回null。

[html]  view plain copy
  1. static int  
  2. ep_matches (  
  3.     struct usb_gadget       *gadget,  
  4.     struct usb_ep           *ep,  
  5.     struct usb_endpoint_descriptor  *desc,  
  6.     struct usb_ss_ep_comp_descriptor *ep_comp  
  7. )  
  8. {  
  9.     u8      type;  
  10.     const char  *tmp;  
  11.     u16     max;  
  12.   
  13.     int     num_req_streams = 0;  
  14.   
  15.     /* endpoint already claimed? */  
  16.     if (NULL != ep->driver_data)  
  17.         return 0;  
  18.   
  19.     /* only support ep0 for portable CONTROL traffic */  
  20.     type = desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;  
  21.     if (USB_ENDPOINT_XFER_CONTROL == type)  
  22.         return 0;  
  23.   
  24.     /* some other naming convention */  
  25.     if ('e' != ep->name[0])  
  26.         return 0;  
  27.   
  28.     /* type-restriction:  "-iso", "-bulk", or "-int".  
  29.      * direction-restriction:  "in", "out".  
  30.      */  
  31.     if ('-' != ep->name[2]) {  
  32.         tmp = strrchr (ep->name, '-');  
  33.         if (tmp) {  
  34.             switch (type) {  
  35.             case USB_ENDPOINT_XFER_INT:  
  36.                 /* bulk endpoints handle interrupt transfers,  
  37.                  * except the toggle-quirky iso-synch kind  
  38.                  */  
  39.                 if ('s' == tmp[2])  // == "-iso"  
  40.                     return 0;  
  41.                 /* for now, avoid PXA "interrupt-in";  
  42.                  * it's documented as never using DATA1.  
  43.                  */  
  44.                 if (gadget_is_pxa (gadget)  
  45.                         && 'i' == tmp [1])  
  46.                     return 0;  
  47.                 break;  
  48.             case USB_ENDPOINT_XFER_BULK:  
  49.                 if ('b' != tmp[1])  // != "-bulk"  
  50.                     return 0;  
  51.                 break;  
  52.             case USB_ENDPOINT_XFER_ISOC:  
  53.                 if ('s' != tmp[2])  // != "-iso"  
  54.                     return 0;  
  55.             }  
  56.         } else {  
  57.             tmp = ep->name + strlen (ep->name);  
  58.         }  
  59.   
  60.         /* direction-restriction:  "..in-..", "out-.." */  
  61.         tmp--;  
  62.         if (!isdigit (*tmp)) {  
  63.             if (desc->bEndpointAddress & USB_DIR_IN) {  
  64.                 if ('n' != *tmp)  
  65.                     return 0;  
  66.             } else {  
  67.                 if ('t' != *tmp)  
  68.                     return 0;  
  69.             }  
  70.         }  
  71.     }  
  72.   
  73.     /*  
  74.      * Get the number of required streams from the EP companion  
  75.      * descriptor and see if the EP matches it  
  76.      */  
  77.     if (usb_endpoint_xfer_bulk(desc)) {  
  78.         if (ep_comp) {  
  79.             num_req_streams = ep_comp->bmAttributes & 0x1f;  
  80.             if (num_req_streams > ep->max_streams)  
  81.                 return 0;  
  82.             /* Update the ep_comp descriptor if needed */  
  83.             if (num_req_streams != ep->max_streams)  
  84.                 ep_comp->bmAttributes = ep->max_streams;  
  85.         }  
  86.   
  87.     }  
  88.   
  89.     /*  
  90.      * If the protocol driver hasn't yet decided on wMaxPacketSize  
  91.      * and wants to know the maximum possible, provide the info.  
  92.      */  
  93.     if (desc->wMaxPacketSize == 0)  
  94.         desc->wMaxPacketSize = cpu_to_le16(ep->maxpacket);  
  95.   
  96.     /* endpoint maxpacket size is an input parameter, except for bulk  
  97.      * where it's an output parameter representing the full speed limit.  
  98.      * the usb spec fixes high speed bulk maxpacket at 512 bytes.  
  99.      */  
  100.     max = 0x7ff & le16_to_cpu(desc->wMaxPacketSize);  
  101.     switch (type) {  
  102.     case USB_ENDPOINT_XFER_INT:  
  103.         /* INT:  limit 64 bytes full speed, 1024 high/super speed */  
  104.         if (!gadget->is_dualspeed && max > 64)  
  105.             return 0;  
  106.         /* FALLTHROUGH */  
  107.   
  108.     case USB_ENDPOINT_XFER_ISOC:  
  109.         /* ISO:  limit 1023 bytes full speed, 1024 high/super speed */  
  110.         if (ep->maxpacket < max)  
  111.             return 0;  
  112.         if (!gadget->is_dualspeed && max > 1023)  
  113.             return 0;  
  114.   
  115.         /* BOTH:  "high bandwidth" works only at high speed */  
  116.         if ((desc->wMaxPacketSize & cpu_to_le16(3<<11))) {  
  117.             if (!gadget->is_dualspeed)  
  118.                 return 0;  
  119.             /* configure your hardware with enough buffering!! */  
  120.         }  
  121.         break;  
  122.     }  
  123.   
  124.     /* MATCH!! */  
  125.   
  126.     /* report address */  
  127.     desc->bEndpointAddress &= USB_DIR_IN;  
  128.     if (isdigit (ep->name [2])) {  
  129.         u8  num = simple_strtoul (&ep->name [2], NULL, 10);  
  130.         desc->bEndpointAddress |= num;  
  131. #ifdef  MANY_ENDPOINTS  
  132.     } else if (desc->bEndpointAddress & USB_DIR_IN) {  
  133.         if (++in_epnum > 15)  
  134.             return 0;  
  135.         desc->bEndpointAddress = USB_DIR_IN | in_epnum;  
  136. #endif  
  137.     } else {  
  138.         if (++epnum > 15)  
  139.             return 0;  
  140.         desc->bEndpointAddress |= epnum;  
  141.     }  
  142.   
  143.     /* report (variable) full speed bulk maxpacket */  
  144.     if ((USB_ENDPOINT_XFER_BULK == type) && !ep_comp) {  
  145.         int size = ep->maxpacket;  
  146.   
  147.         /* min() doesn't work on bitfields with gcc-3.5 */  
  148.         if (size > 64)  
  149.             size = 64;  
  150.         desc->wMaxPacketSize = cpu_to_le16(size);  
  151.     }  
  152.     ep->address = desc->bEndpointAddress;  
  153.     return 1;  
  154. }  
ep_matches通过端口描述符的一些特性来和gadget ep_list进行比较,device controller在初始化endpoint时,会将endpoint的名字设置成好几种类型:

1.ep1,  ep2, ... 地址确定,方向和类型不确定;

2. ep1in, ep2out, ...地址和方向确定,类型不确定;

3. ep1-bulk, ep2-bulk, ... 地址和类型确定,方向不确定;

4. ep1in-bulk, ep2out-iso, ... 地址,方向和类型都确定;

5.  ep-* ... 没有任何限制;

ep_matches首先通过比较端口传输地址,方向和类型,然后再比较速度等信息来匹配,如果不匹配则返回0,否则如果条件都满足则返回1。

31-58行,首先根据endpoint的name和端口描述符所指定的传输类型进行比较,对于中断传输如'-'后面第二个字符是s,即表示iso,那肯定不匹配,直接返回,对于批量传输如果‘-’后面第一个字符不是b,则不匹配,对于等时传输,‘-’后第二个字符应该是s.

62-69根据端口描述符中的bEndpointAddress和endpoint中的name进行比较,如果端口传输方向为in,但发现name却不是以n字符结尾,则不匹配,如果端口传输方面是out,而name不以t结尾,则不匹配;

77-87行是对超高速设备进行判断;

93-94行,如果端口描述符里没有指定最大传输长度,但将当前endpoint的最大传输长度赋值给端口描述符。

端口描述符中的wMaxPacketSize用来表示,wMaxPacketSize中低11位用来表示最大传输长度,对于高速的中断和等时传输类型,wMaxPacketSize中的第12,13位用来表示每帧数据里额外传输事务的数量。

100-105行,通过端点传输类型,传输最大长度和端口速度来进行匹配,对于全速的中断传输,最大数据长度为64个字节,如大于64个字节,则不匹配;

108-120行,对于等时传输,如端口描述符里指定的最大传输长度大于endpoint里的最大传输长度,那肯定不匹配,在全速时最大数据长度不能超过1023个字节,而额外事务传输只有是在高速的情况下才能满足。

如果当前端口通过上面这些匹配条件,表明当前的endpoint就是所需的端口,接下来进行一些如端口传输方向,地址等设置。

运行到目前为止,device controller ,composite driver, gadget driver都已经成功注册到系统中,并完成了对复合设备配置,接口和端口添加和配置,表示usb设备准备完成 ,可以开始响应host 端的枚举请求。

3. 响应host枚举

host端枚举过程如下:
a. 当hub检测到hub状态寄存器发生变化时,去唤醒hub的守护进程,去查看具体是那 一个port引起的;
b.  如果发现有设备插入,等待100ms使设备稳定后,root hub会向插入设备的port发送reset请求,reset成功后usb设备处于default状态;
c. 向新插入的设备发送设置地址请求,用来设置设备地址;
d. 获取usb设备的设备描述符; 
e.根据usb设备的配置个数,获取对应usb设备配置描述符;

f. 选择e获取的配置描述符,选择合适 的usb配置,对usb设备进行配置;

对于usb device 而言,它不会主动的去和host进行数据传输,它都是处于被动的位置,它只是对host请求做出响应,请求都是由host发起。

由图2可以看到usb设备侧对host的请求都是通过中断进行触发的, device controller中断是在控制器初始化过程中申请的,中断处理函数为s3c_hsotg_irq,对于host的请求都是从这个函数开始。

[html]  view plain copy
  1. static irqreturn_t s3c_hsotg_irq(int irq, void *pw)  
  2. {  
  3.     struct s3c_hsotg *hsotg = pw;  
  4.     int retry_count = 8;  
  5.     u32 gintsts;  
  6.     u32 gintmsk;  
  7.   
  8. irq_retry:  
  9.     gintsts = readl(hsotg->regs + S3C_GINTSTS);  
  10.     gintmsk = readl(hsotg->regs + S3C_GINTMSK);  
  11.   
  12.     dev_dbg(hsotg->dev, "%s: %08x %08x (%08x) retry %d\n",  
  13.         __func__, gintsts, gintsts & gintmsk, gintmsk, retry_count);  
  14.   
  15.     gintsts &= gintmsk;  
  16.   
  17.     if (gintsts & S3C_GINTSTS_OTGInt) {  
  18.         u32 otgint = readl(hsotg->regs + S3C_GOTGINT);  
  19.   
  20.         dev_info(hsotg->dev, "OTGInt: %08x\n", otgint);  
  21.   
  22.         writel(otgint, hsotg->regs + S3C_GOTGINT);  
  23.     }  
  24.   
  25.     if (gintsts & S3C_GINTSTS_DisconnInt) {  
  26.         dev_dbg(hsotg->dev, "%s: DisconnInt\n", __func__);  
  27.         writel(S3C_GINTSTS_DisconnInt, hsotg->regs + S3C_GINTSTS);  
  28.   
  29.         s3c_hsotg_disconnect_irq(hsotg);  
  30.     }  
  31.   
  32.     if (gintsts & S3C_GINTSTS_SessReqInt) {  
  33.         dev_dbg(hsotg->dev, "%s: SessReqInt\n", __func__);  
  34.         writel(S3C_GINTSTS_SessReqInt, hsotg->regs + S3C_GINTSTS);  
  35.     }  
  36.   
  37.     if (gintsts & S3C_GINTSTS_EnumDone) {  
  38.         writel(S3C_GINTSTS_EnumDone, hsotg->regs + S3C_GINTSTS);  
  39.   
  40.         s3c_hsotg_irq_enumdone(hsotg);  
  41.     }  
  42.   
  43.     if (gintsts & S3C_GINTSTS_ConIDStsChng) {  
  44.         dev_dbg(hsotg->dev, "ConIDStsChg (DSTS=0x%08x, GOTCTL=%08x)\n",  
  45.             readl(hsotg->regs + S3C_DSTS),  
  46.             readl(hsotg->regs + S3C_GOTGCTL));  
  47.   
  48.         writel(S3C_GINTSTS_ConIDStsChng, hsotg->regs + S3C_GINTSTS);  
  49.     }  
  50.   
  51.     if (gintsts & (S3C_GINTSTS_OEPInt | S3C_GINTSTS_IEPInt)) {  
  52.         u32 daint = readl(hsotg->regs + S3C_DAINT);  
  53.         u32 daint_out = daint >> S3C_DAINT_OutEP_SHIFT;  
  54.         u32 daint_in = daint & ~(daint_out << S3C_DAINT_OutEP_SHIFT);  
  55.         int ep;  
  56.   
  57.         dev_dbg(hsotg->dev, "%s: daint=%08x\n", __func__, daint);  
  58.   
  59.         for (ep = 0; ep < 15 && daint_out; ep++, daint_out >>= 1) {  
  60.             if (daint_out & 1)  
  61.                 s3c_hsotg_epint(hsotg, ep, 0);  
  62.         }  
  63.   
  64.         for (ep = 0; ep < 15 && daint_in; ep++, daint_in >>= 1) {  
  65.             if (daint_in & 1)  
  66.                 s3c_hsotg_epint(hsotg, ep, 1);  
  67.         }  
  68.     }  
  69.   
  70.     if (gintsts & S3C_GINTSTS_USBRst) {  
  71.         dev_info(hsotg->dev, "%s: USBRst\n", __func__);  
  72.         dev_dbg(hsotg->dev, "GNPTXSTS=%08x\n",  
  73.             readl(hsotg->regs + S3C_GNPTXSTS));  
  74.   
  75.         writel(S3C_GINTSTS_USBRst, hsotg->regs + S3C_GINTSTS);  
  76.   
  77.         kill_all_requests(hsotg, &hsotg->eps[0], -ECONNRESET, true);  
  78.   
  79.         /* it seems after a reset we can end up with a situation  
  80.          * where the TXFIFO still has data in it... the docs  
  81.          * suggest resetting all the fifos, so use the init_fifo  
  82.          * code to relayout and flush the fifos.  
  83.          */  
  84.   
  85.         s3c_hsotg_init_fifo(hsotg);  
  86.   
  87.         s3c_hsotg_enqueue_setup(hsotg);  
  88.     }  
  89.   
  90.     /* check both FIFOs */  
  91.   
  92.     if (gintsts & S3C_GINTSTS_NPTxFEmp) {  
  93.         dev_dbg(hsotg->dev, "NPTxFEmp\n");  
  94.   
  95.         /* Disable the interrupt to stop it happening again  
  96.          * unless one of these endpoint routines decides that  
  97.          * it needs re-enabling */  
  98.   
  99.         s3c_hsotg_disable_gsint(hsotg, S3C_GINTSTS_NPTxFEmp);  
  100.         s3c_hsotg_irq_fifoempty(hsotg, false);  
  101.     }  
  102.   
  103.     if (gintsts & S3C_GINTSTS_PTxFEmp) {  
  104.         dev_dbg(hsotg->dev, "PTxFEmp\n");  
  105.   
  106.         /* See note in S3C_GINTSTS_NPTxFEmp */  
  107.   
  108.         s3c_hsotg_disable_gsint(hsotg, S3C_GINTSTS_PTxFEmp);  
  109.         s3c_hsotg_irq_fifoempty(hsotg, true);  
  110.     }  
  111.   
  112.     if (gintsts & S3C_GINTSTS_RxFLvl) {  
  113.         /* note, since GINTSTS_RxFLvl doubles as FIFO-not-empty,  
  114.          * we need to retry s3c_hsotg_handle_rx if this is still  
  115.          * set. */  
  116.   
  117.         s3c_hsotg_handle_rx(hsotg);  
  118.     }  
  119.   
  120.     if (gintsts & S3C_GINTSTS_ModeMis) {  
  121.         dev_warn(hsotg->dev, "warning, mode mismatch triggered\n");  
  122.         writel(S3C_GINTSTS_ModeMis, hsotg->regs + S3C_GINTSTS);  
  123.     }  
  124.   
  125.     if (gintsts & S3C_GINTSTS_USBSusp) {  
  126.         dev_info(hsotg->dev, "S3C_GINTSTS_USBSusp\n");  
  127.         writel(S3C_GINTSTS_USBSusp, hsotg->regs + S3C_GINTSTS);  
  128.   
  129.         call_gadget(hsotg, suspend);  
  130.     }  
  131.   
  132.     if (gintsts & S3C_GINTSTS_WkUpInt) {  
  133.         dev_info(hsotg->dev, "S3C_GINTSTS_WkUpIn\n");  
  134.         writel(S3C_GINTSTS_WkUpInt, hsotg->regs + S3C_GINTSTS);  
  135.   
  136.         call_gadget(hsotg, resume);  
  137.     }  
  138.   
  139.     if (gintsts & S3C_GINTSTS_ErlySusp) {  
  140.         dev_dbg(hsotg->dev, "S3C_GINTSTS_ErlySusp\n");  
  141.         writel(S3C_GINTSTS_ErlySusp, hsotg->regs + S3C_GINTSTS);  
  142.     }  
  143.   
  144.     /* these next two seem to crop-up occasionally causing the core  
  145.      * to shutdown the USB transfer, so try clearing them and logging  
  146.      * the occurrence. */  
  147.   
  148.     if (gintsts & S3C_GINTSTS_GOUTNakEff) {  
  149.         dev_info(hsotg->dev, "GOUTNakEff triggered\n");  
  150.   
  151.         writel(S3C_DCTL_CGOUTNak, hsotg->regs + S3C_DCTL);  
  152.   
  153.         s3c_hsotg_dump(hsotg);  
  154.     }  
  155.   
  156.     if (gintsts & S3C_GINTSTS_GINNakEff) {  
  157.         dev_info(hsotg->dev, "GINNakEff triggered\n");  
  158.   
  159.         writel(S3C_DCTL_CGNPInNAK, hsotg->regs + S3C_DCTL);  
  160.   
  161.         s3c_hsotg_dump(hsotg);  
  162.     }  
  163.   
  164.     /* if we've had fifo events, we should try and go around the  
  165.      * loop again to see if there's any point in returning yet. */  
  166.   
  167.     if (gintsts & IRQ_RETRY_MASK && --retry_count > 0)  
  168.             goto irq_retry;  
  169.   
  170.     return IRQ_HANDLED;  
  171. }  

s3c_hsotg_irq通过读取中断状态寄存器来确定发生什么中断,再通过中断使能寄存器来确定那些中断那是中断是合法的,然后清除中断的状态位,重新使能中断,最后根据不同中断源进行不同处理。

在这里有两个类型中断最为重要,端口中断和接收中断,如果发生了端口中断,则需要进一步去读取端口中断状态寄存器,来确定产生中断的端口及产生中断原因;如果产生了接收中断,则去FIFO里读取数据,如果当前帧接收完成,则会调用注册request时确定的回调函数通知request请求者;

51-68行,产生了端口中断,先去设备端口中断寄存器里读取产生中断端口,设备端口中断寄存器是一个32位寄存器,高16位对应out的16个端口,bit16对应out endpoint0 ,bit31对应out endpoint 15,而低16位对应in的16个端口,bit0对应in endpoint 0,bit15对应in endpoint15. 在确定产生中断的端口后,调用s3c_hsotg_epint()分别对out和in中产生中断的各端口进行处理。

[html]  view plain copy
  1. static void s3c_hsotg_epint(struct s3c_hsotg *hsotg, unsigned int idx,  
  2.                 int dir_in)  
  3. {  
  4.     struct s3c_hsotg_ep *hs_ep = &hsotg->eps[idx];  
  5.     u32 epint_reg = dir_in ? DIEPINT(idx) : DOEPINT(idx);  
  6.     u32 epctl_reg = dir_in ? DIEPCTL(idx) : DOEPCTL(idx);  
  7.     u32 epsiz_reg = dir_in ? DIEPTSIZ(idx) : DOEPTSIZ(idx);  
  8.     u32 ints;  
  9.   
  10.     ints = readl(hsotg->regs + epint_reg);  
  11.   
  12.     /* Clear endpoint interrupts */  
  13.     writel(ints, hsotg->regs + epint_reg);  
  14.   
  15.     dev_dbg(hsotg->dev, "%s: ep%d(%s) DxEPINT=0x%08x\n",  
  16.         __func__, idx, dir_in ? "in" : "out", ints);  
  17.   
  18.     if (ints & DxEPINT_XferCompl) {  
  19.         dev_dbg(hsotg->dev,  
  20.             "%s: XferCompl: DxEPCTL=0x%08x, DxEPTSIZ=%08x\n",  
  21.             __func__, readl(hsotg->regs + epctl_reg),  
  22.             readl(hsotg->regs + epsiz_reg));  
  23.   
  24.         /*  
  25.          * we get OutDone from the FIFO, so we only need to look  
  26.          * at completing IN requests here  
  27.          */  
  28.         if (dir_in) {  
  29.             s3c_hsotg_complete_in(hsotg, hs_ep);  
  30.   
  31.             if (idx == 0 && !hs_ep->req)  
  32.                 s3c_hsotg_enqueue_setup(hsotg);  
  33.         } else if (using_dma(hsotg)) {  
  34.             /*  
  35.              * We're using DMA, we need to fire an OutDone here  
  36.              * as we ignore the RXFIFO.  
  37.              */  
  38.   
  39.             s3c_hsotg_handle_outdone(hsotg, idx, false);  
  40.         }  
  41.     }  
  42.   
  43.     if (ints & DxEPINT_EPDisbld) {  
  44.         dev_dbg(hsotg->dev, "%s: EPDisbld\n", __func__);  
  45.   
  46.         if (dir_in) {  
  47.             int epctl = readl(hsotg->regs + epctl_reg);  
  48.   
  49.             s3c_hsotg_txfifo_flush(hsotg, idx);  
  50.   
  51.             if ((epctl & DxEPCTL_Stall) &&  
  52.                 (epctl & DxEPCTL_EPType_Bulk)) {  
  53.                 int dctl = readl(hsotg->regs + DCTL);  
  54.   
  55.                 dctl |= DCTL_CGNPInNAK;  
  56.                 writel(dctl, hsotg->regs + DCTL);  
  57.             }  
  58.         }  
  59.     }  
  60.   
  61.     if (ints & DxEPINT_AHBErr)  
  62.         dev_dbg(hsotg->dev, "%s: AHBErr\n", __func__);  
  63.   
  64.     if (ints & DxEPINT_Setup) {  /* Setup or Timeout */  
  65.         dev_dbg(hsotg->dev, "%s: Setup/Timeout\n",  __func__);  
  66.   
  67.         if (using_dma(hsotg) && idx == 0) {  
  68.             /*  
  69.              * this is the notification we've received a  
  70.              * setup packet. In non-DMA mode we'd get this  
  71.              * from the RXFIFO, instead we need to process  
  72.              * the setup here.  
  73.              */  
  74.   
  75.             if (dir_in)  
  76.                 WARN_ON_ONCE(1);  
  77.             else  
  78.                 s3c_hsotg_handle_outdone(hsotg, 0, true);  
  79.         }  
  80.     }  
  81.   
  82.     if (ints & DxEPINT_Back2BackSetup)  
  83.         dev_dbg(hsotg->dev, "%s: B2BSetup/INEPNakEff\n", __func__);  
  84.   
  85.     if (dir_in) {  
  86.         /* not sure if this is important, but we'll clear it anyway */  
  87.         if (ints & DIEPMSK_INTknTXFEmpMsk) {  
  88.             dev_dbg(hsotg->dev, "%s: ep%d: INTknTXFEmpMsk\n",  
  89.                 __func__, idx);  
  90.         }  
  91.   
  92.         /* this probably means something bad is happening */  
  93.         if (ints & DIEPMSK_INTknEPMisMsk) {  
  94.             dev_warn(hsotg->dev, "%s: ep%d: INTknEP\n",  
  95.                  __func__, idx);  
  96.         }  
  97.   
  98.         /* FIFO has space or is empty (see GAHBCFG) */  
  99.         if (hsotg->dedicated_fifos &&  
  100.             ints & DIEPMSK_TxFIFOEmpty) {  
  101.             dev_dbg(hsotg->dev, "%s: ep%d: TxFIFOEmpty\n",  
  102.                 __func__, idx);  
  103.             if (!using_dma(hsotg))  
  104.                 s3c_hsotg_trytx(hsotg, hs_ep);  
  105.         }  
  106.     }  
  107. }  
s3c_hsotg_epint会根据产生中断的不同方向和中断类型做出不同处理。

18-41行,表示端口产生了传输完成中断,它即可对应输入in类型,也可以对应输出out类型。如里是输入类型传输完成中断,即完成device->host传输,则会调用s3c_hsotg_complete_in对发送长度等信息进行统计,如需要发送0长数据做为发送结束,则向host传输0长度数据帧,如已发送数据长度,少于期望长度则继续开始发送请求,否则调用request的回调函数通知上层;对于out类型传输,即对应接收中断,usb设备会专门产生接收中断,它不在这里处理。

64-80表示,表示端口产生setup传输完成或超时中断。

回到s3c_hsotg_irq 的112-118行,这里表示RXFIFO非空,有数据需要读取,通过s3c_hsotg_handle_rx去处理。

[html]  view plain copy
  1. static void s3c_hsotg_handle_rx(struct s3c_hsotg *hsotg)  
  2. {  
  3.     u32 grxstsr = readl(hsotg->regs + S3C_GRXSTSP);  
  4.     u32 epnum, status, size;  
  5.   
  6.     WARN_ON(using_dma(hsotg));  
  7.   
  8.     epnum = grxstsr & S3C_GRXSTS_EPNum_MASK;  
  9.     status = grxstsr & S3C_GRXSTS_PktSts_MASK;  
  10.   
  11.     size = grxstsr & S3C_GRXSTS_ByteCnt_MASK;  
  12.     size >>= S3C_GRXSTS_ByteCnt_SHIFT;  
  13.   
  14.     if (1)  
  15.         dev_dbg(hsotg->dev, "%s: GRXSTSP=0x%08x (%d@%d)\n",  
  16.             __func__, grxstsr, size, epnum);  
  17.   
  18. #define __status(x) ((x) >> S3C_GRXSTS_PktSts_SHIFT)  
  19.   
  20.     switch (status >> S3C_GRXSTS_PktSts_SHIFT) {  
  21.     case __status(S3C_GRXSTS_PktSts_GlobalOutNAK):  
  22.         dev_dbg(hsotg->dev, "GlobalOutNAK\n");  
  23.         break;  
  24.   
  25.     case __status(S3C_GRXSTS_PktSts_OutDone):  
  26.         dev_dbg(hsotg->dev, "OutDone (Frame=0x%08x)\n",  
  27.             s3c_hsotg_read_frameno(hsotg));  
  28.   
  29.         if (!using_dma(hsotg))  
  30.             s3c_hsotg_handle_outdone(hsotg, epnum, false);  
  31.         break;  
  32.   
  33.     case __status(S3C_GRXSTS_PktSts_SetupDone):  
  34.         dev_dbg(hsotg->dev,  
  35.             "SetupDone (Frame=0x%08x, DOPEPCTL=0x%08x)\n",  
  36.             s3c_hsotg_read_frameno(hsotg),  
  37.             readl(hsotg->regs + S3C_DOEPCTL(0)));  
  38.   
  39.         s3c_hsotg_handle_outdone(hsotg, epnum, true);  
  40.         break;  
  41.   
  42.     case __status(S3C_GRXSTS_PktSts_OutRX):  
  43.         s3c_hsotg_rx_data(hsotg, epnum, size);  
  44.         break;  
  45.   
  46.     case __status(S3C_GRXSTS_PktSts_SetupRX):  
  47.         dev_dbg(hsotg->dev,  
  48.             "SetupRX (Frame=0x%08x, DOPEPCTL=0x%08x)\n",  
  49.             s3c_hsotg_read_frameno(hsotg),  
  50.             readl(hsotg->regs + S3C_DOEPCTL(0)));  
  51.   
  52.         s3c_hsotg_rx_data(hsotg, epnum, size);  
  53.         break;  
  54.   
  55.     default:  
  56.         dev_warn(hsotg->dev, "%s: unknown status %08x\n",  
  57.              __func__, grxstsr);  
  58.   
  59.         s3c_hsotg_dump(hsotg);  
  60.         break;  
  61.     }  
  62. }  
当RXFIFO中数据不为空时,表示有接收到数据,需要进行处理,s3c_hsotg_handle_rx,它会先确定产生中断的endpoint及数据包状态,然后再根据不同的状态做处不同处理。

08-18行,用来确定产生中断的endpoint端口号和接收到数据长度及数据包状态,共有5种数据包状态:OUT NAK, 收到OUT数据包,OUT数据包传输完成(设备侧接收完成),SETUP包传输完成,收到SETUP数据包;

21-23行,out nak中断,表示接收者不能接收数据;

不管是正常数据包还是SETUP包,收到数据都是通过s3c_hsotg_rx_data从FIFO读取数据,而如果当前的数据帧接收完成,则会通过s3c_hsotg_handle_outdone函数调用s3c_hsotg_complete_request来通知上层;

[html]  view plain copy
  1. static void s3c_hsotg_complete_request(struct s3c_hsotg *hsotg,  
  2.                        struct s3c_hsotg_ep *hs_ep,  
  3.                        struct s3c_hsotg_req *hs_req,  
  4.                        int result)  
  5. {  
  6.     bool restart;  
  7.   
  8.     if (!hs_req) {  
  9.         dev_dbg(hsotg->dev, "%s: nothing to complete?\n", __func__);  
  10.         return;  
  11.     }  
  12.   
  13.     dev_dbg(hsotg->dev, "complete: ep %p %s, req %p, %d => %p\n",  
  14.         hs_ep, hs_ep->ep.name, hs_req, result, hs_req->req.complete);  
  15.   
  16.     /*  
  17.      * only replace the status if we've not already set an error  
  18.      * from a previous transaction  
  19.      */  
  20.   
  21.     if (hs_req->req.status == -EINPROGRESS)  
  22.         hs_req->req.status = result;  
  23.   
  24.     hs_ep->req = NULL;  
  25.     list_del_init(&hs_req->queue);  
  26.   
  27.     if (using_dma(hsotg))  
  28.         s3c_hsotg_unmap_dma(hsotg, hs_ep, hs_req);  
  29.   
  30.     /*  
  31.      * call the complete request with the locks off, just in case the  
  32.      * request tries to queue more work for this endpoint.  
  33.      */  
  34.   
  35.     if (hs_req->req.complete) {  
  36.         spin_unlock(&hsotg->lock);  
  37.         hs_req->req.complete(&hs_ep->ep, &hs_req->req);  
  38.         spin_lock(&hsotg->lock);  
  39.     }  
  40.   
  41.     /*  
  42.      * Look to see if there is anything else to do. Note, the completion  
  43.      * of the previous request may have caused a new request to be started  
  44.      * so be careful when doing this.  
  45.      */  
  46.   
  47.     if (!hs_ep->req && result >= 0) {  
  48.         restart = !list_empty(&hs_ep->queue);  
  49.         if (restart) {  
  50.             hs_req = get_ep_head(hs_ep);  
  51.             s3c_hsotg_start_req(hsotg, hs_ep, hs_req, false);  
  52.         }  
  53.     }  
  54. }  

s3c_hsotg_complete_request首先会把req本身从endpoint的request队列里删除,然后再调用request的回调函数req->complete通知request请求者,在这里对应的回调函数为s3c_hsotg_complete_setup,最后会根据result的值来确定是否继续开始当前endpoint的其它request;

[html]  view plain copy
  1. static void s3c_hsotg_complete_setup(struct usb_ep *ep,  
  2.                      struct usb_request *req)  
  3. {  
  4.     struct s3c_hsotg_ep *hs_ep = our_ep(ep);  
  5.     struct s3c_hsotg *hsotg = hs_ep->parent;  
  6.   
  7.     if (req->status < 0) {  
  8.         dev_dbg(hsotg->dev, "%s: failed %d\n", __func__, req->status);  
  9.         return;  
  10.     }  
  11.   
  12.     if (req->actual == 0)  
  13.         s3c_hsotg_enqueue_setup(hsotg);  
  14.     else  
  15.         s3c_hsotg_process_control(hsotg, req->buf);  
  16. }  
s3c_hsotg_complete_setup它会调用s3c_hsotg_process_control对来自host的请求做出相应的处理;

[html]  view plain copy
  1. static void s3c_hsotg_process_control(struct s3c_hsotg *hsotg,  
  2.                       struct usb_ctrlrequest *ctrl)  
  3. {  
  4.     struct s3c_hsotg_ep *ep0 = &hsotg->eps[0];  
  5.     int ret = 0;  
  6.     u32 dcfg;  
  7.   
  8.     ep0->sent_zlp = 0;  
  9.   
  10.     dev_dbg(hsotg->dev, "ctrl Req=%02x, Type=%02x, V=%04x, L=%04x\n",  
  11.          ctrl->bRequest, ctrl->bRequestType,  
  12.          ctrl->wValue, ctrl->wLength);  
  13.   
  14.     /*  
  15.      * record the direction of the request, for later use when enquing  
  16.      * packets onto EP0.  
  17.      */  
  18.   
  19.     ep0->dir_in = (ctrl->bRequestType & USB_DIR_IN) ? 1 : 0;  
  20.     dev_dbg(hsotg->dev, "ctrl: dir_in=%d\n", ep0->dir_in);  
  21.   
  22.     /*  
  23.      * if we've no data with this request, then the last part of the  
  24.      * transaction is going to implicitly be IN.  
  25.      */  
  26.     if (ctrl->wLength == 0)  
  27.         ep0->dir_in = 1;  
  28.   
  29.     if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {  
  30.         switch (ctrl->bRequest) {  
  31.         case USB_REQ_SET_ADDRESS:  
  32.             dcfg = readl(hsotg->regs + DCFG);  
  33.             dcfg &= ~DCFG_DevAddr_MASK;  
  34.             dcfg |= ctrl->wValue << DCFG_DevAddr_SHIFT;  
  35.             writel(dcfg, hsotg->regs + DCFG);  
  36.   
  37.             dev_info(hsotg->dev, "new address %d\n", ctrl->wValue);  
  38.   
  39.             ret = s3c_hsotg_send_reply(hsotg, ep0, NULL, 0);  
  40.             return;  
  41.   
  42.         case USB_REQ_GET_STATUS:  
  43.             ret = s3c_hsotg_process_req_status(hsotg, ctrl);  
  44.             break;  
  45.   
  46.         case USB_REQ_CLEAR_FEATURE:  
  47.         case USB_REQ_SET_FEATURE:  
  48.             ret = s3c_hsotg_process_req_feature(hsotg, ctrl);  
  49.             break;  
  50.         }  
  51.     }  
  52.   
  53.     /* as a fallback, try delivering it to the driver to deal with */  
  54.   
  55.     if (ret == 0 && hsotg->driver) {  
  56.         ret = hsotg->driver->setup(&hsotg->gadget, ctrl);  
  57.         if (ret < 0)  
  58.             dev_dbg(hsotg->dev, "driver->setup() ret %d\n", ret);  
  59.     }  
  60.   
  61.     /*  
  62.      * the request is either unhandlable, or is not formatted correctly  
  63.      * so respond with a STALL for the status stage to indicate failure.  
  64.      */  
  65.   
  66.     if (ret < 0) {  
  67.         u32 reg;  
  68.         u32 ctrl;  
  69.   
  70.         dev_dbg(hsotg->dev, "ep0 stall (dir=%d)\n", ep0->dir_in);  
  71.         reg = (ep0->dir_in) ? DIEPCTL0 : DOEPCTL0;  
  72.   
  73.         /*  
  74.          * DxEPCTL_Stall will be cleared by EP once it has  
  75.          * taken effect, so no need to clear later.  
  76.          */  
  77.   
  78.         ctrl = readl(hsotg->regs + reg);  
  79.         ctrl |= DxEPCTL_Stall;  
  80.         ctrl |= DxEPCTL_CNAK;  
  81.         writel(ctrl, hsotg->regs + reg);  
  82.   
  83.         dev_dbg(hsotg->dev,  
  84.             "written DxEPCTL=0x%08x to %08x (DxEPCTL=0x%08x)\n",  
  85.             ctrl, reg, readl(hsotg->regs + reg));  
  86.   
  87.         /*  
  88.          * don't believe we need to anything more to get the EP  
  89.          * to reply with a STALL packet  
  90.          */  
  91.     }  
  92. }  
s3c_hsotg_process_control实现了一些和低层usb device controller相关的操作,如枚举时的设置地址请求,就是从这里开始的。

31-41行,对应USB枚举过程中的设备地址请求,在收到HOST的设备地址请求后,根据地址值会配置相应的地址寄存器,并通过s3c_hsotg_send_reply向HOST回复一个0长度的数据帧表示控制传输中的status传输。

42-44行,表示host请求获取设备,接口和端口状态,在收到请求后通过s3c_hsotg_send_reply回复host请求的状态;

47-49行,表示设置或清除设备的DEVICE_REMOTE_WAKEUP,端口的ENDPOINT_HALT等特征,这里实现了端口endpoint_halt设置和清除功能,在设置或清除后,向HOST回复0长度的数据帧。

55-59行,如果host发送了获取设备描述符,设置配置等和usb功能相关的请求,这些请求是和设备的功能相关,但和具体硬件无关,它一般在gadget driver里实现,这里会调用gadget driver 中的composite_setup函数,它实现了除和硬件相关之外的其它usb请求。

[html]  view plain copy
  1. static int  
  2. composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)  
  3. {  
  4.     struct usb_composite_dev    *cdev = get_gadget_data(gadget);  
  5.     struct usb_request      *req = cdev->req;  
  6.     int             value = -EOPNOTSUPP;  
  7.     int             status = 0;  
  8.     u16             w_index = le16_to_cpu(ctrl->wIndex);  
  9.     u8              intf = w_index & 0xFF;  
  10.     u16             w_value = le16_to_cpu(ctrl->wValue);  
  11.     u16             w_length = le16_to_cpu(ctrl->wLength);  
  12.     struct usb_function     *f = NULL;  
  13.     u8              endp;  
  14.   
  15.     /* partial re-init of the response message; the function or the  
  16.      * gadget might need to intercept e.g. a control-OUT completion  
  17.      * when we delegate to it.  
  18.      */  
  19.     req->zero = 0;  
  20.     req->complete = composite_setup_complete;  
  21.     req->length = 0;  
  22.     gadget->ep0->driver_data = cdev;  
  23.   
  24.     switch (ctrl->bRequest) {  
  25.   
  26.     /* we handle all standard USB descriptors */  
  27.     case USB_REQ_GET_DESCRIPTOR:  
  28.         if (ctrl->bRequestType != USB_DIR_IN)  
  29.             goto unknown;  
  30.         switch (w_value >> 8) {  
  31.   
  32.         case USB_DT_DEVICE:  
  33.             cdev->desc.bNumConfigurations =  
  34.                 count_configs(cdev, USB_DT_DEVICE);  
  35.             cdev->desc.bMaxPacketSize0 =  
  36.                 cdev->gadget->ep0->maxpacket;  
  37.             if (gadget_is_superspeed(gadget)) {  
  38.                 if (gadget->speed >= USB_SPEED_SUPER) {  
  39.                     cdev->desc.bcdUSB = cpu_to_le16(0x0300);  
  40.                     cdev->desc.bMaxPacketSize0 = 9;  
  41.                 } else {  
  42.                     cdev->desc.bcdUSB = cpu_to_le16(0x0210);  
  43.                 }  
  44.             }  
  45.   
  46.             value = min(w_length, (u16) sizeof cdev->desc);  
  47.             memcpy(req->buf, &cdev->desc, value);  
  48.             break;  
  49.         case USB_DT_DEVICE_QUALIFIER:  
  50.             if (!gadget_is_dualspeed(gadget) ||  
  51.                 gadget->speed >= USB_SPEED_SUPER)  
  52.                 break;  
  53.             device_qual(cdev);  
  54.             value = min_t(int, w_length,  
  55.                 sizeof(struct usb_qualifier_descriptor));  
  56.             break;  
  57.         case USB_DT_OTHER_SPEED_CONFIG:  
  58.             if (!gadget_is_dualspeed(gadget) ||  
  59.                 gadget->speed >= USB_SPEED_SUPER)  
  60.                 break;  
  61.             /* FALLTHROUGH */  
  62.         case USB_DT_CONFIG:  
  63.             value = config_desc(cdev, w_value);  
  64.             if (value >= 0)  
  65.                 value = min(w_length, (u16) value);  
  66.             break;  
  67.         case USB_DT_STRING:  
  68.             value = get_string(cdev, req->buf,  
  69.                     w_index, w_value & 0xff);  
  70.             if (value >= 0)  
  71.                 value = min(w_length, (u16) value);  
  72.             break;  
  73.         case USB_DT_BOS:  
  74.             if (gadget_is_superspeed(gadget)) {  
  75.                 value = bos_desc(cdev);  
  76.                 value = min(w_length, (u16) value);  
  77.             }  
  78.             break;  
  79.         }  
  80.         break;  
  81.   
  82.     /* any number of configs can work */  
  83.     case USB_REQ_SET_CONFIGURATION:  
  84.         if (ctrl->bRequestType != 0)  
  85.             goto unknown;  
  86.         if (gadget_is_otg(gadget)) {  
  87.             if (gadget->a_hnp_support)  
  88.                 DBG(cdev, "HNP available\n");  
  89.             else if (gadget->a_alt_hnp_support)  
  90.                 DBG(cdev, "HNP on another port\n");  
  91.             else  
  92.                 VDBG(cdev, "HNP inactive\n");  
  93.         }  
  94.         spin_lock(&cdev->lock);  
  95.         value = set_config(cdev, ctrl, w_value);  
  96.         spin_unlock(&cdev->lock);  
  97.         break;  
  98.     case USB_REQ_GET_CONFIGURATION:  
  99.         if (ctrl->bRequestType != USB_DIR_IN)  
  100.             goto unknown;  
  101.         if (cdev->config)  
  102.             *(u8 *)req->buf = cdev->config->bConfigurationValue;  
  103.         else  
  104.             *(u8 *)req->buf = 0;  
  105.         value = min(w_length, (u16) 1);  
  106.         break;  
  107.   
  108.     /* function drivers must handle get/set altsetting; if there's  
  109.      * no get() method, we know only altsetting zero works.  
  110.      */  
  111.     case USB_REQ_SET_INTERFACE:  
  112.         if (ctrl->bRequestType != USB_RECIP_INTERFACE)  
  113.             goto unknown;  
  114.         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)  
  115.             break;  
  116.         f = cdev->config->interface[intf];  
  117.         if (!f)  
  118.             break;  
  119.         if (w_value && !f->set_alt)  
  120.             break;  
  121.         value = f->set_alt(f, w_index, w_value);  
  122.         if (value == USB_GADGET_DELAYED_STATUS) {  
  123.             DBG(cdev,  
  124.              "%s: interface %d (%s) requested delayed status\n",  
  125.                     __func__, intf, f->name);  
  126.             cdev->delayed_status++;  
  127.             DBG(cdev, "delayed_status count %d\n",  
  128.                     cdev->delayed_status);  
  129.         }  
  130.         break;  
  131.     case USB_REQ_GET_INTERFACE:  
  132.         if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))  
  133.             goto unknown;  
  134.         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)  
  135.             break;  
  136.         f = cdev->config->interface[intf];  
  137.         if (!f)  
  138.             break;  
  139.         /* lots of interfaces only need altsetting zero... */  
  140.         value = f->get_alt ? f->get_alt(f, w_index) : 0;  
  141.         if (value < 0)  
  142.             break;  
  143.         *((u8 *)req->buf) = value;  
  144.         value = min(w_length, (u16) 1);  
  145.         break;  
  146.   
  147.     /*  
  148.      * USB 3.0 additions:  
  149.      * Function driver should handle get_status request. If such cb  
  150.      * wasn't supplied we respond with default value = 0  
  151.      * Note: function driver should supply such cb only for the first  
  152.      * interface of the function  
  153.      */  
  154.     case USB_REQ_GET_STATUS:  
  155.         if (!gadget_is_superspeed(gadget))  
  156.             goto unknown;  
  157.         if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))  
  158.             goto unknown;  
  159.         value = 2;  /* This is the length of the get_status reply */  
  160.         put_unaligned_le16(0, req->buf);  
  161.         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)  
  162.             break;  
  163.         f = cdev->config->interface[intf];  
  164.         if (!f)  
  165.             break;  
  166.         status = f->get_status ? f->get_status(f) : 0;  
  167.         if (status < 0)  
  168.             break;  
  169.         put_unaligned_le16(status & 0x0000ffff, req->buf);  
  170.         break;  
  171.     /*  
  172.      * Function drivers should handle SetFeature/ClearFeature  
  173.      * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied  
  174.      * only for the first interface of the function  
  175.      */  
  176.     case USB_REQ_CLEAR_FEATURE:  
  177.     case USB_REQ_SET_FEATURE:  
  178.         if (!gadget_is_superspeed(gadget))  
  179.             goto unknown;  
  180.         if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))  
  181.             goto unknown;  
  182.         switch (w_value) {  
  183.         case USB_INTRF_FUNC_SUSPEND:  
  184.             if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)  
  185.                 break;  
  186.             f = cdev->config->interface[intf];  
  187.             if (!f)  
  188.                 break;  
  189.             value = 0;  
  190.             if (f->func_suspend)  
  191.                 value = f->func_suspend(f, w_index >> 8);  
  192.             if (value < 0) {  
  193.                 ERROR(cdev,  
  194.                       "func_suspend() returned error %d\n",  
  195.                       value);  
  196.                 value = 0;  
  197.             }  
  198.             break;  
  199.         }  
  200.         break;  
  201.     default:  
  202. unknown:  
  203.         VDBG(cdev,  
  204.             "non-core control req%02x.%02x v%04x i%04x l%d\n",  
  205.             ctrl->bRequestType, ctrl->bRequest,  
  206.             w_value, w_index, w_length);  
  207.   
  208.         /* functions always handle their interfaces and endpoints...  
  209.          * punt other recipients (other, WUSB, ...) to the current  
  210.          * configuration code.  
  211.          *  
  212.          * REVISIT it could make sense to let the composite device  
  213.          * take such requests too, if that's ever needed:  to work  
  214.          * in config 0, etc.  
  215.          */  
  216.         switch (ctrl->bRequestType & USB_RECIP_MASK) {  
  217.         case USB_RECIP_INTERFACE:  
  218.             if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)  
  219.                 break;  
  220.             f = cdev->config->interface[intf];  
  221.             break;  
  222.   
  223.         case USB_RECIP_ENDPOINT:  
  224.             endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);  
  225.             list_for_each_entry(f, &cdev->config->functions, list) {  
  226.                 if (test_bit(endp, f->endpoints))  
  227.                     break;  
  228.             }  
  229.             if (&f->list == &cdev->config->functions)  
  230.                 f = NULL;  
  231.             break;  
  232.         }  
  233.   
  234.         if (f && f->setup)  
  235.             value = f->setup(f, ctrl);  
  236.         else {  
  237.             struct usb_configuration    *c;  
  238.   
  239.             c = cdev->config;  
  240.             if (c && c->setup)  
  241.                 value = c->setup(c, ctrl);  
  242.         }  
  243.   
  244.         goto done;  
  245.     }  
  246.   
  247.     /* respond with data transfer before status phase? */  
  248.     if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {  
  249.         req->length = value;  
  250.         req->zero = value < w_length;  
  251.         value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);  
  252.         if (value < 0) {  
  253.             DBG(cdev, "ep_queue --> %d\n", value);  
  254.             req->status = 0;  
  255.             composite_setup_complete(gadget->ep0, req);  
  256.         }  
  257.     } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {  
  258.         WARN(cdev,  
  259.             "%s: Delayed status not supported for w_length != 0",  
  260.             __func__);  
  261.     }  
  262.   
  263. done:  
  264.     /* device either stalls (value < 0) or reports success */  
  265.     return value;  
  266. }  

composite_setup会根据host的不同请求做出不同处理,这里主要包含获取设备,配置及字符串描述符请求、设置和获取usb配置请求、设备和获取usb接口请求、获取usb状态请求、设置和清除usb feature请求。

19-22行,初始化用于传输设备描述符等信息的request结构;

32-48表示获取设备描述符请求,将保存于composite_dev里的device desc拷贝到用来存放request发送数据的buf里。

57-61表示用来获取配置描述符请求,一个USB设备它有可能有多个配置,在枚举的时候,HOST端会遍历每个配置,获取相应的配置描述符。对于获取配置描述符这个请求,device端不仅仅会将配置描述符拷贝到用于存放request数据的buf里, 还会把这个配置里的接口,再对应接口里的端口描述符一起拷贝到有buf里,所以在host发送获取配置描述符后,它就得到了这个配置下面的接口和端口信息,如果它是OTG设备,它还会包含OTG的信息。

67-72,它用来获取USB设备的字符串描述符。

83-97表示收到设置配置请求,它会调用set_config函数去设置USB配置。

[html]  view plain copy
  1. static int set_config(struct usb_composite_dev *cdev,  
  2.         const struct usb_ctrlrequest *ctrl, unsigned number)  
  3. {  
  4.     struct usb_gadget   *gadget = cdev->gadget;  
  5.     struct usb_configuration *c = NULL;  
  6.     int         result = -EINVAL;  
  7.     unsigned        power = gadget_is_otg(gadget) ? 8 : 100;  
  8.     int         tmp;  
  9.   
  10.     if (number) {  
  11.         list_for_each_entry(c, &cdev->configs, list) {  
  12.             if (c->bConfigurationValue == number) {  
  13.                 /*  
  14.                  * We disable the FDs of the previous  
  15.                  * configuration only if the new configuration  
  16.                  * is a valid one  
  17.                  */  
  18.                 if (cdev->config)  
  19.                     reset_config(cdev);  
  20.                 result = 0;  
  21.                 break;  
  22.             }  
  23.         }  
  24.         if (result < 0)  
  25.             goto done;  
  26.     } else { /* Zero configuration value - need to reset the config */  
  27.         if (cdev->config)  
  28.             reset_config(cdev);  
  29.         result = 0;  
  30.     }  
  31.   
  32.     INFO(cdev, "%s speed config #%d: %s\n",  
  33.         ({ char *speed;  
  34.         switch (gadget->speed) {  
  35.         case USB_SPEED_LOW:  
  36.             speed = "low";  
  37.             break;  
  38.         case USB_SPEED_FULL:  
  39.             speed = "full";  
  40.             break;  
  41.         case USB_SPEED_HIGH:  
  42.             speed = "high";  
  43.             break;  
  44.         case USB_SPEED_SUPER:  
  45.             speed = "super";  
  46.             break;  
  47.         default:  
  48.             speed = "?";  
  49.             break;  
  50.         } ; speed; }), number, c ? c->label : "unconfigured");  
  51.   
  52.     if (!c)  
  53.         goto done;  
  54.   
  55.     cdev->config = c;  
  56.   
  57.     /* Initialize all interfaces by setting them to altsetting zero. */  
  58.     for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {  
  59.         struct usb_function *f = c->interface[tmp];  
  60.         struct usb_descriptor_header **descriptors;  
  61.   
  62.         if (!f)  
  63.             break;  
  64.   
  65.         /*  
  66.          * Record which endpoints are used by the function. This is used  
  67.          * to dispatch control requests targeted at that endpoint to the  
  68.          * function's setup callback instead of the current  
  69.          * configuration's setup callback.  
  70.          */  
  71.         switch (gadget->speed) {  
  72.         case USB_SPEED_SUPER:  
  73.             descriptors = f->ss_descriptors;  
  74.             break;  
  75.         case USB_SPEED_HIGH:  
  76.             descriptors = f->hs_descriptors;  
  77.             break;  
  78.         default:  
  79.             descriptors = f->descriptors;  
  80.         }  
  81.   
  82.         for (; *descriptors; ++descriptors) {  
  83.             struct usb_endpoint_descriptor *ep;  
  84.             int addr;  
  85.   
  86.             if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)  
  87.                 continue;  
  88.   
  89.             ep = (struct usb_endpoint_descriptor *)*descriptors;  
  90.             addr = ((ep->bEndpointAddress & 0x80) >> 3)  
  91.                  |  (ep->bEndpointAddress & 0x0f);  
  92.             set_bit(addr, f->endpoints);  
  93.         }  
  94.   
  95.         result = f->set_alt(f, tmp, 0);  
  96.         if (result < 0) {  
  97.             DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",  
  98.                     tmp, f->name, f, result);  
  99.   
  100.             reset_config(cdev);  
  101.             goto done;  
  102.         }  
  103.   
  104.         if (result == USB_GADGET_DELAYED_STATUS) {  
  105.             DBG(cdev,  
  106.              "%s: interface %d (%s) requested delayed status\n",  
  107.                     __func__, tmp, f->name);  
  108.             cdev->delayed_status++;  
  109.             DBG(cdev, "delayed_status count %d\n",  
  110.                     cdev->delayed_status);  
  111.         }  
  112.     }  
  113.   
  114.     /* when we return, be sure our power usage is valid */  
  115.     power = c->bMaxPower ? (2 * c->bMaxPower) : CONFIG_USB_GADGET_VBUS_DRAW;  
  116. done:  
  117.     usb_gadget_vbus_draw(gadget, power);  
  118.     if (result >= 0 && cdev->delayed_status)  
  119.         result = USB_GADGET_DELAYED_STATUS;  
  120.     return result;  
  121. }  

对于一个复合型USB设备, 它的当前配置保存在cdev->config里,在设置设备的配置时,它会根据配置的值先将与配置值相对应的配置初始化,然后将所需的配置保存到cdev->config里,一个配置里包含多个接口,一个接口下包含多个接口设置,一个接口设置里包含多个端口,在把指定配置保存到cdev->config后,调用usb配置中的set_alt函数将接口下的接口设置设置成0,这里通过sourcesink_set_alt来说明,set_alt的具体工作。

[html]  view plain copy
  1. static int sourcesink_set_alt(struct usb_function *f,  
  2.         unsigned intf, unsigned alt)  
  3. {  
  4.     struct f_sourcesink     *ss = func_to_ss(f);  
  5.     struct usb_composite_dev    *cdev = f->config->cdev;  
  6.   
  7.     if (ss->in_ep->driver_data)  
  8.         disable_source_sink(ss);  
  9.     return enable_source_sink(cdev, ss, alt);  
  10. }  

sourcesink_set_alt中有三个参数,一个是接口功能usb_function,

通过配置得到f_sourcesink和cdev ,然后判断端口中driver_data是不是已经赋值,如果已经赋值则把相应的端口disable,最后调用enable_source_sink函数;

[html]  view plain copy
  1. static int  
  2. enable_source_sink(struct usb_composite_dev *cdev, struct f_sourcesink *ss)  
  3. {  
  4.     int                 result = 0;  
  5.     struct usb_ep               *ep;  
  6.   
  7.     /* one endpoint writes (sources) zeroes IN (to the host) */  
  8.     ep = ss->in_ep;  
  9.     result = config_ep_by_speed(cdev->gadget, &(ss->function), ep);  
  10.     if (result)  
  11.         return result;  
  12.     result = usb_ep_enable(ep);  
  13.     if (result < 0)  
  14.         return result;  
  15.     ep->driver_data = ss;  
  16.   
  17.     result = source_sink_start_ep(ss, true);  
  18.     if (result < 0) {  
  19. fail:  
  20.         ep = ss->in_ep;  
  21.         usb_ep_disable(ep);  
  22.         ep->driver_data = NULL;  
  23.         return result;  
  24.     }  
  25.   
  26.     /* one endpoint reads (sinks) anything OUT (from the host) */  
  27.     ep = ss->out_ep;  
  28.     result = config_ep_by_speed(cdev->gadget, &(ss->function), ep);  
  29.     if (result)  
  30.         goto fail;  
  31.     result = usb_ep_enable(ep);  
  32.     if (result < 0)  
  33.         goto fail;  
  34.     ep->driver_data = ss;  
  35.   
  36.     result = source_sink_start_ep(ss, false);  
  37.     if (result < 0) {  
  38.         usb_ep_disable(ep);  
  39.         ep->driver_data = NULL;  
  40.         goto fail;  
  41.     }  
  42.   
  43.     DBG(cdev, "%s enabled\n", ss->function.name);  
  44.     return result;  
  45. }  

usb接口功能usb_function数据结构中有专门用来保存不同速度情况下接口和端口描述符头指针数组,descriptors用来存放全速描述符头指针,hs_descriptors用来存放高速描述符头指针,ss_descriptors用来存放超速描述符头指针,虽然usb端口可以在不同速度下工作,但是对于一个gadget device它的速度是固定的, 所以对一个USB端口进行配置时要根据gadget的速度来确定端口,在10-13行中,enable_source_sink会根据gadget所支持的速度来完成usb_ep配置。

[html]  view plain copy
  1. int config_ep_by_speed(struct usb_gadget *g,  
  2.             struct usb_function *f,  
  3.             struct usb_ep *_ep)  
  4. {  
  5.     struct usb_endpoint_descriptor *chosen_desc = NULL;  
  6.     struct usb_descriptor_header **speed_desc = NULL;  
  7.   
  8.     struct usb_ss_ep_comp_descriptor *comp_desc = NULL;  
  9.     int want_comp_desc = 0;  
  10.   
  11.     struct usb_descriptor_header **d_spd; /* cursor for speed desc */  
  12.   
  13.     if (!g || !f || !_ep)  
  14.         return -EIO;  
  15.   
  16.     /* select desired speed */  
  17.     switch (g->speed) {  
  18.     case USB_SPEED_SUPER:  
  19.         if (gadget_is_superspeed(g)) {  
  20.             speed_desc = f->ss_descriptors;  
  21.             want_comp_desc = 1;  
  22.             break;  
  23.         }  
  24.         /* else: Fall trough */  
  25.     case USB_SPEED_HIGH:  
  26.         if (gadget_is_dualspeed(g)) {  
  27.             speed_desc = f->hs_descriptors;  
  28.             break;  
  29.         }  
  30.         /* else: fall through */  
  31.     default:  
  32.         speed_desc = f->descriptors;  
  33.     }  
  34.     /* find descriptors */  
  35.     for_each_ep_desc(speed_desc, d_spd) {  
  36.         chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;  
  37.         if (chosen_desc->bEndpointAddress == _ep->address)  
  38.             goto ep_found;  
  39.     }  
  40.     return -EIO;  
  41.   
  42. ep_found:  
  43.     /* commit results */  
  44.     _ep->maxpacket = le16_to_cpu(chosen_desc->wMaxPacketSize);  
  45.     _ep->desc = chosen_desc;  
  46.     _ep->comp_desc = NULL;  
  47.     _ep->maxburst = 0;  
  48.     _ep->mult = 0;  
  49.     if (!want_comp_desc)  
  50.         return 0;  
  51.   
  52.     /*  
  53.      * Companion descriptor should follow EP descriptor  
  54.      * USB 3.0 spec, #9.6.7  
  55.      */  
  56.     comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);  
  57.     if (!comp_desc ||  
  58.         (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))  
  59.         return -EIO;  
  60.     _ep->comp_desc = comp_desc;  
  61.     if (g->speed == USB_SPEED_SUPER) {  
  62.         switch (usb_endpoint_type(_ep->desc)) {  
  63.         case USB_ENDPOINT_XFER_BULK:  
  64.         case USB_ENDPOINT_XFER_INT:  
  65.             _ep->maxburst = comp_desc->bMaxBurst;  
  66.             break;  
  67.         case USB_ENDPOINT_XFER_ISOC:  
  68.             /* mult: bits 1:0 of bmAttributes */  
  69.             _ep->mult = comp_desc->bmAttributes & 0x3;  
  70.             break;  
  71.         default:  
  72.             /* Do nothing for control endpoints */  
  73.             break;  
  74.         }  
  75.     }  
  76.     return 0;  
  77. }  

17-33行,根据gadget的速度来获取端口描述符头指针,并保存在chose_desc里;

35-39行,从端口描述符头指针里获取端口描述符,并于给定的ep的地址比较,如果相同,表示找到相应端口,找到端口后补全usb_ep结构中的最大传输长度和端口描述符,如果是超速USB设备,则还需要补全用于描述高速端口的描述符。

由config_ep_by_speed找到相匹配的端口后,通过usb_ep_enable使能端口,usb_ep_enable里调用了和硬件相关的usb_ep_ops中的enable函数,这里是s3c_hsotg_ep_enable,接着赋值ep的driver_data.

在使能端口后,就要为这个端口申请用于request的资源,回调函数,并将request加入到端口的请求队列里,这个工作由38行的source_sink_start_ep完成。

[html]  view plain copy
  1. static int source_sink_start_ep(struct f_sourcesink *ss, bool is_in)  
  2. {  
  3.     struct usb_ep       *ep;  
  4.     struct usb_request  *req;  
  5.     int         status;  
  6.   
  7.     ep = is_in ? ss->in_ep : ss->out_ep;  
  8.     req = alloc_ep_req(ep);  
  9.     if (!req)  
  10.         return -ENOMEM;  
  11.   
  12.     req->complete = source_sink_complete;  
  13.     if (is_in)  
  14.         reinit_write_data(ep, req);  
  15.     else  
  16.         memset(req->buf, 0x55, req->length);  
  17.   
  18.     status = usb_ep_queue(ep, req, GFP_ATOMIC);  
  19.     if (status) {  
  20.         struct usb_composite_dev    *cdev;  
  21.   
  22.         cdev = ss->function.config->cdev;  
  23.         ERROR(cdev, "start %s %s --> %d\n",  
  24.                 is_in ? "IN" : "OUT",  
  25.                 ep->name, status);  
  26.         free_ep_req(ep, req);  
  27.     }  
  28.   
  29.     return status;  
  30. }  
08行,调用alloc_ep_req为endpoint申请request请求数据结构,并为request分配用于存放传输数据的buf。

12行,将request的回调函数赋值给req->complete,当这个端口传输完成后通过这个回调函数来通知上层,实现source_sink功能;

13行,如果是in类型传输,即从device->host则根据pattern来初始化传输的数据。

18行,将当前端口的request加入到端口的request队列中,这个功能通过调用与硬件相关的queue函数实现,这里是调用s3c_hsotg_ep_queue。
对于source_sink配置,它有两个端口,即in和out,一个用于接收来自HOST的数据,一个用于向host发送数据,所以配置完in端口后,还需要配置out端口,到这里为止就算设置完成 配置了。

由此可见,对于来自host的设置配置请求,对于复合型的设备,它将配置值对应的配置保存在复合型结构cdev的config中,用来表示当前配置,再将这个配置下的接口和端口使能,并为各个端口申请请求资源,将其加入到端口的请求队列中,等待事件处发。

讲完了usb设备的设置配置请求后,回到composite_bind。

98-106行,获取usb当前配置值,把它保存在用于存放request传输数据的buf里。

111-129行,配置当前配置接口设置请求,通过调用sourcesink_set_alt函数来为当前usb配置下由usb请求中中的index指定的接口配置由w_value指定的接口设置。

131-146,获取当前配置下某个接口的接口设置。

对于接下来的获取某个状态和设置、清除feature这里就不深入研究了。

其实到这里为止,USB的枚举已经算是完成了,与枚举有关的USB请求主要有设置USB地址,获取设备,配置描述符,然后是设置配置。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
musb 中文翻译和英文文档.可以通过会话请求协议(SRP)发起USB流量,而双角色设备同时支持SRP和主机协商协议(HNP),并且可以根据需要担任主机或外设的角色。MUSBMHDRC还支持拆事务,这反过来允许它支持使用带有USB 2.0集线器的全速度或低速设备。核心还包括支持在不使用时关闭便携式设备。 除了端点0之外,MUSBMHDRC是用户可配置的,可支持最多15个‘传输’端点和/或最多15个‘接收’端点。(对于IN事务和OUT事务使用这些端点取决于MUSBMHDRC是用作外设还是用作主机。当用作外设时,IN事务通过TX端点处理,OUT事务通过Rx端点处理。当用作主机时,IN事务通过Rx端点处理,OUT事务通过TX端点处理。)这些附加端点可以在软件中单独配置,以处理批量传输(这也允许它们处理中断传输)、同步传输或控制传输。此外,还可以动态地将端点配给不同的目标设备函数——最大限度地同时支持设备的数量。 每个端点都需要一个FIFO与之关联。MUSBMHDRC有一个RAM接口,用于连接到用于所有端点FIFOs的同步单端口RAM的单个块。(RAM块本身需要由用户添加。) 端点0的FIFO需要为64字节深,并缓冲1个数据包。RAM接口可以根据其他端点FIFOs进行配置,它的大小可以从8到8192字节,可以缓冲1个或2个数据包。单独的FIFOs可以与每个端点相关联:或者,具有相同端点编号的TX端点和Rx端点可以配置为使用相同的FIFO,例如,如果它们永远不能同时活动,可以减少所需RAM块的大小。 MUSBMHDRC提供了一个32位同步CPU接口,设计用于连接AMBA AHB bus1。接口支持使用AHB总线运行在一个大范围的总线速度。AHB总线上的多层操作也被支持。通过添加合适的包装器/桥接器,MUSBMHDRC还可以很容易地连接到一系列其他标准总线。 还支持对端点FIFOs的DMA访问。 MUSBMHDRC提供了一个UTMI+ 3级兼容接口,用于连接到一个合适的USB高/全速收发器。包含了一个可选的ULPI链接包装器(在musbhdrc /docs目录中包含的musbhdrc_ulpi_an.pdf文档中描述),用于连接到与ULPI兼容的物理。另一种接口也提供,允许使用USB 1.1与核心全速PHY,但仅为全速和低速事务。(此接口见8.1节)。 MUSBMHDRC提供发送和接收USB数据包所需的所有编码、解码、检查和重新请求——仅当端点数据已被成功传输时才中断CPU。 当充当主机时,MUSBMHDRC另外维护一个帧计数器,并自动调度SOF、同步、中断和批量传输。它还包括对在点对点通信中使用的会话请求和主机协商协议的支持,其细节在USB 2.0规范的USB on - go补充中给出。MUSBMHDRC提供了一系列的测试模式——主要是USB 2.0规范中描述的高速运行的四种测试模式。它还包括选项,允许它被迫进入全速模式,高速模式或主机模式。最后一个可能在帮助调试硬件PHY问题时有用。 提供了图形用户界面脚本,用于根据用户的需求配置核心。要使用的脚本取决于所选的CPU接口。请注意:在撰写本文时,内核仅在Verilog中可用。 本规范应与USB运行规范一起阅读,该规范还提供了电源要求、电压水平、连接器等细节。.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值