系统相关
首页 > 系统相关> > linux usb 总线驱动(二)

linux usb 总线驱动(二)

作者:互联网

原文:https://blog.csdn.net/weiqing1981127/article/details/8215708 

2.USB鼠标驱动 usbmouse.c

下面我们分析下USB鼠标驱动,鼠标输入HID类型,其数据传输采用中断URB,鼠标端点类型为IN。好了,我们先看看这个驱动的模块加载部分。

static int __init usb_mouse_init(void)

{

     int retval = usb_register(&usb_mouse_driver);

     if (retval == 0)

            printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"

                          DRIVER_DESC "\n");

     return retval;

}

模块加载部分仍然是调用usb_register注册USB驱动,我们跟踪看看被注册的usb_mouse_driver

static struct usb_driver usb_mouse_driver = {

     .name             = "usbmouse",    //驱动名

     .probe            = usb_mouse_probe,  //探测

     .disconnect     = usb_mouse_disconnect,

     .id_table  = usb_mouse_id_table,  //支持项

};

关于设备支持项我们前面已经讨论过了

static struct usb_device_id usb_mouse_id_table [] = {

{USB_INTERFACE_INFO(USB_INTERFACE_CLASS_HID, USB_INTERFACE_SUBCLASS_BOOT,

            USB_INTERFACE_PROTOCOL_MOUSE) },

     { }  

};

再细细看看USB_INTERFACE_INFO宏的定义

#define USB_INTERFACE_INFO(cl, sc, pr) \

     .match_flags = USB_DEVICE_ID_MATCH_INT_INFO, \

     .bInterfaceClass = (cl), \

     .bInterfaceSubClass = (sc), \

     .bInterfaceProtocol = (pr)

根据宏,我们知道,我们设置的支持项包括接口类,接口子类,接口协议三个匹配项。

好了,我们主要看看usb_driver中定义的probe函数

static int usb_mouse_probe(struct usb_interface *intf, const struct usb_device_id *id)

{

     struct usb_device *dev = interface_to_usbdev(intf);  //由接口获取usb_device

     struct usb_host_interface *interface;   //设置

     struct usb_endpoint_descriptor *endpoint;  //端点描述符

     struct usb_mouse *mouse            //本驱动私有结构体

     struct input_dev *input_dev;          //输入结构体

     int pipe, maxp;

     int error = -ENOMEM;

     interface = intf->cur_altsetting;          //获取设置

     if (interface->desc.bNumEndpoints != 1)    //鼠标端点只有1个

            return -ENODEV;

     endpoint = &interface->endpoint[0].desc;   //获得端点描述符

     if (!usb_endpoint_is_int_in(endpoint))       //检查该端点是否是中断输入端点

            return -ENODEV;

     pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);   //建立中断输入端点

     //返回端点能传输的最大的数据包,鼠标的返回的最大数据包为4个字节

maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));    

     mouse = kzalloc(sizeof(struct usb_mouse), GFP_KERNEL);  //分配mouse结构体

     input_dev = input_allocate_device();    //分配input设备空间

     if (!mouse || !input_dev)

            goto fail1;

     mouse->data = usb_buffer_alloc(dev, 8, GFP_ATOMIC, &mouse->data_dma); //分配缓冲区

     if (!mouse->data)

            goto fail1;

     mouse->irq = usb_alloc_urb(0, GFP_KERNEL);   //分配urb

     if (!mouse->irq)

            goto fail2;

     mouse->usbdev = dev;        //填充mouse的usb_device结构体  

     mouse->dev = input_dev;     //填充mouse的 input结构体

     if (dev->manufacturer)    //拷贝厂商ID

            strlcpy(mouse->name, dev->manufacturer, sizeof(mouse->name));

     if (dev->product) {   //拷贝产品ID

            if (dev->manufacturer)

                   strlcat(mouse->name, " ", sizeof(mouse->name));

            strlcat(mouse->name, dev->product, sizeof(mouse->name));

     }

     if (!strlen(mouse->name))   //拷贝产品ID

            snprintf(mouse->name, sizeof(mouse->name),

                    "USB HIDBP Mouse %04x:%04x",

                    le16_to_cpu(dev->descriptor.idVendor),

                    le16_to_cpu(dev->descriptor.idProduct));

     usb_make_path(dev, mouse->phys, sizeof(mouse->phys));

     strlcat(mouse->phys, "/input0", sizeof(mouse->phys));

     input_dev->name = mouse->name;   //将鼠标名赋给内嵌input结构体

     input_dev->phys = mouse->phys;    //将鼠标设备节点名赋给内嵌input结构体

     usb_to_input_id(dev, &input_dev->id);  //将usb_driver的支持项拷贝给input

     input_dev->dev.parent = &intf->dev;     

     //evbit表明支持按键事件(EV_KEY)和相对坐标事件(EV_REL)

     input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);

     //keybit表明按键值包括左键、右键和中键

     input_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |

            BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);

     //relbit表明相对坐标事件值包括X坐标和Y坐标

     input_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);

    //keybit表明除了左键、右键和中键,还支持其他按键

     input_dev->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_SIDE) |

            BIT_MASK(BTN_EXTRA);

    //relbit表明除了X坐标和Y坐标,还支持中键滚轮的滚动值

     input_dev->relbit[0] |= BIT_MASK(REL_WHEEL);

     input_set_drvdata(input_dev, mouse);  //将mouse设置为input的私有数据

     input_dev->open = usb_mouse_open;    //input设备的open

     input_dev->close = usb_mouse_close;

     usb_fill_int_urb(mouse->irq, dev, pipe, mouse->data, (maxp > 8 ? 8 : maxp),

                    usb_mouse_irq, mouse, endpoint->bInterval);  //填充urb

     mouse->irq->transfer_dma = mouse->data_dma;  

     mouse->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; //使用transfer_dma

     error = input_register_device(mouse->dev);  //注册input设备

     if (error)

            goto fail3;

     usb_set_intfdata(intf, mouse);

     return 0;

fail3:     

     usb_free_urb(mouse->irq);

fail2:     

     usb_buffer_free(dev, 8, mouse->data, mouse->data_dma);

fail1:     

     input_free_device(input_dev);

     kfree(mouse);

     return error;

}

其实上面这个probe主要是初始化usb设备和input设备,终极目标是为了完成urb的提交和input设备的注册。由于注册为input设备类型,那么当用户层open打开设备时候,最终会调用input中的open实现打开,我们看看input中open的实现

static int usb_mouse_open(struct input_dev *dev)

{

     struct usb_mouse *mouse = input_get_drvdata(dev);  //获取私有数据

     mouse->irq->dev = mouse->usbdev;  //获取urb指针

     if (usb_submit_urb(mouse->irq, GFP_KERNEL))  //提交urb

            return -EIO;

     return 0;

}

好了,当用户层open打开这个USB鼠标后,我们就已经将urb提交给了USB核心,那么根据USB数据处理流程知道,当处理完毕后,USB核心会通知USB设备驱动程序,这里我们是响应中断服务程序,这就相当于该URB的回调函数。我们在提交urb时候定义了中断服务程序usb_mouse_irq,我们跟踪看看

static void usb_mouse_irq(struct urb *urb)

