Linux下 USB設備驅動分析(原創)

以前作過STM32的usb HID複合設備,閒來看看linux下USB設備驅動是怎麼一回事,html

參考資料基於韋東山JZ2440開發板,如下,有錯誤歡迎指出。linux

一、準備知識redis

1.1USB相關概念:app

(1)usb是主從結構,usb的傳輸都是主機發起;框架

(2)usb右四種傳輸類型:控制、批量、中斷、實時傳輸。ide

(3)usb數據是經過端點進行通信的,0端點既能輸入也能輸出,端點都是有傳輸方向的,函數

(4)USB驅動程序框架post

app:ui

-----------------------------------------------this

內核:USB設備驅動程序---知道數據含義,好比 用戶自定義HID數據能夠在這裏解析;

---------------------------------------------------------------------------------------------------------------

   USB總線驅動程序--識別,找到匹配的設備驅動,提供讀寫函數;

-----------------------------------------------

底層硬件相關:USB主機控制器,具體的USB類--HID、AUDIO、DFU、CDC、MSC等

 

1.2

二、USB總線驅動概念:

USB 設備驅動程序就是用來支持 「硬件 -- USB 設備」的。可是爲了訪問底層具體的「USB 設
備」,就要用到了「USB 總線驅動程序」提供的讀寫函數,將命令或數據發給底層「USB 主機控制
器」,由「USB 主機控制器」產生信號發送給「USB 設備」。

2.1USB總線驅動程序的做用

(1)識別USB設備;

當你插上USB設備時, 硬件上拉電阻觸發,進入中斷函數,經過端點0主機set 地址,獲取相關的描述符,枚舉。

這個過程有點複雜,能夠看參考USB枚舉連接。

(2)查找並安裝對應的設備驅動程序;

(3)提供USB讀寫函數

 

2.2USB主機控制器

  1. UHC:intel 低速-全速
  2. OHCI:microsoft 低速、全速
  3. EHCI:高速
  • linux內核源碼(linux-2.6.22.6)
  • 參考的內核代碼:
/*
 * $Id: usbmouse.c,v 1.15 2001/12/27 10:37:41 vojtech Exp $
 *
 *  Copyright (c) 1999-2001 Vojtech Pavlik
 *
 *  USB HIDBP Mouse support
 */

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Should you need to contact me, the author, you can do so either by
 * e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
 * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
 */

#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/usb/input.h>
#include <linux/hid.h>

/*
 * Version Information
 */
#define DRIVER_VERSION "v1.6"
#define DRIVER_AUTHOR "Vojtech Pavlik <vojtech@ucw.cz>"
#define DRIVER_DESC "USB HID Boot Protocol mouse driver"
#define DRIVER_LICENSE "GPL"

MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE(DRIVER_LICENSE);

struct usb_mouse {
    char name[128];
    char phys[64];
    struct usb_device *usbdev;
    struct input_dev *dev;
    struct urb *irq;

    signed char *data;
    dma_addr_t data_dma;
};

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:            /* success */
        break;
    case -ECONNRESET:    /* unlink */
    case -ENOENT:
    case -ESHUTDOWN:
        return;
    /* -EPIPE:  should clear the halt */
    default:        /* error */
        goto resubmit;
    }

    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);
    input_report_key(dev, BTN_EXTRA,  data[0] & 0x10);

    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);
    if (status)
        err ("can't resubmit intr, %s-%s/input0, status %d",
                mouse->usbdev->bus->bus_name,
                mouse->usbdev->devpath, status);
}

static int usb_mouse_open(struct input_dev *dev)
{
    struct usb_mouse *mouse = input_get_drvdata(dev);

    mouse->irq->dev = mouse->usbdev;
    if (usb_submit_urb(mouse->irq, GFP_KERNEL))
        return -EIO;

    return 0;
}

static void usb_mouse_close(struct input_dev *dev)
{
    struct usb_mouse *mouse = input_get_drvdata(dev);

    usb_kill_urb(mouse->irq);
}

