在学习了这么些天的驱动之后,个人觉得驱动就是个架构的问题,只要把架构弄清楚了
然后往里面添砖加瓦就可以了,所以似乎看起来不是太困难,但也许是是我经验不足吧,这只能算是个人浅见了
这两天在学习USB驱动开发,奇怪的是老师居然不讲USB的代码,让人不理解,后来在网上找资料才发现原来内核已经给我们准备了一个usb_skel的代码向我们介绍几本的USB驱动的架构,于是自己分析了一下代码,画了一个我认为的代码架构(比较难看),写了一些注释
废话不多说啦,直接上图上代码,请高手们批评指正!
/*
* 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");