{

     struct usb_mouse *mouse = urb->context;

     signed char *data = mouse->data;

     struct input_dev *dev = mouse->dev;

     int status;

     switch (urb->status) {

     case 0:                  //成功

            break;

     case -ECONNRESET:    //未连接

     case -ENOENT:

     case -ESHUTDOWN:

            return;

     default:          

            goto resubmit;   //数据处理没成功,重新提交urb

     }

     input_report_key(dev, BTN_LEFT,   data[0] & 0x01);    //鼠标左键

     input_report_key(dev, BTN_RIGHT,  data[0] & 0x02);    //鼠标右键

     input_report_key(dev, BTN_MIDDLE, data[0] & 0x04);    //鼠标中键

     input_report_key(dev, BTN_SIDE,   data[0] & 0x08);    //鼠标SIDE

     input_report_key(dev, BTN_EXTRA,  data[0] & 0x10);    //鼠标EXTRA

     input_report_rel(dev, REL_X,     data[1]);  //鼠标的水平位移

     input_report_rel(dev, REL_Y,     data[2]);  //鼠标的垂直位移

     input_report_rel(dev, REL_WHEEL, data[3]); //鼠标的滚轮滚动值

     input_sync(dev);

resubmit:

     status = usb_submit_urb (urb, GFP_ATOMIC);  //再次提交urb,等待下次响应

     if (status)

            err ("can't resubmit intr, %s-%s/input0, status %d",

                          mouse->usbdev->bus->bus_name,

                          mouse->usbdev->devpath, status);

}

根据上面的中断服务程序,我们应该知道,系统是周期性地获取鼠标的事件信息,因此在URB回调函数的末尾再次提交URB请求块,这样又会调用新的回调函数,周而复始。在回调函数中提交URB只能是GFP_ATOMIC优先级,因为URB回调函数运行于中断上下文中禁止导致睡眠的行为。而在提交URB过程中可能会需要申请内存、保持信号量,这些操作或许会导致USB内核睡眠。

最后我们再看看这个驱动的私有数据mouse的定义

struct usb_mouse {

     char name[128];             //名字

     char phys[64];              //设备节点

     struct usb_device *usbdev;    //内嵌usb_device设备

     struct input_dev *dev;        //内嵌input_dev设备

     struct urb *irq;              //urb结构体

     signed char *data;           //transfer_buffer缓冲区

     dma_addr_t data_dma;       // transfer _dma缓冲区

};

在上面这个结构体中,每一个成员的作用都应该很清楚了,尤其最后两个的使用区别和作用,前面也已经说过。

如果最终需要测试这个USB鼠标驱动,需要在内核中配置USB支持、对HID接口的支持、对OHCI HCD驱动的支持。另外,将驱动移植到开发板之后,由于采用的是input设备模型,所以还需要开发板带LCD屏才能测试。

 

3.USB键盘驱动usbkbd.c

跟USB鼠标类型,USB键盘也属于HID类型,代码在/dirver/hid/usbhid/usbkbd.c下。USB键盘除了提交中断URB外,还需要提交控制URB。不多话,我们看代码

static int __init usb_kbd_init(void)

{

     int result = usb_register(&usb_kbd_driver);  //注册USB驱动

     if (result == 0)

            printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"

                          DRIVER_DESC "\n");

     return result;

}

static struct usb_driver usb_kbd_driver = {

     .name =          "usbkbd",

     .probe =  usb_kbd_probe,

     .disconnect =  usb_kbd_disconnect,

     .id_table =      usb_kbd_id_table,

};

大家都懂,下面跟踪usb_driver中的probe

static int usb_kbd_probe(struct usb_interface *iface,

                    const struct usb_device_id *id)

