歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Linux驅動開發:USB驅動之usb_skel分析

在學習了這麼些天的驅動之後,個人覺得驅動就是個架構的問題,只要把架構弄清楚了

然後往裡面添磚加瓦就可以了,所以似乎看起來不是太困難,但也許是是我經驗不足吧,這只能算是個人淺見了

這兩天在學習USB驅動開發,奇怪的是老師居然不講USB的代碼,讓人不理解,後來在網上找資料才發現原來內核已經給我們准備了一個usb_skel的代碼向我們介紹幾本的USB驅動的架構,於是自己分析了一下代碼,畫了一個我認為的代碼架構(比較難看),寫了一些注釋

相關閱讀:

Linux驅動開發:網絡設備之虛擬網卡 http://www.linuxidc.com/Linux/2012-03/56415.htm

Linux驅動開發:Nand Flash時序圖分析 http://www.linuxidc.com/Linux/2012-03/56414.htm

Linux驅動開發:網絡設備之DM9000驅動架構分析 http://www.linuxidc.com/Linux/2012-03/56416.htm

廢話不多說啦,直接上圖上代碼,請高手們批評指正!

/*

 * USB Skeleton driver - 2.2

 *

 * Copyright (C) 2001-2004 Greg Kroah-Hartman ([email protected])

 *

 * 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, version 2.

 *

 * This driver is based on the 2.6.3 version of drivers/usb/usb-skeleton.c

 * but has been rewritten to be easier to read and use.

 *

 */

#include <linux/kernel.h>

#include <linux/errno.h>

#include <linux/init.h>

#include <linux/slab.h>

#include <linux/module.h>

#include <linux/kref.h>

#include <asm/uaccess.h>

#include <linux/usb.h>

#include <linux/mutex.h>

/* Define these values to match your devices */

#define USB_SKEL_VENDOR_ID 0xfff0          //廠商ID

#define USB_SKEL_PRODUCT_ID 0xfff0      //產品ID

/* table of devices that work with this driver */

//驅動支持的USB設備列表

static struct usb_device_id skel_table [] = {

        { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },

        { }, /* Terminating entry */

};

MODULE_DEVICE_TABLE(usb, skel_table);

 

/* to prevent a race between open and disconnect */

static DEFINE_MUTEX(skel_open_lock);

/* Get a minor range for your devices from the usb maintainer */

#define USB_SKEL_MINOR_BASE 192      //USB主設備號

/* our private defines. if this grows any larger, use your own .h file */

#define MAX_TRANSFER (PAGE_SIZE - 512)

/* MAX_TRANSFER is chosen so that the VM is not stressed by allocations > PAGE_SIZE and the number of packets in a page is an integer 512 is the largest possible packet on EHCI */

#define WRITES_IN_FLIGHT 8

/* arbitrarily chosen */

//8、usb_skel結構體可以被看作一個私有數據結構體,應該根據具體的設備量身定制

struct usb_skel {

        struct usb_device *udev;                    //該設備的usb_device指針

        struct usb_interface *interface;         //該設備的usb_interface指針

        struct semaphore limit_sem;            //限制進程寫的數據量

        unsigned char  *bulk_in_buffer;       //接收數據的緩沖區

        size_t bulk_in_size;                            //接收緩沖區大小

        __u8 bulk_in_endpointAddr;            //批量IN端點的地址

        __u8 bulk_out_endpointAddr;         //批量OUT端點的地址

        struct kref kref;                                    //sturct kref作為內核中最基本的引用計數而存在

        struct mutex io_mutex;                     //同步的IO互斥鎖,保證

};

//5、聲明一個USB骨架驅動結構體對象

static struct usb_driver skel_driver;

 

static void skel_delete(struct kref *kref)

{

        struct usb_skel *dev = to_skel_dev(kref);

        usb_put_dev(dev->udev);

        kfree(dev->bulk_in_buffer);

        kfree(dev);

}

 

static int skel_open(struct inode *inode, struct file *file)

