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