static int usb_mouse_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
    struct usb_device *dev = interface_to_usbdev(intf);
    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)
        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));

    mouse = kzalloc(sizeof(struct usb_mouse), GFP_KERNEL);
    input_dev = input_allocate_device();
    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);
    if (!mouse->irq)
        goto fail2;

    mouse->usbdev = dev;
    mouse->dev = input_dev;

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

    if (dev->product) {
        if (dev->manufacturer)
            strlcat(mouse->name, " ", sizeof(mouse->name));
        strlcat(mouse->name, dev->product, sizeof(mouse->name));
    }

    if (!strlen(mouse->name))
        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_dev->phys = mouse->phys;
    usb_to_input_id(dev, &input_dev->id);
    input_dev->dev.parent = &intf->dev;

    input_dev->evbit[0] = BIT(EV_KEY) | BIT(EV_REL);
    input_dev->keybit[LONG(BTN_MOUSE)] = BIT(BTN_LEFT) | BIT(BTN_RIGHT) | BIT(BTN_MIDDLE);
    input_dev->relbit[0] = BIT(REL_X) | BIT(REL_Y);
    input_dev->keybit[LONG(BTN_MOUSE)] |= BIT(BTN_SIDE) | BIT(BTN_EXTRA);
    input_dev->relbit[0] |= BIT(REL_WHEEL);

    input_set_drvdata(input_dev, mouse);

    input_dev->open = usb_mouse_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);
    mouse->irq->transfer_dma = mouse->data_dma;
    mouse->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;

    error = input_register_device(mouse->dev);
    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;
}

static void usb_mouse_disconnect(struct usb_interface *intf)
{
    struct usb_mouse *mouse = usb_get_intfdata (intf);

    usb_set_intfdata(intf, NULL);
    if (mouse) {
        usb_kill_urb(mouse->irq);
        input_unregister_device(mouse->dev);
        usb_free_urb(mouse->irq);
        usb_buffer_free(interface_to_usbdev(intf), 8, mouse->data, mouse->data_dma);
        kfree(mouse);
    }
}

static struct usb_device_id usb_mouse_id_table [] = {
    { USB_INTERFACE_INFO(USB_INTERFACE_CLASS_HID, USB_INTERFACE_SUBCLASS_BOOT,
        USB_INTERFACE_PROTOCOL_MOUSE) },
    { }    /* Terminating entry */
};

MODULE_DEVICE_TABLE (usb, usb_mouse_id_table);

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

static int __init usb_mouse_init(void)
{
    int retval = usb_register(&usb_mouse_driver);
    if (retval == 0)
        info(DRIVER_VERSION ":" DRIVER_DESC);
    return retval;
}

static void __exit usb_mouse_exit(void)
{
    usb_deregister(&usb_mouse_driver);
}

module_init(usb_mouse_init);
module_exit(usb_mouse_exit);
View Code

 

2.3其它概念-HUB概念-USB描述符概念

 

三、USB設備驅動代碼框架分析

以上屬於平臺設備「總線-設備-驅動」模型;

能夠百度下--驅動程序分層分離概念

以上是總線設備驅動模型;

當接上一個 USB 設備時,就會產生一箇中斷(hub_irq()) ,在中斷裏會分配一個編
號地址(choose_address(udev) )。
再而後把這個地址告訴 USB 設備(hub_set_address() )。
接着發出各類命令獲取 USB 設備的「設備描述符」 (usb_get_device_descriptor
() )。
再而後註冊一個 device(device_add() )。這個被註冊的 device 會被放到 USB 總線
(usb_bus_type)的「設備鏈表」。而且會從總線(usb_bus_type)的「驅動鏈表」中取
出"usb_driver" - USB 設備驅動結構, 把 usb_interface 和 usb_driver 的 id_table 比
較,若能匹配就去調用「usb_driver」結構中的「.probe」函數。 --接着能夠在probe函數實現本身想要的功能

四、實現一個簡單的USB鼠標驅動代碼分析

 4.1 USB 總線驅動程序,在接入 USB 設備時,會幫咱們構造一個新的 usb_dev 註冊到「usb_bus_type」裏去。這部分是內核作好的。

 4.2 咱們要作的是,構造一個 usb_driver 結構體,註冊到「usb_bus_type」中去。在「usb_driver」結構體中有「id_table」表示他能支持哪些設備,

 4.3  .match。當 USB 設備能匹配 id_table 中某一個設備時,就會調用咱們構造的「usb_driver」結構體中的「.probe」 (自已肯定在 probe 中作的事情)等函數,如當 拔掉

USB 設備時,就會調用其中的「.disconnect」函數

五、如今要實現的是:

