linxu_usb驱动之框架
USB骨架程序可以被看做一个最简单的USB设备驱动的实例。
首先看看USB骨架程序的usb_driver的定义
[cpp] view plain copy
static struct usb_driver skel_driver = {
.name = "skeleton",
.probe = skel_probe, //设备探测
.disconnect = skel_disconnect,
.suspend = skel_suspend,
.resume = skel_resume,
.pre_reset = skel_pre_reset,
.post_reset = skel_post_reset,
.id_table = skel_table, //设备支持项
.supports_autosuspend = 1,
};
[cpp] view plain copy
/* Define these values to match your devices */
#define USB_SKEL_VENDOR_ID 0xfff0
#define USB_SKEL_PRODUCT_ID 0xfff0
/* table of devices that work with this driver */
static const struct usb_device_id skel_table[] = {
{ USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, skel_table);
由上面代码可见,通过USB_DEVICE宏定义了设备支持项。
对上面usb_driver的注册和注销发送在USB骨架程序的模块加载和卸载函数中。
[cpp] view plain copy
static int __init usb_skel_init(void)
{
int result;
/* register this driver with the USB subsystem */
result = usb_register(&skel_driver); //将该驱动挂在USB总线上
if (result)
err("usb_register failed. Error number %d", result);
return result;
}
一个设备被安装或者有设备插入后,当USB总线上经过match匹配成功,就会调用设备驱动程序中的probe探测函数,向探测函数传递设备的信息,以便确定驱动程序是否支持该设备。
[cpp] view plain copy
static int skel_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_skel *dev; //特定设备结构体
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); ////初始化内核引用计数
sema_init(&dev->limit_sem, WRITES_IN_FLIGHT); //初始化信号量
mutex_init(&dev->io_mutex); //初始化互斥锁
spin_lock_init(&dev->err_lock); //初始化自旋锁
init_usb_anchor(&dev->submitted);
init_completion(&dev->bulk_in_completion); //初始化完成量
dev->udev = usb_get_dev(interface_to_usbdev(interface)); //获取usb_device结构体
dev->interface = interface; //获取usb_ interface结构体
/* set up the endpoint information */
/* use only the first bulk-in and bulk-out endpoints */
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)) { //如果端点为批量输入端点
/* we found a bulk in endpoint */
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;
}
dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL); //分配URB空间
if (!dev->bulk_in_urb) {
err("Could not allocate bulk_in_urb");
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;
}
/* save our data pointer in this interface device */
usb_set_intfdata(interface, dev); //将特定设备结构体设置为接口的私有数据
/* we can register the device now, as it is ready */
retval = usb_register_dev(interface, &skel_class); //注册USB设备
if (retval) {
/* something prevented us from registering this driver */
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 */
dev_info(&interface->dev,
"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;
}
通过上面分析,我们知道,usb_driver的probe函数中根据usb_interface的成员寻找第一个批量输入和输出的端点,将端点地址、缓冲区等信息存入USB骨架程序定义的usb_skel结构体中,并将usb_skel通过usb_set_intfdata传为USB接口的私有数据,最后注册USB设备。
我们来看看这个USB骨架程序定义的usb_skel结构体
[cpp] view plain copy
/* Structure to hold all of our device specific stuff */
struct usb_skel {
struct usb_device *udev; /* the usb device for this device */
struct usb_interface *interface; /* the interface for this device */
struct semaphore limit_sem; /* limiting the number of writes in progress */
struct usb_anchor submitted; /* in case we need to retract our submissions */
struct urb *bulk_in_urb; /* the urb to read data with */
unsigned char *bulk_in_buffer; /* the buffer to receive data */
size_t bulk_in_size; /* the size of the receive buffer */
size_t bulk_in_filled; /* number of bytes in the buffer */
size_t bulk_in_copied; /* already copied to user space */
__u8 bulk_in_endpointAddr; /* the address of the bulk in endpoint */
__u8 bulk_out_endpointAddr; /* the address of the bulk out endpoint */
int errors; /* the last request tanked */
int open_count; /* count the number of openers */
bool ongoing_read; /* a read is going on */
bool processed_urb; /* indicates we haven‘t processed the urb */
spinlock_t err_lock; /* lock for errors */
struct kref kref;
struct mutex io_mutex; /* synchronize I/O with disconnect */
struct completion bulk_in_completion; /* to wait for an ongoing read */
};
#define to_skel_dev(d) container_of(d, struct usb_skel, kref)
好了看完了probe,我们再看看disconnect函数
[cpp] view plain copy
static void skel_disconnect(struct usb_interface *interface)
{
struct usb_skel *dev;
int minor = interface->minor; //获得接口的次设备号
dev = usb_get_intfdata(interface); //获取接口的私有数据
usb_set_intfdata(interface, NULL); //设置接口的私有数据为空
/* give back our minor */
usb_deregister_dev(interface, &skel_class); //注销USB设备
/* prevent more I/O from starting */
mutex_lock(&dev->io_mutex);
dev->interface = NULL;
mutex_unlock(&dev->io_mutex);
usb_kill_anchored_urbs(&dev->submitted);
/* decrement our usage count */
kref_put(&dev->kref, skel_delete);
dev_info(&interface->dev, "USB Skeleton #%d now disconnected", minor);
}
我们在skel_probe中最后执行了usb_register_dev(interface, &skel_class)来注册了一个USB设备,我们看看skel_class的定义
[cpp] view plain copy
/*
* 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,
};
static const struct file_operations skel_fops = {
.owner = THIS_MODULE,
.read = skel_read,
.write = skel_write,
.open = skel_open,
.release = skel_release,
.flush = skel_flush,
.llseek = noop_llseek,
};
根据上面代码我们知道,其实我们在probe中注册USB设备的时候使用的skel_class是一个包含file_operations的结构体,而这个结构体正是字符设备文件操作结构体。
我们先来看看这个file_operations中open函数的实现
[cpp] view plain copy
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); //获得次设备号
//根据usb_driver和次设备号获取设备的接口
interface = usb_find_interface(&skel_driver, subminor);
if (!interface) {
err("%s - error, can‘t find device for minor %d",
__func__, subminor);
retval = -ENODEV;
goto exit;
}
dev = usb_get_intfdata(interface); //获取接口的私有数据usb_ske
if (!dev) {
retval = -ENODEV;
goto exit;
}
/* increment our usage count for the device */
kref_get(&dev->kref);
/* lock the device to allow correctly handling errors
* in resumption */
mutex_lock(&dev->io_mutex);
if (!dev->open_count++) {
retval = usb_autopm_get_interface(interface);
if (retval) {
dev->open_count--;
mutex_unlock(&dev->io_mutex);
kref_put(&dev->kref, skel_delete);
goto exit;
}
} /* else { //uncomment this block if you want exclusive open
retval = -EBUSY;
dev->open_count--;
mutex_unlock(&dev->io_mutex);
kref_put(&dev->kref, skel_delete);
goto exit;
} */
/* prevent the device from being autosuspended */
/* save our object in the file‘s private structure */
file->private_data = dev; //将usb_skel设置为文件的私有数据
mutex_unlock(&dev->io_mutex);
exit:
return retval;
}
这个open函数实现非常简单,它根据usb_driver和次设备号通过usb_find_interface获取USB接口,然后通过usb_get_intfdata获得接口的私有数据并赋值给文件。
好了,我们看看write函数,在write函数中,我们进行了urb的分配、初始化和提交的操作
[cpp] view plain copy
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 = 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 (!(file->f_flags & O_NONBLOCK)) { //如果文件采用非阻塞方式
if (down_interruptible(&dev->limit_sem)) { //获取限制读的次数的信号量
retval = -ERESTARTSYS;
goto exit;
}
} else {
if (down_trylock(&dev->limit_sem)) {
retval = -EAGAIN;
goto exit;
}
}
spin_lock_irq(&dev->err_lock); //关中断
retval = dev->errors;
if (retval < 0) {
/* any error is reported once */
dev->errors = 0;
/* to preserve notifications about reset */
retval = (retval == -EPIPE) ? retval : -EIO;
}
spin_unlock_irq(&dev->err_lock); //开中断
if (retval < 0)
goto error;
/* create a urb, and a buffer for it, and copy the data to the urb */
urb = usb_alloc_urb(0, GFP_KERNEL); //分配urb
if (!urb) {
retval = -ENOMEM;
goto error;
}
buf = usb_alloc_coherent(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;
}
/* initialize the urb properly */
usb_fill_bulk_urb(urb, dev->udev,
usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
buf, writesize, skel_write_bulk_callback, dev); //填充urb
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; //urb->transfer_dma有效
usb_anchor_urb(urb, &dev->submitted);
/* send the data out the bulk port */
retval = usb_submit_urb(urb, GFP_KERNEL); //提交urb
mutex_unlock(&dev->io_mutex);
if (retval) {
err("%s - failed submitting write urb, error %d", __func__,
retval);
goto error_unanchor;
}
/*
* release our reference to this urb, the USB core will eventually free
* it entirely
*/
usb_free_urb(urb);
return writesize;
error_unanchor:
usb_unanchor_urb(urb);
error:
if (urb) {
usb_free_coherent(dev->udev, writesize, buf, urb->transfer_dma);
usb_free_urb(urb);
}
up(&dev->limit_sem);
exit:
return retval;
}
首先说明一个问题,填充urb后,设置了transfer_flags标志,当transfer_flags中的URB_NO_TRANSFER_DMA_MAP被设置,USB核心使用transfer_dma指向的缓冲区而不是使用transfer_buffer 指向的缓冲区,这表明即将传输DMA缓冲区。当transfer_flags中的URB_NO_SETUP_DMA_MAP被设置,如果控制urb有 DMA缓冲区,USB核心将使用setup_dma指向的缓冲区而不是使用setup_packet指向的缓冲区。
另外,通过上面这个write函数我们知道,当写函数发起的urb结束后,其完成函数skel_write_bulk_callback会被调用,我们继续跟踪
[cpp] view plain copy
static void skel_write_bulk_callback(struct urb *urb)
{
struct usb_skel *dev;
dev = urb->context;
/* sync/async unlink faults aren‘t errors */
if (urb->status) {
if (!(urb->status == -ENOENT ||
urb->status == -ECONNRESET ||
urb->status == -ESHUTDOWN))
err("%s - nonzero write bulk status received: %d",
__func__, urb->status);
spin_lock(&dev->err_lock);
dev->errors = urb->status;
spin_unlock(&dev->err_lock);
}
/* free up our allocated buffer */
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
up(&dev->limit_sem);
}
很明显,skel_write_bulk_callback主要对urb->status进行判断,根据错误提示显示错误信息,然后释放urb空间。
接着,我们看看USB骨架程序的字符设备的read函数
[cpp] view plain copy
static ssize_t skel_read(struct file *file, char *buffer, size_t count,
loff_t *ppos)
{
struct usb_skel *dev;
int rv;
bool ongoing_io;
dev = file->private_data; //获得文件私有数据
/* if we cannot read at all, return EOF */
if (!dev->bulk_in_urb || !count) //正在写的时候禁止读操作
return 0;
/* no concurrent readers */
rv = mutex_lock_interruptible(&dev->io_mutex);
if (rv < 0)
return rv;
if (!dev->interface) { /* disconnect() was called */
rv = -ENODEV;
goto exit;
}
/* if IO is under way, we must not touch things */
retry:
spin_lock_irq(&dev->err_lock);
ongoing_io = dev->ongoing_read;
spin_unlock_irq(&dev->err_lock);
if (ongoing_io) { //USB core正在读取数据,数据没准备好
/* nonblocking IO shall not wait */
if (file->f_flags & O_NONBLOCK) {
rv = -EAGAIN;
goto exit;
}
/*
* IO may take forever
* hence wait in an interruptible state
*/
rv = wait_for_completion_interruptible(&dev->bulk_in_completion);
if (rv < 0)
goto exit;
/*
* by waiting we also semiprocessed the urb
* we must finish now
*/
dev->bulk_in_copied = 0; //拷贝到用户空间操作已成功
dev->processed_urb = 1; //目前已处理好urb
}
if (!dev->processed_urb) { //目前还未处理好urb
/*
* the URB hasn‘t been processed
* do it now
*/
wait_for_completion(&dev->bulk_in_completion); //等待完成
dev->bulk_in_copied = 0; //拷贝到用户空间操作已成功
dev->processed_urb = 1; //目前已处理好urb
}
/* errors must be reported */
rv = dev->errors;
if (rv < 0) {
/* any error is reported once */
dev->errors = 0;
/* to preserve notifications about reset */
rv = (rv == -EPIPE) ? rv : -EIO;
/* no data to deliver */
dev->bulk_in_filled = 0;
/* report it */
goto exit;
}
/*
* if the buffer is filled we may satisfy the read
* else we need to start IO
*/
if (dev->bulk_in_filled) { //缓冲区有内容
/* we had read data */
//可读数据大小为缓冲区内容减去已经拷贝到用户空间的数据大小
size_t available = dev->bulk_in_filled - dev->bulk_in_copied;
size_t chunk = min(available, count); //真正读取的数据大小
if (!available) {
/*
* all data has been used
* actual IO needs to be done
*/
rv = skel_do_read_io(dev, count);
if (rv < 0)
goto exit;
else
goto retry;
}
/*
* data is available
* chunk tells us how much shall be copied
*/
//拷贝缓冲区数据到用户空间
if (copy_to_user(buffer,
dev->bulk_in_buffer + dev->bulk_in_copied,
chunk))
rv = -EFAULT;
else
rv = chunk;
dev->bulk_in_copied += chunk; //目前拷贝完成的数据大小
/*
* if we are asked for more than we have,
* we start IO but don‘t wait
*/
if (available < count)
skel_do_read_io(dev, count - chunk);
} else {
/* no data in the buffer */
rv = skel_do_read_io(dev, count);
if (rv < 0)
goto exit;
else if (!(file->f_flags & O_NONBLOCK))
goto retry;
rv = -EAGAIN;
}
exit:
mutex_unlock(&dev->io_mutex);
return rv;
}
通过上面read函数,我们知道,在读取数据时候,如果发现缓冲区没有数据,或者缓冲区的数据小于用户需要读取的数据量时,则会调用IO操作,也就是skel_do_read_io函数。
[cpp] view plain copy
static int skel_do_read_io(struct usb_skel *dev, size_t count)
{
int rv;
/* prepare a read */
usb_fill_bulk_urb(dev->bulk_in_urb,dev->udev,usb_rcvbulkpipe(dev->udev,
dev->bulk_in_endpointAddr),dev->bulk_in_buffer,
min(dev->bulk_in_size, count),skel_read_bulk_callback,dev); //填充urb
/* tell everybody to leave the URB alone */
spin_lock_irq(&dev->err_lock);
dev->ongoing_read = 1; //标志正在读取数据中
spin_unlock_irq(&dev->err_lock);
rv = usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL); //提交urb
if (rv < 0) {
err("%s - failed submitting read urb, error %d",
__func__, rv);
dev->bulk_in_filled = 0;
rv = (rv == -ENOMEM) ? rv : -EIO;
spin_lock_irq(&dev->err_lock);
dev->ongoing_read = 0;
spin_unlock_irq(&dev->err_lock);
}
return rv;
}
好了,其实skel_do_read_io只是完成了urb的填充和提交,USB core读取到了数据后,会调用填充urb时设置的回调函数skel_read_bulk_callback。
[cpp] view plain copy
static void skel_read_bulk_callback(struct urb *urb)
{
struct usb_skel *dev;
dev = urb->context;
spin_lock(&dev->err_lock);
/* sync/async unlink faults aren‘t errors */
if (urb->status) {//根据返回状态判断是否出错
if (!(urb->status == -ENOENT ||
urb->status == -ECONNRESET ||
urb->status == -ESHUTDOWN))
err("%s - nonzero write bulk status received: %d",
__func__, urb->status);
dev->errors = urb->status;
} else {
dev->bulk_in_filled = urb->actual_length; //记录缓冲区的大小
}
dev->ongoing_read = 0; //已经读取数据完毕
spin_unlock(&dev->err_lock);
complete(&dev->bulk_in_completion); //唤醒skel_read函数
}
到目前为止,我们已经把USB驱动框架usb-skeleton.c分析完了,总结下,其实很简单,在模块加载里面注册 usb_driver,然后在probe函数里初始化一些参数,最重要的是注册了USB设备,这个USB设备相当于一个字符设备,提供 file_operations接口。然后设计open,close,read,write函数,这个open里基本没做什么事情,在write中,通过分配urb、填充urb和提交urb。注意读的urb的分配在probe里申请空间,写的urb的分配在write里申请空间。在这个驱动程序中,我们重点掌握usb_fill_bulk_urb的设计。
linxu_usb驱动之鼠标驱动
原文链接:http://www.linuxidc.com/Linux/2012-12/76197p7.htm
drivers/hid/usbhid/usbmouse.c
下面我们分析下USB鼠标驱动,鼠标输入HID类型,其数据传输采用中断URB,鼠标端点类型为IN。我们先看看这个驱动的模块加载部分。
[cpp] view plain copy
static int __init usb_mouse_init(void)
{
int retval = usb_register(&usb_mouse_driver);
if (retval == 0)
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
return retval;
}
模块加载部分仍然是调用usb_register注册USB驱动,我们跟踪看看被注册的usb_mouse_driver
[cpp] view plain copy
static struct usb_driver usb_mouse_driver = {
.name = "usbmouse", //驱动名
.probe = usb_mouse_probe,
.disconnect = usb_mouse_disconnect,
.id_table = usb_mouse_id_table, //支持项
};
关于设备支持项我们前面已经讨论过了
[cpp] view plain copy
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);
再细细看看USB_INTERFACE_INFO宏的定义
[cpp] view plain copy
/**
* USB_INTERFACE_INFO - macro used to describe a class of usb interfaces
* @cl: bInterfaceClass value
* @sc: bInterfaceSubClass value
* @pr: bInterfaceProtocol value
*
* This macro is used to create a struct usb_device_id that matches a
* specific class of interfaces.
*/
#define USB_INTERFACE_INFO(cl, sc, pr) \
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO, \
.bInterfaceClass = (cl), \
.bInterfaceSubClass = (sc), \
.bInterfaceProtocol = (pr)
根据宏,我们知道,我们设置的支持项包括接口类,接口子类,接口协议三个匹配项。
主要看看usb_driver中定义的probe函数
[cpp] view plain copy
static int usb_mouse_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);//由接口获取usb_dev
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) //鼠标端点只有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为4个)
mouse = kzalloc(sizeof(struct usb_mouse), GFP_KERNEL); //分配usb_mouse结构体
input_dev = input_allocate_device(); //分配input设备空间
if (!mouse || !input_dev)
goto fail1;
mouse->data = usb_alloc_coherent(dev, 8, GFP_ATOMIC, &mouse->data_dma); //分配缓冲区
if (!mouse->data)
goto fail1;
mouse->irq = usb_alloc_urb(0, GFP_KERNEL); //分配urb
if (!mouse->irq)
goto fail2;
mouse->usbdev = dev; //填充mouse的usb_device结构体
mouse->dev = input_dev; //填充mouse的input结构体
if (dev->manufacturer) //复制厂商ID
strlcpy(mouse->name, dev->manufacturer, sizeof(mouse->name));
if (dev->product) { //复制产品ID
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)); //获取usb_mouse的设备节点
input_dev->name = mouse->name; //将鼠标名赋给内嵌input结构体
input_dev->phys = mouse->phys; //将鼠标设备节点名赋给内嵌input结构体
usb_to_input_id(dev, &input_dev->id); //将usb_driver的支持项拷贝给input
input_dev->dev.parent = &intf->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL); //支持按键事件和相对坐标事件
input_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE); //表明按键值包括左键、中键和右键
input_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y); //表明相对坐标包括X坐标和Y坐标
input_dev->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_SIDE) |
BIT_MASK(BTN_EXTRA); //表明除了左键、右键和中键,还支持其他按键
input_dev->relbit[0] |= BIT_MASK(REL_WHEEL); //表明还支持中键滚轮的滚动值
input_set_drvdata(input_dev, mouse); //将mouse设为input的私有数据
input_dev->open = usb_mouse_open; //input设备的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); //填充urb
mouse->irq->transfer_dma = mouse->data_dma;
mouse->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; //使用transfer_dma
error = input_register_device(mouse->dev); //注册input设备
if (error)
goto fail3;
usb_set_intfdata(intf, mouse);
return 0;
fail3:
usb_free_urb(mouse->irq);
fail2:
usb_free_coherent(dev, 8, mouse->data, mouse->data_dma);
fail1:
input_free_device(input_dev);
kfree(mouse);
return error;
}
在探讨probe实现的功能时,我们先看看urb填充函数usb_fill_int_urb
[cpp] view plain copy
/**
* usb_fill_int_urb - macro to help initialize a interrupt urb
* @urb: pointer to the urb to initialize.
* @dev: pointer to the struct usb_device for this urb.
* @pipe: the endpoint pipe
* @transfer_buffer: pointer to the transfer buffer
* @buffer_length: length of the transfer buffer
* @complete_fn: pointer to the usb_complete_t function
* @context: what to set the urb context to.
* @interval: what to set the urb interval to, encoded like
* the endpoint descriptor‘s bInterval value.
*
* Initializes a interrupt urb with the proper information needed to submit
* it to a device.
*
* Note that High Speed and SuperSpeed interrupt endpoints use a logarithmic
* encoding of the endpoint interval, and express polling intervals in
* microframes (eight per millisecond) rather than in frames (one per
* millisecond).
*
* Wireless USB also uses the logarithmic encoding, but specifies it in units of
* 128us instead of 125us. For Wireless USB devices, the interval is passed
* through to the host controller, rather than being translated into microframe
* units.
*/
static inline void usb_fill_int_urb(struct urb *urb,
struct usb_device *dev,
unsigned int pipe,
void *transfer_buffer,
int buffer_length,
usb_complete_t complete_fn,
void *context,
int interval)
{
urb->dev = dev;
urb->pipe = pipe;
urb->transfer_buffer = transfer_buffer;
urb->transfer_buffer_length = buffer_length;
urb->complete = complete_fn;
urb->context = context;
if (dev->speed == USB_SPEED_HIGH || dev->speed == USB_SPEED_SUPER)
urb->interval = 1 << (interval - 1);
else
urb->interval = interval;
urb->start_frame = -1;
}
其实probe主要是初始化usb设备和input设备,终极目标是为了完成urb的提交和input设备的注册。由于注册为input设备类型,那么当用户层open打开设备时候,最终会调用input中的open实现打开,我们看看input中open的实现
[cpp] view plain copy
static int usb_mouse_open(struct input_dev *dev)
{
struct usb_mouse *mouse = input_get_drvdata(dev); //获取私有数据
mouse->irq->dev = mouse->usbdev; //获取utb指针
if (usb_submit_urb(mouse->irq, GFP_KERNEL)) //提交urb
return -EIO;
return 0;
}
当用户层open打开这个USB鼠标后,我们就已经将urb提交给了USB core,那么根据USB数据处理流程知道,当处理完毕后,USB core会通知USB设备驱动程序,这里我们是响应中断服务程序,这就相当于该URB的回调函数。我们在提交urb时候定义了中断服务程序 usb_mouse_irq,我们跟踪看看
[cpp] view plain copy
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; //数据处理没成功,重新提交urb
}
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); //再次提交urb,等待下次响应
if (status)
err ("can‘t resubmit intr, %s-%s/input0, status %d",
mouse->usbdev->bus->bus_name,
mouse->usbdev->devpath, status);
}
根据上面的中断服务程序,我们应该知道,系统是周期性地获取鼠标的事件信息,因此在URB回调函数的末尾再次提交URB请求块,这样又会调用新的回调函数,周而复始。在回调函数中提交URB只能是GFP_ATOMIC优先级,因为URB回调函数运行于中断上下文中禁止导致睡眠的行为。而在提交URB 过程中可能会需要申请内存、保持信号量,这些操作或许会导致USB内核睡眠。
最后我们再看看这个驱动的私有数据mouse的定义
[cpp] view plain copy
struct usb_mouse {
char name[128]; //名字
char phys[64]; //设备节点
struct usb_device *usbdev; //内嵌usb_device设备
struct input_dev *dev; //内嵌input_dev设备
struct urb *irq; //urb结构体
signed char *data; //transfer_buffer缓冲区
dma_addr_t data_dma; //transfer _dma缓冲区
};
在上面这个结构体中,每一个成员的作用都应该很清楚了,尤其最后两个的使用区别和作用,前面也已经说过。
如果最终需要测试这个USB鼠标驱动,需要在内核中配置USB支持、对HID接口的支持、对OHCI HCD驱动的支持。另外,将驱动移植到开发板之后,由于采用的是input设备模型,所以还需要开发板带LCD屏才能测试。
Linux_usb驱动之键盘驱动
跟USB鼠标类型一样,USB键盘也属于HID类型,代码在/dirver/hid/usbhid/usbkbd.c下。USB键盘除了提交中断URB外,还需要提交控制URB。不多话,我们看代码
[cpp] view plain copy
static int __init usb_kbd_init(void)
{
int result = usb_register(&usb_kbd_driver);
if (result == 0)
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
return result;
}
[cpp] view plain copy
static struct usb_driver usb_kbd_driver = {
.name = "usbkbd",
.probe = usb_kbd_probe,
.disconnect = usb_kbd_disconnect,
.id_table = usb_kbd_id_table, //驱动设备ID表,用来指定设备或接口
};
下面跟踪usb_driver中的probe
[cpp] view plain copy
static int usb_kbd_probe(struct usb_interface *iface,
const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(iface); //通过接口获取USB设备指针
struct usb_host_interface *interface; //设置
struct usb_endpoint_descriptor *endpoint; //端点描述符
struct usb_kbd *kbd; //usb_kbd私有数据
struct input_dev *input_dev; //input设备
int i, pipe, maxp;
int error = -ENOMEM;
interface = iface->cur_altsetting; //获取设置
if (interface->desc.bNumEndpoints != 1) //与mouse一样只有一个端点
return -ENODEV;
endpoint = &interface->endpoint[0].desc; //获取端点描述符
if (!usb_endpoint_is_int_in(endpoint)) //检查端点是否为中断输入端点
return -ENODEV;
pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress); //将endpoint设置为中断IN端点
maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe)); //端点传输的最大数据包
kbd = kzalloc(sizeof(struct usb_kbd), GFP_KERNEL); //分配urb
input_dev = input_allocate_device(); //分配input设备空间
if (!kbd || !input_dev)
goto fail1;
if (usb_kbd_alloc_mem(dev, kbd)) //分配urb空间和其他缓冲区
goto fail2;
kbd->usbdev = dev; //给内嵌结构体赋值
kbd->dev = input_dev;
if (dev->manufacturer) //拷贝厂商ID
strlcpy(kbd->name, dev->manufacturer, sizeof(kbd->name));
if (dev->product) { //拷贝产品ID
if (dev->manufacturer)
strlcat(kbd->name, " ", sizeof(kbd->name));
strlcat(kbd->name, dev->product, sizeof(kbd->name));
}
if (!strlen(kbd->name)) //检测不到厂商名字
snprintf(kbd->name, sizeof(kbd->name),
"USB HIDBP Keyboard %04x:%04x",
le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
//设备链接地址
usb_make_path(dev, kbd->phys, sizeof(kbd->phys));
strlcat(kbd->phys, "/input0", sizeof(kbd->phys));
input_dev->name = kbd->name; //给input_dev结构体赋值
input_dev->phys = kbd->phys;
usb_to_input_id(dev, &input_dev->id); //拷贝usb_driver的支持给input,设置bustype,vendo,product等
input_dev->dev.parent = &iface->dev;
input_set_drvdata(input_dev, kbd); //将kbd设置为input的私有数据
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_LED) |
BIT_MASK(EV_REP); //支持的按键事件类型
input_dev->ledbit[0] = BIT_MASK(LED_NUML) | BIT_MASK(LED_CAPSL) |
BIT_MASK(LED_SCROLLL) | BIT_MASK(LED_COMPOSE) |
BIT_MASK(LED_KANA); //EV_LED事件支持的事件码
for (i = 0; i < 255; i++)
set_bit(usb_kbd_keycode[i], input_dev->keybit); //EV_KEY事件支持的事件码(即设置支持的键盘码)
clear_bit(0, input_dev->keybit);
input_dev->event = usb_kbd_event; //定义event函数
input_dev->open = usb_kbd_open;
input_dev->close = usb_kbd_close;
usb_fill_int_urb(kbd->irq, dev, pipe,
kbd->new, (maxp > 8 ? 8 : maxp),
usb_kbd_irq, kbd, endpoint->bInterval);//填充中断urb
kbd->irq->transfer_dma = kbd->new_dma;
kbd->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
kbd->cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
kbd->cr->bRequest = 0x09;//设置控制请求的格式
kbd->cr->wValue = cpu_to_le16(0x200);
kbd->cr->wIndex = cpu_to_le16(interface->desc.bInterfaceNumber);
kbd->cr->wLength = cpu_to_le16(1);
usb_fill_control_urb(kbd->led, dev, usb_sndctrlpipe(dev, 0),
(void *) kbd->cr, kbd->leds, 1,
usb_kbd_led, kbd);//填充控制urb
kbd->led->transfer_dma = kbd->leds_dma;
kbd->led->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
error = input_register_device(kbd->dev);
if (error)
goto fail2;
usb_set_intfdata(iface, kbd);
device_set_wakeup_enable(&dev->dev, 1);
return 0;
fail2:
usb_kbd_free_mem(dev, kbd);
fail1:
input_free_device(input_dev);
kfree(kbd);
return error;
}
在上面的probe中,我们主要是初始化一些结构体,然后提交中断urb和控制urb,并注册input设备。其中有几个地方需要细看下,其一,usb_kbd_alloc_mem的实现。其二,设置控制请求的格式。
先来看看usb_kbd_alloc_mem的实现
[cpp] view plain copy
static int usb_kbd_alloc_mem(struct usb_device *dev, struct usb_kbd *kbd)
{
if (!(kbd->irq = usb_alloc_urb(0, GFP_KERNEL))) //分配中断urb
return -1;
if (!(kbd->led = usb_alloc_urb(0, GFP_KERNEL))) //分配控制urb
return -1;
if (!(kbd->new = usb_alloc_coherent(dev, 8, GFP_ATOMIC, &kbd->new_dma)))
return -1; //分配中断urb使用的缓冲区
if (!(kbd->cr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL)))
return -1; //分配控制urb使用的控制请求描述符
if (!(kbd->leds = usb_alloc_coherent(dev, 1, GFP_ATOMIC, &kbd->leds_dma)))
return -1; //分配控制urb使用的缓冲区
return 0;
}
这里我们需要明白中断urb和控制urb需要分配不同的urb结构体,同时在提交urb之前,需要填充的内容也不同,中断urb填充的是缓冲区和中断处理函数,控制urb填充的是控制请求描述符与回调函数。
设置控制请求的格式。cr是struct usb_ctrlrequest结构的指针,USB协议中规定一个控制请求的格式为一个8个字节的数据包,其定义如下
[cpp] view plain copy
/**
* struct usb_ctrlrequest - SETUP data for a USB device control request
* @bRequestType: matches the USB bmRequestType field
* @bRequest: matches the USB bRequest field
* @wValue: matches the USB wValue field (le16 byte order)
* @wIndex: matches the USB wIndex field (le16 byte order)
* @wLength: matches the USB wLength field (le16 byte order)
*
* This structure is used to send control requests to a USB device. It matches
* the different fields of the USB 2.0 Spec section 9.3, table 9-2. See the
* USB spec for a fuller description of the different fields, and what they are
* used for.
*
* Note that the driver for any interface can issue control requests.
* For most devices, interfaces don‘t coordinate with each other, so
* such requests may be made at any time.
*/
struct usb_ctrlrequest {
__u8 bRequestType; //设定传输方向、请求类型等
__u8 bRequest; //指定哪个请求,可以是规定的标准值也可以是厂家定义的值
__le16 wValue; //即将写到寄存器的数据
__le16 wIndex; //接口数量,也就是寄存器的偏移地址
__le16 wLength; //数据传输阶段传输多少个字节
} __attribute__ ((packed));
USB协议中规定,所有的USB设备都会响应主机的一些请求,这些请求来自USB主机控制器,主机控制器通过设备的默认控制管道发出这些请求。默认的管道为0号端口对应的那个管道。
同样这个input设备首先由用户层调用open函数,所以先看看input中定义的open
[cpp] view plain copy
static int usb_kbd_open(struct input_dev *dev)
{
struct usb_kbd *kbd = input_get_drvdata(dev);
kbd->irq->dev = kbd->usbdev;
if (usb_submit_urb(kbd->irq, GFP_KERNEL))
return -EIO;
return 0;
}
因为这个驱动里面有一个中断urb一个控制urb,我们先看中断urb的处理流程。中断urb在input的open中被提交后,当USB core处理完毕,会通知这个USB设备驱动,然后执行回调函数,也就是中断处理函数usb_kbd_irq
[cpp] view plain copy
static void usb_kbd_irq(struct urb *urb)
{
struct usb_kbd *kbd = urb->context;
int i;
switch (urb->status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default: /* error */
goto resubmit;
}
//报告usb_kbd_keycode[224..231]8按键状态
//KEY_LEFTCTRL,KEY_LEFTSHIFT,KEY_LEFTALT,KEY_LEFTMETA,
//KEY_RIGHTCTRL,KEY_RIGHTSHIFT,KEY_RIGHTALT,KEY_RIGHTMETA
for (i = 0; i < 8; i++)
input_report_key(kbd->dev, usb_kbd_keycode[i + 224], (kbd->new[0] >> i) & 1);
//若同时只按下1个按键则在第[2]个字节,若同时有两个按键则第二个在第[3]字节,类推最多可有6个按键同时按下
for (i = 2; i < 8; i++) {
//获取键盘离开的中断
//同时没有该KEY的按下状态
if (kbd->old[i] > 3 && memscan(kbd->new + 2, kbd->old[i], 6) == kbd->new + 8) {
if (usb_kbd_keycode[kbd->old[i]])
input_report_key(kbd->dev, usb_kbd_keycode[kbd->old[i]], 0);
else
hid_info(urb->dev,
"Unknown key (scancode %#x) released.\n",
kbd->old[i]);
}
//获取键盘按下的中断
//同时没有该KEY的离开状态
if (kbd->new[i] > 3 && memscan(kbd->old + 2, kbd->new[i], 6) == kbd->old + 8) {
if (usb_kbd_keycode[kbd->new[i]])
input_report_key(kbd->dev, usb_kbd_keycode[kbd->new[i]], 1);
else
hid_info(urb->dev,
"Unknown key (scancode %#x) released.\n",
kbd->new[i]);
}
}
input_sync(kbd->dev); //同步设备,告知事件的接收者驱动已经发出了一个完整的报告
memcpy(kbd->old, kbd->new, 8); //防止未松开时被当成新的按键处理
resubmit:
i = usb_submit_urb (urb, GFP_ATOMIC);
if (i)
hid_err(urb->dev, "can‘t resubmit intr, %s-%s/input0, status %d",
kbd->usbdev->bus->bus_name,
kbd->usbdev->devpath, i);
}
这个就是中断urb的处理流程,跟前面讲的的USB鼠标中断处理流程类似。好了,我们再来看看剩下的控制urb处理流程吧。
我们有个疑问,我们知道在probe中,我们填充了中断urb和控制urb,但是在input的open中,我们只提交了中断urb,那么控制urb什么时候提交呢?
我们知道对于input子系统,如果有事件被响应,我们会调用事件处理层的event函数,而该函数最终调用的是input下的event。所以,对于input设备,我们在USB键盘驱动中只设置了支持LED选项,也就是ledbit项,这是怎么回事呢?刚才我们分析的那个中断urb其实跟这个 input基本没啥关系,中断urb并不是像讲键盘input实现的那样属于input下的中断。我们在USB键盘驱动中的input子系统中只设计了 LED选项,那么当input子系统有按键选项的时候必然会使得内核调用调用事件处理层的event函数,最终调用input下的event。好了,那我们来看看input下的event干了些什么。
[cpp] view plain copy
static int usb_kbd_event(struct input_dev *dev, unsigned int type,
unsigned int code, int value)
{
struct usb_kbd *kbd = input_get_drvdata(dev);
if (type != EV_LED)//不支持LED事件
return -1;
//获取指示灯的目标状态
kbd->newleds = (!!test_bit(LED_KANA, dev->led) << 3) | (!!test_bit(LED_COMPOSE, dev->led) << 3) |
(!!test_bit(LED_SCROLLL, dev->led) << 2) | (!!test_bit(LED_CAPSL, dev->led) << 1) |
(!!test_bit(LED_NUML, dev->led));
if (kbd->led->status == -EINPROGRESS)
return 0;
//指示灯状态已经是目标状态则不需要再做任何操作
if (*(kbd->leds) == kbd->newleds)
return 0;
*(kbd->leds) = kbd->newleds;
kbd->led->dev = kbd->usbdev;
if (usb_submit_urb(kbd->led, GFP_ATOMIC))
pr_err("usb_submit_urb(leds) failed\n");
//提交控制urb
return 0;
}
当在input的event里提交了控制urb后,经过URB处理流程,最后返回给USB设备驱动的回调函数,也就是在probe中定义的usb_kbd_led
[cpp] view plain copy
static void usb_kbd_led(struct urb *urb)
{
struct usb_kbd *kbd = urb->context;
if (urb->status)
hid_warn(urb->dev, "led urb status %d received\n",
urb->status);
if (*(kbd->leds) == kbd->newleds)
return;
*(kbd->leds) = kbd->newleds;
kbd->led->dev = kbd->usbdev;
if (usb_submit_urb(kbd->led, GFP_ATOMIC))
hid_err(urb->dev, "usb_submit_urb(leds) failed\n");
}
总结下,我们的控制urb走的是先由input的event提交,触发后由控制urb的回调函数再次提交。好了,通过USB鼠标,我们已经知道了控制urb和中断urb的设计和处理流程。
<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">