{

        struct usb_skel *dev;

        struct usb_interface *interface;

        int subminor;

        int retval = 0;

        subminor = iminor(inode);   //獲取次設備號

        mutex_lock(&skel_open_lock);   //上鎖

        interface = usb_find_interface(&skel_driver, subminor);   //獲得接口數據

        if (!interface) {

                mutex_unlock(&skel_open_lock);  //解鎖

                err ("%s - error, can't find device for minor %d",  __FUNCTION__, subminor);

                retval = -ENODEV;

                goto exit;

        }

        dev = usb_get_intfdata(interface);

        if (!dev) {

                mutex_unlock(&skel_open_lock);

                retval = -ENODEV;

                goto exit;

        }

        /* increment our usage count for the device */

        kref_get(&dev->kref);

        /* now we can drop the lock */

        mutex_unlock(&skel_open_lock);

        /* prevent the device from being autosuspended */

        retval = usb_autopm_get_interface(interface);

        if (retval) {

                kref_put(&dev->kref, skel_delete);

                goto exit;

        }

        /* save our object in the file's private structure */

        file->private_data = dev;

        exit:

        return retval;

}

 

static int skel_release(struct inode *inode, struct file *file)

{

        struct usb_skel *dev;

        dev = (struct usb_skel *)file->private_data;

        if (dev == NULL)

        return -ENODEV;

        /* allow the device to be autosuspended */

        mutex_lock(&dev->io_mutex);

        if (dev->interface)

        usb_autopm_put_interface(dev->interface);

        mutex_unlock(&dev->io_mutex);

        /* decrement the count on our device */

        kref_put(&dev->kref, skel_delete);

        return 0;

}

 

static ssize_t skel_read(struct file *file, char *buffer, size_t count, loff_t *ppos)

{

        struct usb_skel *dev;

        int retval;

        int bytes_read;

        dev = (struct usb_skel *)file->private_data;

        mutex_lock(&dev->io_mutex);

        if (!dev->interface) { /* disconnect() was called */

        retval = -ENODEV;

        goto exit;

}

/* 進行阻塞的批量讀以從設備獲取數據 */

retval = usb_bulk_msg(dev->udev, usb_rcvbulkpipe(dev->udev, dev->bulk_in_endpointAddr),  dev->bulk_in_buffer, min(dev->bulk_in_size, count), &bytes_read, 10000);

/* 如果讀成功,復制到用戶空間 */

if (!retval) {

        if (copy_to_user(buffer, dev->bulk_in_buffer, bytes_read))

        retval = -EFAULT;

        else

        retval = bytes_read;

}

exit:

mutex_unlock(&dev->io_mutex);

return retval;

}

 

/*當urb被成功傳輸到USB設備之後,urb回調函數將被USB核心調用,在我們的例子中,我們初始化urb,使它指向skel_write_bulk_callback函數*/

static void skel_write_bulk_callback(struct urb *urb)

{

        struct usb_skel *dev;

        dev = (struct usb_skel *)urb->context;

        /* sync/async unlink faults aren't errors */

        if (urb->status && !(urb->status == -ENOENT || urb->status == -ECONNRESET || urb->status == -ESHUTDOWN)) {

                err("%s - nonzero write bulk status received: %d",

                 __FUNCTION__, urb->status);

        }

        / * free up our allocated buffer */

        usb_buffer_free(urb->dev, urb->transfer_buffer_length,

        urb->transfer_buffer, urb->transfer_dma);

        up(&dev->limit_sem);

}

 

static ssize_t skel_write(struct file *file, const char *user_buffer, size_t count, loff_t *ppos)

