Linux USB鼠标驱动注解及测试

参考2.6.14版本中的driver/usb/input/usbmouse.c。鼠标驱动可分为几个部分:驱动加载部分、probe部分、open部分、urb回调函数处理部分。
下文阴影部分为注解。

一、驱动加载部分

static int __init usb_mouse_init(void)
         {
                  int retval = usb_register(&usb_mouse_driver);//注册鼠标驱动
                  if (retval == 0)
                  info(DRIVER_VERSION ":" DRIVER_DESC);
                  return retval;
          }

其中usb_mouse_driver的定义为:

static struct usb_driver usb_mouse_driver = {
        .owner                  = THIS_MODULE,
         .name                  = "usbmouse",
         .probe                  = usb_mouse_probe,
         .disconnect         = usb_mouse_disconnect,
          .id_table              = usb_mouse_id_table,
         };

如果注册成功的话,将会调用usb_mouse_probe。那么什么时候才算注册成功呢?

和其它驱动注册过程一样,只有在其对应的“总线”上发现匹配的“设备”才会调用probe。总线匹配的方法和具体总线相关,如:platform_bus_type中是判断驱动名称和平台设备名称是否相同;那如何确认usb总线的匹配方法呢?

Usb设备是注册在usb_bus_type总线下的。查看usb_bus_type的匹配方法。

struct bus_type usb_bus_type = {
         .name =                "usb",
         .match =               usb_device_match,
         .hotplug =            usb_hotplug,
         .suspend =         usb_generic_suspend,
         .resume =           usb_generic_resume,
          };

其中usb_device_match定义了匹配方法

static int usb_device_match (struct device *dev, struct device_driver *drv)
          {
                    struct usb_interface *intf;
                    struct usb_driver *usb_drv;
                    const struct usb_device_id *id;
                    /* check for generic driver, which we don't match any device with */
                    if (drv == &usb_generic_driver)
                    return 0;
                    intf = to_usb_interface(dev);
                    usb_drv = to_usb_driver(drv);
                    id = usb_match_id (intf, usb_drv->id_table);
                    if (id)
                              return 1;
                    return 0;
          }