{

     struct usb_device *dev = interface_to_usbdev(iface);  //由接口获得设备

     struct usb_host_interface *interface;   //设置

     struct usb_endpoint_descriptor *endpoint;  //端点描述符

     struct usb_kbd *kbd;     //私有数据

     struct input_dev *input_dev;  //input设备

     int i, pipe, maxp;       

     int error = -ENOMEM;

     interface = iface->cur_altsetting;   //获得设置

     if (interface->desc.bNumEndpoints != 1)  //只有一个端点

            return -ENODEV;

     endpoint = &interface->endpoint[0].desc;  //获取端点描述符

     if (!usb_endpoint_is_int_in(endpoint))      //端点必须是中断输入端点

            return -ENODEV;

     pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);   //建立中断输入端点

     maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));  //获取返回字节大小

     kbd = kzalloc(sizeof(struct usb_kbd), GFP_KERNEL);  //分配私有数据空间

     input_dev = input_allocate_device();            //分配input设备空间

     if (!kbd || !input_dev)

            goto fail1;

     if (usb_kbd_alloc_mem(dev, kbd))             //分配urb空间和其他缓冲空间

            goto fail2;

     kbd->usbdev = dev;                        //给内嵌结构体赋值

     kbd->dev = input_dev;                        //给内嵌结构体赋值

     if (dev->manufacturer)

            strlcpy(kbd->name, dev->manufacturer, sizeof(kbd->name));

     if (dev->product) {

            if (dev->manufacturer)

                   strlcat(kbd->name, " ", sizeof(kbd->name));

            strlcat(kbd->name, dev->product, sizeof(kbd->name));

     }

     if (!strlen(kbd->name))

            snprintf(kbd->name, sizeof(kbd->name),

                    "USB HIDBP Keyboard %04x:%04x",

                    le16_to_cpu(dev->descriptor.idVendor),

                    le16_to_cpu(dev->descriptor.idProduct));

     usb_make_path(dev, kbd->phys, sizeof(kbd->phys));

     strlcpy(kbd->phys, "/input0", sizeof(kbd->phys));

     input_dev->name = kbd->name;

     input_dev->phys = kbd->phys;

     usb_to_input_id(dev, &input_dev->id);     //复制usb_driver的支持项给input的支持项

     input_dev->dev.parent = &iface->dev;

     input_set_drvdata(input_dev, kbd);       //将kbd设置为input的私有数据

     input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_LED) |

            BIT_MASK(EV_REP);

     input_dev->ledbit[0] = BIT_MASK(LED_NUML) | BIT_MASK(LED_CAPSL) |

            BIT_MASK(LED_SCROLLL) | BIT_MASK(LED_COMPOSE) |

            BIT_MASK(LED_KANA);

     for (i = 0; i < 255; i++)

            set_bit(usb_kbd_keycode[i], input_dev->keybit);

     clear_bit(0, input_dev->keybit);

     input_dev->event = usb_kbd_event;  //定义event函数

     input_dev->open = usb_kbd_open;

     input_dev->close = usb_kbd_close;

     usb_fill_int_urb(kbd->irq, dev, pipe,kbd->new, (maxp > 8 ? 8 : maxp),

                    usb_kbd_irq, kbd, endpoint->bInterval);  //填充中断urb

     kbd->irq->transfer_dma = kbd->new_dma; 

     kbd->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;  //dma方式传输

     kbd->cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;

     kbd->cr->bRequest = 0x09;   //设置控制请求的格式

     kbd->cr->wValue = cpu_to_le16(0x200);

     kbd->cr->wIndex = cpu_to_le16(interface->desc.bInterfaceNumber);

     kbd->cr->wLength = cpu_to_le16(1);

     usb_fill_control_urb(kbd->led, dev, usb_sndctrlpipe(dev, 0), (void *) kbd->cr, kbd->leds, 1,

                        usb_kbd_led, kbd);   //填充控制urb

     kbd->led->setup_dma = kbd->cr_dma;

     kbd->led->transfer_dma = kbd->leds_dma;

     kbd->led->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP | URB_NO_SETUP_DMA_MAP);   //设置dma和setup_dma有效

     error = input_register_device(kbd->dev);   //注册input设备

     if (error)

            goto fail2;

     usb_set_intfdata(iface, kbd);

     return 0;

fail2:     

     usb_kbd_free_mem(dev, kbd);

fail1:     

     input_free_device(input_dev);

     kfree(kbd);

     return error;

}

在上面的probe中,我们主要是初始化一些结构体,然后提交中断urb和控制urb,并注册input设备。其中有几个地方需要细看下,其一,usb_kbd_alloc_mem的实现。其二,设置控制请求的格式。

