Linux USB设备驱动程序设计 和 USB下载线驱动设计
USB设备驱动模型
USB设备包括配置(configuration)、接口(interface)和端点(endpoint),一个USB设备驱动程序对应一个USB接口,而非整个USB设备。
在Linux内核中,使用 struct usb_driver结构体 描述一个USB驱动。
struct usb_driver {
const char *name; /*驱动程序名*/
/* 当USB核心发现了该驱动能够处理的USB接口时,调用该函数 */
int (*probe) (struct usb_interface *intf, const struct usb_device_id *id);
/* 当相应的USB接口被移除时,调用该函数 */
void (*disconnect) (struct usb_interface *intf);
/* USB驱动能够处理的设备列表 */
const struct usb_device_id *id_table;
}
URB通讯模型
USB请求块(USB request block-URB)是USB设备驱动中用来与USB设备通信所用的基本载体和核心数据结构,非常类似于网络设备驱动中的sk_buff结构体,是USB主机与设备通信的“电波”。
struct urb *usb_alloc_urb(int iso_packets, gfp_t mem_flags)
//参数:
//iso_packets:urb所包含的等时数据包的个数。
//mem_flags:内存分配标识(如GFP_KERNEL),参考kmalloc。
static inline void usb_fill_int_urb(
struct urb *urb, //待初始化的urb
struct usb_device *dev, //urb所要访问的设备
unsigned int pipe, //要访问的端点所对应的管道,
void *transfer_buffer, //保存传输数据的buffer
int buffer_length, //buffer长度
usb_complete_t complete_fn, //urb完成时调用的函数
void *context, //赋值到urb->context的数据
int interval //urb被调度的时间间隔
)
在完成urb的创建和初始化后,USB驱动需要将urb提交
给USB核心。
int usb_submit_urb(struct urb *urb, gfp_t mem_flags)
//参数:
//urb:要提交urb的指针
//mem_flags: 内存分配标识(如GFP_KERNEL),参考kmalloc
URB被提交到USB核心后,USB核心指定usb主控制器驱动
程序来处理该urb,处理完之后,urb完成函数将被调用。
HID协议
HID(Human Interface Device), 属于人机交互类的设备,如USB鼠标,USB键盘,USB游戏操纵杆等。该类设备必须遵循HID设计规范。
鼠标设备驱动程序
从硬件结构上看,鼠标是URB总线设备,从功能上看,鼠标是输入型设备。因此鼠标驱动由两部分组成,分别是URB驱动和输入设备驱动。
代码举例:
#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>
/* for apple IDs */
#ifdef CONFIG_USB_HID_MODULE
#include "../hid-ids.h"
#endif
/*
* 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;
/* 检测urb传输是否成功 */
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)
{
/* 设备描述 usb_device */
/* 接口描述 usb_interface */
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;
/* 根据HID规范,鼠标只有一个端点(不包含0号控制端点)*/
if (interface->desc.bNumEndpoints != 1)
return -ENODEV;
/* 获取端点0描述符 */
endpoint = &interface->endpoint[0].desc;
/* 根据HID规范,鼠标唯一的端点应为中断端点 */
if (!usb_endpoint_is_int_in(endpoint))
return -ENODEV;
/* 生成中断管道 */
pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);
/* 返回该端点能够传输的最大的包长度,鼠标的返回的最大数据包为4个字节。*/
maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
/* 创建input设备 */
mouse = kzalloc(sizeof(struct usb_mouse), GFP_KERNEL);
input_dev = input_allocate_device();
if (!mouse || !input_dev)
goto fail1;
/* 申请内存空间用于数据传输,data 为指向该空间的地址*/
mouse->data = usb_buffer_alloc(dev, 8, GFP_ATOMIC, &mouse->data_dma);
if (!mouse->data)
goto fail1;
/* 分配URB */
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 用来获取 USB 设备在 Sysfs 中的路径*/
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_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);
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);
input_dev->open = usb_mouse_open;
input_dev->close = usb_mouse_close;
/* 初始化中断URB */
/* 思考实验:将interval参数设置为1分钟,观察现象 */
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;
/*将mouse指针保存到intf的dev成员中*/
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)
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
return retval;
}
static void __exit usb_mouse_exit(void)
{
usb_deregister(&usb_mouse_driver);
}
module_init(usb_mouse_init);
module_exit(usb_mouse_exit);
USB下载线驱动设计
内核驱动代码:
dnw_usb.c:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/usb.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#define BULKOUT_BUFFER_SIZE 512
char *bulkout_buffer;
struct usb_device *udev;
__u8 bulk_out_endaddr;
static struct usb_device_id dnw_id_table [] = {
{ USB_DEVICE(0x5345, 0x1234) },//在启动下载后,用lsusb命令在系统中查看
{ }
};
static int dnw_open(struct inode* inode, struct file *file)
{
bulkout_buffer = kmalloc(BULKOUT_BUFFER_SIZE,GFP_KERNEL);
return 0;
}
static int dnw_release (struct inode* inode, struct file *file)
{
kfree(bulkout_buffer);
return 0;
}
static ssize_t dnw_write(struct file *file, const char __user *buf, size_t len, loff_t *pos)
{
size_t to_write;
size_t total_write = 0;
size_t act_len;
while(len>0)
{
to_write = min(len,(size_t)BULKOUT_BUFFER_SIZE);
copy_from_user(bulkout_buffer,buf+total_write,to_write);
usb_bulk_msg(udev,usb_sndbulkpipe(udev,bulk_out_endaddr),bulkout_buffer,to_write,&act_len,3*HZ);
len -= to_write;
total_write += to_write;
}
return total_write;
}
static struct file_operations dnw_ops =
{
.owner = THIS_MODULE,
.write = dnw_write,
.open = dnw_open,
.release = dnw_release,
};
static struct usb_class_driver dnw_class = {
.name = "secbulk%d",
.fops = &dnw_ops,
.minor_base = 100,
};
static int dnw_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
/* 接口设置描述 */
struct usb_host_interface *interface;
struct usb_endpoint_descriptor *endpoint;
int i;
interface = intf->cur_altsetting;
for(i=0;i<interface->desc.bNumEndpoints;i++)
{
endpoint = &interface->endpoint[i].desc;
if(usb_endpoint_is_bulk_out(endpoint))
{
bulk_out_endaddr = endpoint->bEndpointAddress;
break;
}
}
usb_register_dev(intf,&dnw_class);//创建USB型字符设备
udev = usb_get_dev(interface_to_usbdev(intf));
}
static void dnw_disconnect(struct usb_interface *intf)
{
usb_deregister_dev(intf,&dnw_class);
}
struct usb_driver dnw_driver = {
.name = "dnw", /* 驱动名 */
.probe = dnw_probe, /* 捕获函数 */
.disconnect = dnw_disconnect, /* 卸载函数 */
.id_table = dnw_id_table, /* 设备列表 */
};
int dnw_init() //初始化入口函数
{
usb_register(&dnw_driver);//注册总线设备
return 0;
}
void dnw_exit() //退出函数
{
usb_deregister(&dnw_driver);
}
module_init(dnw_init);
module_exit(dnw_exit);
MODULE_LICENSE("GPL");
应用程序代码:
dnw.c
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
const char* dev = "/dev/dnw0";
int main(int argc, char* argv[])
{
unsigned char* file_buffer = NULL;
long int addr = 0;
if( 3 != argc ) {
printf("Usage: dwn <filename> address\n");
return 1;
}
int fd = open(argv[1], O_RDONLY);
if(-1 == fd) {
printf("Can not open file - %s\n", argv[1]);
return 1;
}
addr = strtol((char *) argv[2] ,NULL, 16);
printf("addr = %x \n", addr);
// get file size
struct stat file_stat;
if( -1 == fstat(fd, &file_stat) ) {
printf("Get file size filed!\n");
return 1;
}
file_buffer = (unsigned char*)malloc(file_stat.st_size+10);
if(NULL == file_buffer) {
printf("malloc failed!\n");
goto error;
}
//memset(file_buffer, '\0', sizeof(file_buffer)); // bad code ! corrected by Qulory
memset(file_buffer, '\0', sizeof(char)*(file_stat.st_size+10));
// the first 8 bytes in the file_buffer is reserved, the last 2 bytes also;
if( file_stat.st_size != read(fd, file_buffer+8, file_stat.st_size)) {
printf("Read file failed!\n");
goto error;
}
printf("File name : %s\n", argv[1]);
printf("File size : %ld bytes\n", file_stat.st_size);// off_t is long int
int fd_dev = open(dev, O_WRONLY);
if( -1 == fd_dev) {
printf("Can not open %s\n", dev);
goto error;
}
/*
* Note: the first 4 bytes store the dest addr ;
* the following 4 bytes store the file size ;
* and the last 2 bytes store the sum of each bytes of the file ;
*/
*((unsigned long*)file_buffer) = addr; //load address
*((unsigned long*)file_buffer+1) = file_stat.st_size+10; //file size
unsigned short sum = 0;
int i;
for(i=8; i<file_stat.st_size+8; i++) {
sum += file_buffer[i];
}
*((unsigned short*)(file_buffer+8+file_stat.st_size)) = sum;
printf("Start Sending data...\n");
size_t remain_size = file_stat.st_size+10;
size_t block_size = 512;
size_t written = 0;
while(remain_size > 0) {
size_t to_write = remain_size > block_size ? block_size:remain_size;
size_t real_write = write(fd_dev, file_buffer+written, to_write);
if( to_write != real_write) {
printf(" write /dev/secbulk0 failed! to_write = %u real_write = %u \n" , to_write ,real_write );
return 1;
}
remain_size -= to_write;
written += to_write;
printf("\rSent %lu%% \t %u bytes !", written*100/(file_stat.st_size+10), written);
fflush(stdout);
}
printf("OK\n");
return 0;
error:
if(-1 != fd_dev) {
close(fd_dev);
}
if(fd != -1) {
close(fd);
}
if( NULL != file_buffer ) {
free(file_buffer);
}
return -1;
}