{

        struct usb_skel *dev;

        int retval = 0;

        struct urb *urb = NULL;

        char *buf = NULL;

        size_t writesize = min(count, (size_t)MAX_TRANSFER);

        dev = (struct usb_skel *)file->private_data;

        /* verify that we actually have some data to write */

        if (count == 0)

        goto exit;

        /* limit the number of URBs in flight to stop a user from using up all RAM */

        if (down_interruptible(&dev->limit_sem)) {

               retval = -ERESTARTSYS;

                goto exit;

        }

 

         /* 創建一個urb,並且給它分配一個緩存*/
        urb = usb_alloc_urb(0, GFP_KERNEL);

        if (!urb) {

                retval = -ENOMEM;

                goto error;

        }

 

        /*當urb被成功分配後,還要創建一個DMA緩沖區來以高效的方式發送數據到設備,傳遞給驅動程序的數據要復制到這塊緩沖中去*/

        buf = usb_buffer_alloc(dev->udev, writesize, GFP_KERNEL, &urb->transfer_dma);

        if (!buf) {

                retval = -ENOMEM;

                goto error;

        }

 

        if (copy_from_user(buf, user_buffer, writesize)) {

                retval = -EFAULT;

                goto error;

        }

 

        /* this lock makes sure we don't submit URBs to gone devices */

        mutex_lock(&dev->io_mutex);

        if (!dev->interface) {

                 /* disconnect() was called */

                mutex_unlock(&dev->io_mutex);

                retval = -ENODEV;

                goto error;

        }

 

        /*當數據從用戶空間正確復制到局部緩沖區後,urb必須在可以被提交給USB核心之前被正確初始化*/

        usb_fill_bulk_urb(urb, dev->udev,  usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),  buf, writesize, skel_write_bulk_callback, dev);

        urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;

        /* 把數據從批量OUT端口發出 */

        retval = usb_submit_urb(urb, GFP_KERNEL);

        mutex_unlock(&dev->io_mutex);

        if (retval) {

                err("%s - failed submitting write urb, error %d", __FUNCTION__, retval);

                goto error;

        }

        /* release our reference to this urb, the USB core will eventually free it entirely */

        usb_free_urb(urb);

        return writesize;

        error:

        if (urb) {

                usb_buffer_free(dev->udev, writesize, buf, urb->transfer_dma);

                usb_free_urb(urb);

        }

        up(&dev->limit_sem);

        exit:

        return retval;

}

 

//字符設備的file_operations結構體,這個結構體中的成員實現

static const struct file_operations skel_fops = {

        .owner = THIS_MODULE,

        .read = skel_read,

        .write = skel_write,

        .open = skel_open,

        .release = skel_release,

};

/*

 * usb class driver info in order to get a minor number from the usb core,

 * and to have the device registered with the driver core

 */

static struct usb_class_driver skel_class = {

        .name = "skel%d",

        .fops  = &skel_fops,

        .minor_base  = USB_SKEL_MINOR_BASE,

};

//7、探測函數skel_probe

探測和斷開:當一個設備被安裝而USB核心認為該驅動程序應該處理時,探測函數被調用,探測函數檢查傳遞給它的設備信息,確定驅動程序是否真的適合該設備。當驅動程序因為某種原因不應該控制設備時,斷開函數被調用,它可以做一些清理工作。探測回調函數中,USB驅動程序初始化任何可能用於控制USB設備的局部結構體,它還把所需的任何設備相關信息保存到一個局部結構體中

static int skel_probe(struct usb_interface *interface, const struct usb_device_id *id)