USB 鼠標用做按鍵: (至關於輸入子系統)。
左鍵 -- L
右鍵 -- S
中鍵 -- Enter

 代碼框架:

#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/usb/input.h>
#include <linux/hid.h>
//
static struct usb_device_id usbmouse_as_key_id_table [] = {
    { USB_INTERFACE_INFO(USB_INTERFACE_CLASS_HID, USB_INTERFACE_SUBCLASS_BOOT,
        USB_INTERFACE_PROTOCOL_MOUSE) },
    //{USB_DEVICE(0x1234,0x5678)},
    { }    /* Terminating entry */
};


static int usbmouse_as_key_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
    printk("found usbmouse!\n");
    return 0;
}

static void usbmouse_as_key_disconnect(struct usb_interface *intf)
{
    printk("disconnect usbmouse!\n");
}

/* 1.分配設置usb_driver */
static struct usb_driver usbmouse_as_key_driver = {
    .name        = "usbmouse_as_key_",
    .probe        = usbmouse_as_key_probe,
    .disconnect    = usbmouse_as_key_disconnect,
    .id_table    = usbmouse_as_key_id_table,
};


static int usbmouse_as_key_init(void)
{
    /* 2.註冊 */
    usb_register(&usbmouse_as_key_driver);
    return 0;
}

static void usbmouse_as_key_exit(void)
{
    usb_deregister(&usbmouse_as_key_driver);    
}

module_init(usbmouse_as_key_init);
module_exit(usbmouse_as_key_exit);

MODULE_LICENSE("GPL");
View Code

接着填充usb_driver 裏面的函數,
5.1 id_table:

#define USB_INTERFACE_INFO(cl,sc,pr) \
    .match_flags = USB_DEVICE_ID_MATCH_INT_INFO, .bInterfaceClass = (cl), \
    .bInterfaceSubClass = (sc), .bInterfaceProtocol = (pr)

".match_flags":表示要匹配「設備描述符」中的哪一項。
「USB_DEVICE_ID_MATCH_INT_INFO」: INT 是接口意思,
INT_INFO 就是指接口的信息。接
口的信息就在「接口描述符」裏。
「.bInterfaceClass」:只要「接口描述符」裏的「類」是(cl)。
「.bInterfaceSubClass」:子類是 (sc) 。
「.bInterfaceProtocol」:協議是 (pr) 。

因此,鼠標mouse接口描述符裏類是--HID類,子類--boot,協議--mouse 這個id_table能支持

5.1 usbmouse_as_key_probe函數:

static int usbmouse_as_key_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
    struct usb_device *dev = interface_to_usbdev(intf);
    struct usb_host_interface *interface;
    struct usb_endpoint_descriptor *endpoint;
    int pipe;
    
    interface = intf->cur_altsetting;
    endpoint = &interface->endpoint[0].desc;

    /* a. 分配一個input_dev */
    uk_dev = input_allocate_device();
    
    /* b. 設置 */
    /* b.1 能產生哪類事件 */
    set_bit(EV_KEY, uk_dev->evbit);
    set_bit(EV_REP, uk_dev->evbit);
    
    /* b.2 能產生哪些事件 */
    set_bit(KEY_L, uk_dev->keybit);
    set_bit(KEY_S, uk_dev->keybit);
    set_bit(KEY_ENTER, uk_dev->keybit);
    
    /* c. 註冊 */
    input_register_device(uk_dev);
    
    /* d. 硬件相關操做 */
    /* 數據傳輸3要素: 源,目的,長度 */
    /* 源: USB設備的某個端點 */
    pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);

    /* 長度: */
    len = endpoint->wMaxPacketSize;

    /* 目的: */
    usb_buf = usb_buffer_alloc(dev, len, GFP_ATOMIC, &usb_buf_phys);

    /* 使用"3要素" */
    /* 分配usb request block */
    uk_urb = usb_alloc_urb(0, GFP_KERNEL);
    /* 使用"3要素設置urb" */
    usb_fill_int_urb(uk_urb, dev, pipe, usb_buf, len, usbmouse_as_key_irq, NULL, endpoint->bInterval);
    uk_urb->transfer_dma = usb_buf_phys;
    uk_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;

    /* 使用URB */
    usb_submit_urb(uk_urb, GFP_KERNEL);
    
    return 0;
}
相關文章
相關標籤/搜索