先来看看usb_kbd_alloc_mem的实现

static int usb_kbd_alloc_mem(struct usb_device *dev, struct usb_kbd *kbd)

{

     if (!(kbd->irq = usb_alloc_urb(0, GFP_KERNEL)))  //分配中断urb

            return -1;

     if (!(kbd->led = usb_alloc_urb(0, GFP_KERNEL)))  //分配控制urb

            return -1;

     if (!(kbd->new = usb_buffer_alloc(dev, 8, GFP_ATOMIC, &kbd->new_dma)))            return -1;

       if (!(kbd->cr = usb_buffer_alloc(dev, sizeof(struct usb_ctrlrequest), GFP_ATOMIC, &kbd->cr_dma)))              //分配控制urb使用的控制请求描述符

            return -1;

     if (!(kbd->leds = usb_buffer_alloc(dev, 1, GFP_ATOMIC, &kbd->leds_dma)))

            return -1;                   //分配中断urb使用的缓冲区

     return 0;

}

这里我们需要明白中断urb和控制urb需要分配不同的urb结构体,同时在提交urb之前,需要填充的内容也不同,中断urb填充的是缓冲区和中断处理函数,控制urb填充的是控制请求描述符合回调函数。

好了,接着我们解决第二个问题,设置控制请求的格式。cr是struct usb_ctrlrequest结构的指针,USB协议中规定一个控制请求的格式为一个8个字节的数据包,其定义如下

struct usb_ctrlrequest {

     __u8 bRequestType;  //设定传输方向、请求类型等

     __u8 bRequest;  //指定哪个请求,可以是规定的标准值也可以是厂家定义的值

     __le16 wValue;  //即将写到寄存器的数据

     __le16 wIndex;  //接口数量,也就是寄存器的偏移地址

     __le16 wLength;  //数据传输阶段传输多少个字节

} __attribute__ ((packed));

USB协议中规定,所有的USB设备都会响应主机的一些请求,这些请求来自USB主机控制器,主机控制器通过设备的默认控制管道发出这些请求。默认的管道为0号端口对应的那个管道。

同样这个input设备首先由用户层调用open函数,所以先看看input中定义的open

static int usb_kbd_open(struct input_dev *dev)

{

     struct usb_kbd *kbd = input_get_drvdata(dev);

     kbd->irq->dev = kbd->usbdev;

     if (usb_submit_urb(kbd->irq, GFP_KERNEL))  //提交中断urb

            return -EIO;

     return 0;

}

因为这个驱动里面有一个中断urb一个控制urb,我们先看中断urb的处理流程。中断urb在input的open中被提交后,当USB核心处理完毕,会通知这个USB设备驱动,然后执行回调函数,也就是中断处理函数usb_kbd_irq

static void usb_kbd_irq(struct urb *urb)

{

     struct usb_kbd *kbd = urb->context;

     int i;

     switch (urb->status) {

     case 0:                  //成功

            break;

     case -ECONNRESET:    //未连接

     case -ENOENT:

     case -ESHUTDOWN:

            return;

     default:          

            goto resubmit;  //出错就再次提交中断urb

     }

     for (i = 0; i < 8; i++)  //向input子系统报告

            input_report_key(kbd->dev, usb_kbd_keycode[i + 224], (kbd->new[0] >> i) & 1);

     for (i = 2; i < 8; i++) {

            if (kbd->old[i] > 3 && memscan(kbd->new + 2, kbd->old[i], 6) == kbd->new + 8) {

                   if (usb_kbd_keycode[kbd->old[i]])

                          input_report_key(kbd->dev, usb_kbd_keycode[kbd->old[i]], 0);

                   else

                          dev_info(&urb->dev->dev,

                                        "Unknown key (scancode %#x) released.\n", kbd->old[i]);

            }

            if (kbd->new[i] > 3 && memscan(kbd->old + 2, kbd->new[i], 6) == kbd->old + 8) {

                   if (usb_kbd_keycode[kbd->new[i]])

                          input_report_key(kbd->dev, usb_kbd_keycode[kbd->new[i]], 1);

                   else

                          dev_info(&urb->dev->dev,

                                        "Unknown key (scancode %#x) released.\n", kbd->new[i]);

            }

     }

     input_sync(kbd->dev); 

     memcpy(kbd->old, kbd->new, 8); 

resubmit:

     i = usb_submit_urb (urb, GFP_ATOMIC);  //再次提交中断urb

     if (i)

            err_hid ("can't resubmit intr, %s-%s/input0, status %d",

                          kbd->usbdev->bus->bus_name,

                          kbd->usbdev->devpath, i);

}