{

        struct usb_skel *dev;     //usb_skel設備

        struct usb_host_interface *iface_desc;  

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

        size_t buffer_size;

        int i;

        int retval = -ENOMEM;

        /* allocate memory for our device state and initialize it */

        dev = kzalloc(sizeof(*dev), GFP_KERNEL);  //分配設備狀態的內存並初始化

        if (!dev) {

                err("Out of memory");

                goto error;

        }

        kref_init(&dev->kref);   //初始化引用計數,設置為1

        sema_init(&dev->limit_sem, WRITES_IN_FLIGHT);   //

        mutex_init(&dev->io_mutex);

        dev->udev = usb_get_dev(interface_to_usbdev(interface));

        dev->interface = interface;

      /* 設置端點信息 */
     /* 只使用第一個批量IN和批量OUT端點 */

        iface_desc = interface->cur_altsetting;

        /*在探測函數裡,這個循環首先訪問該接口中存在的每一個端點,給該端點一個局部指針以便以後訪問*/

        for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {

                endpoint = &iface_desc->endpoint[i].desc;

                /*如果所有這些探測都通過了,驅動程序就知道它已經發現了正確的端點類型,可以把該端點的相關信息保存到一個局部結構體中以便稍後用它來和端點進行通信*/

                if (!dev->bulk_in_endpointAddr && usb_endpoint_is_bulk_in(endpoint)) {

                        /* 找到一個批量IN類型的端點 */

                        buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);

                        dev->bulk_in_size = buffer_size;

                        dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;

                        dev->bulk_in_buffer = kmalloc(buffer_size, GFP_KERNEL);

                        if (!dev->bulk_in_buffer) {

                                err("Could not allocate bulk_in_buffer");

                                goto error;

                        }

                }

                if (!dev->bulk_out_endpointAddr && usb_endpoint_is_bulk_out(endpoint)) {

                       /* we found a bulk out endpoint */

                        dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;

                }

        }

        if (!(dev->bulk_in_endpointAddr && dev->bulk_out_endpointAddr)) {

                err("Could not find both bulk-in and bulk-out endpoints");

                goto error;

        }

        /*因為USB驅動程序要在設備的生命周期的稍後時間獲取和接口相關聯的局部數據結構體,所以調用了usb_set_intfdata函數,把它保存到struct usb_interface結構體中以便後面的訪問*/

         /* 把數據指針保存到這個接口設備中 */

        usb_set_intfdata(interface, dev);

        /*我們以後調用usb_set_intfdata函數來獲取數據。當這一切都完成後,USB驅動程序必須在探測函數中調用usb_register_dev函數來把該設備注冊到USB核心裡*/

        /* 注冊設備到USB核心 */

        retval = usb_register_dev(interface, &skel_class);

        if (retval) {

                 /* 有些情況下是不允許注冊驅動程序的 */
                err("Not able to get a minor for this device.");

                usb_set_intfdata(interface, NULL);

                goto error;

        }

        /* let the user know what node this device is now attached to */

        info("USB Skeleton device now attached to USBSkel-%d", interface->minor);

        return 0;

        error:

        if (dev)

        /* this frees allocated memory */

        kref_put(&dev->kref, skel_delete);

        return retval;

}

 

//9、骨架驅動斷開函數

static void skel_disconnect(struct usb_interface *interface)

{

        struct usb_skel *dev;

        int minor = interface->minor;

        /* prevent skel_open() from racing skel_disconnect() */

        mutex_lock(&skel_open_lock);

        dev = usb_get_intfdata(interface);

        usb_set_intfdata(interface, NULL);

        /* give back our minor */

        usb_deregister_dev(interface, &skel_class);

        mutex_unlock(&skel_open_lock);

        /* prevent more I/O from starting */

        mutex_lock(&dev->io_mutex);

        dev->interface = NULL;

        mutex_unlock(&dev->io_mutex);

        /* decrement our usage count */

        kref_put(&dev->kref, skel_delete);

        info("USB Skeleton #%d now disconnected", minor);

}

 

//6、對USB骨架驅動結構體對象進行初始化

static struct usb_driver skel_driver = {

        .owner = THIS_MODULE,          //指向該驅動程序的模塊所有者的批針。USB核心使用它來正確地對該USB驅動程序進行引用計數,使它不會在不合適的時刻被卸載掉,這個變量應該被設置為THIS_MODULE宏。

        .name = "skeleton",                 //指向驅動程序名字的指針,在內核的所有USB驅動程序中它必須是唯一的,通常被設置為和驅動程序模塊名相同的名字。

        .probe = skel_probe,             //這個是指向USB驅動程序中的探測函數的指針。當USB核心認為它有一個接口(usb_interface)可以由該驅動程序處理時,這個函數被調用。

        .disconnect = skel_disconnect,          //指向USB驅動程序中的斷開函數的指針,當一個USB接口(usb_interface)被從系統中移除或者驅動程序正在從USB核心中卸載時,USB核心將調用這個函數。

        .id_table = skel_table,          //指向ID設備表的指針,這個表包含了一列該驅動程序可以支持的USB設備,如果沒有設置這個變量,USB驅動程序中的探測回調函數就不會被調用。
};

 

//1、入口函數

static int __init usb_skel_init(void)

{

        int result;

       /* 驅動程序注冊到USB子系統中*/
        result = usb_register(&skel_driver);

        if (result)

                err("usb_register failed. Error number %d", result);

        return result;

}

 

//2、出口函數

static void __exit usb_skel_exit(void)

{

        /* 從子系統注銷驅動程序 */
        usb_deregister(&skel_driver);

}

 

//3、注冊到內核

module_init(usb_skel_init);

module_exit(usb_skel_exit);

MODULE_LICENSE("GPL");

Copyright © Linux教程網 All Rights Reserved