早早的就买了Linux程序设计和Linux设备驱动程序两本书,一直没什么时间仔细阅读,总是偶尔拿来翻翻。
最近终于有个机会学习USB的驱动程序,手边没有现成的环境,先找找资料学习一下吧。
为Linux USB写驱动程序,要先了解现有的USB子系统。写驱动程序,一般先要分析usb-skeleton.c。我分析的内核代码版本是2.6.23。
文件中定义了设备结构体usb_skel:
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 */
unsigned char * bulk_in_buffer; /* the buffer to receive data */
size_t bulk_in_size; /* the size of the receive buffer */
__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 */
spinlock_t err_lock; /* lock for errors */
struct kref kref;
struct mutex io_mutex; /* synchronize I/O with disconnect */
}
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 */
unsigned char * bulk_in_buffer; /* the buffer to receive data */
size_t bulk_in_size; /* the size of the receive buffer */
__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 */
spinlock_t err_lock; /* lock for errors */
struct kref kref;
struct mutex io_mutex; /* synchronize I/O with disconnect */
}
第一个见到的数据结构就是 struct usb_device,在这里实际就代表这个驱动程序所对应的设备信息。然后将会看到struct usb_interface 结构体,代表了这个设备的接口信息。limit_sem是进行并发控制的,bulk_in_buffer是接收数据的缓冲区,bulk_in_size是缓冲区的大小。bulk_in_endpointAddr和bulk_out_endpointAddr是批量输入输出端口地址。open_count是打开设备的计数器。kref是一个内核使用的引用计数器。io_mutex是I/O的互斥量。err_lock是错误旋锁,errors是错误代码。