这个就是中断urb的处理流程,跟前面讲的的USB鼠标中断处理流程类似。好了,我们再来看看剩下的控制urb处理流程吧。

我们有个疑问,我们知道在probe中,我们填充了中断urb和控制urb,但是在input的open中,我们只提交了中断urb,那么控制urb什么时候提交呢?

我们知道对于input子系统,如果有事件被响应,我们会调用事件处理层的event函数,而该函数最终调用的是input下的event。所以,对于input设备,我们在USB键盘驱动中只设置了支持LED选项,也就是ledbit项,这是怎么回事呢?刚才我们分析的那个中断urb其实跟这个input基本没啥关系,中断urb并不是像讲键盘input实现的那样属于input下的中断。我们在USB键盘驱动中的input子系统中只设计了LED选项,那么当input子系统有按键选项的时候必然会使得内核调用调用事件处理层的event函数,最终调用input下的event。好了,那我们来看看input下的event干了些什么。

static int usb_kbd_event(struct input_dev *dev, unsigned int type,

                    unsigned int code, int value)

{

     struct usb_kbd *kbd = input_get_drvdata(dev);

     if (type != EV_LED)    //不是LED事件就返回

            return -1;

    //将当前的LED值保存在kbd->newleds中

       kbd->newleds = (!!test_bit(LED_KANA,    dev->led) << 3) | (!!test_bit(LED_COMPOSE, dev->led) << 3) | (!!test_bit(LED_SCROLLL, dev->led) << 2) | (!!test_bit(LED_CAPSL,   dev->led) << 1) |(!!test_bit(LED_NUML,    dev->led));

     if (kbd->led->status == -EINPROGRESS)

            return 0;

     if (*(kbd->leds) == kbd->newleds)

            return 0;

     *(kbd->leds) = kbd->newleds;

     kbd->led->dev = kbd->usbdev;

     if (usb_submit_urb(kbd->led, GFP_ATOMIC))  //提交控制urb

            err_hid("usb_submit_urb(leds) failed");

     return 0;

}

当在input的event里提交了控制urb后,经过URB处理流程,最后返回给USB设备驱动的回调函数,也就是在probe中定义的usb_kbd_led

static void usb_kbd_led(struct urb *urb)

{

     struct usb_kbd *kbd = urb->context;

     if (urb->status)              //提交失败显示

            dev_warn(&urb->dev->dev, "led urb status %d received\n",

                    urb->status);

     //比较kbd->leds和kbd->newleds,如果发生变化,则更新kbd->leds

     if (*(kbd->leds) == kbd->newleds)

            return;                

     *(kbd->leds) = kbd->newleds;

     kbd->led->dev = kbd->usbdev;

     if (usb_submit_urb(kbd->led, GFP_ATOMIC))  //再次提交控制urb

            err_hid("usb_submit_urb(leds) failed");

}

总结下,我们的控制urb走的是先由input的event提交,触发后由控制urb的回调函数再次提交。好了,通过USB鼠标,我们已经知道了控制urb和中断urb的设计和处理流程
 

标签:usb,urb,总线,dev,kbd,linux,input,mouse
来源: https://blog.csdn.net/qq_16173531/article/details/90264919