Linux设备驱动开发---USB主机(控制器)与设备驱动(三)

一、Linux USB驱动层次

USB主机(控制器)与设备驱动(一)

二、USB主机(控制器)驱动

USB主机(控制器)与设备驱动(一)

三、USB设备驱动

USB主机(控制器)与设备驱动(二)

3.4 USB骨架程序(详解)

File path: drivers/usb/usb-skeleton.c(省略部分返回值判断及部分代码)

10)编写skel_delete函数(减少引用计数时使用)

	#define to_skel_dev(d) container_of(d, struct usb_skel, kref)
	
	static void skel_delete(struct kref *kref)
	{
		/*获取usb_skel整个变量的数据*/
		struct usb_skel *dev = to_skel_dev(kref);
		
		usb_free_urb(dev->bulk_in_urb);
		usb_put_dev(dev->udev);
		kfree(dev->bulk_in_buffer);
		kfree(dev);
	}

9)编写skel_write及其完成函数;

	9.2static void skel_write_bulk_callback(struct urb *urb)
		{
			struct usb_skel *dev;
			
			dev = urb->context;
			
			/*sync/async去除链路故障都不是errors*/
			if (urb->status) {
				if (!(urb->status == -ENOENT ||
					urb->status == -ECONNRESET ||
					urb->status == -ESHUTDOWN))
					dev_err(&dev->interface->dev, "%s - nonzero write bulk status received: %d\n",
						__func__, urb->status);

				spin_lock(&dev->err_lock);
				dev->errors = urb->status;
				spin_unlock(&dev->err_lock);
			}
			
			/*释放分配的buffer*/
			usb_free_coherent(urb->dev, urb->transfer_buffer_length,
				urb->transfer_buffer, urb->transfer_dma);
			up(&dev->limit_sem);
		}
	9.1static 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);
			
			/*1. 获取接口数据*/
			dev = file->private_data;
			
			/*2. 若无数据可写,则直接返回*/
			if (count == 0)
				goto exit;
			
			/*3. 限制urb的数量,防止将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;                            
				}                                         
			}

			/*4. 报告errors*/
			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;
			
			/*5. 创建一个urb和buffer,然后复制数据到该urb*/
			urb = usb_alloc_urb(0, GFP_KERNEL);
			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;
			}
			
			/*6. 确保不会将urb提交到已移除的device*/
			mutex_lock(&dev->io_mutex);
			if (!dev->interface) {		/* disconnect() was called */
				mutex_unlock(&dev->io_mutex);
				retval = -ENODEV;
				goto error;
			}
			
			/*7. 合适的初始化该urb*/
			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;
			usb_anchor_urb(urb, &dev->submitted);
			
			/*8. 发送数据到批量端口*/
			retval = usb_submit_urb(urb, GFP_KERNEL);
			mutex_unlock(&dev->io_mutex);
			if (retval) {
				dev_err(&dev->interface->dev,"%s - failed submitting write urb, error %d\n",
					__func__, retval);
				goto error_unanchor;
			}
			
			/*9. 释放对这个urb的引用,USB core会最终完全释放*/
			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;
		}

8)编写skel_read及依赖函数

	8.3)读操作完成函数
		static void skel_read_bulk_callback(struct urb *urb)
		{
			struct usb_skel *dev;
			
			dev = urb->context;
			
			spin_lock(&dev->err_lock);
			if (urb->status) {
				if (!(urb->status == -ENOENT || urb->status == -ECONNRESET ||urb->status == -ESHUTDOWN))
					dev_err(&dev->interface->dev, "%s - nonzero write bulk status received: %d\n",
						__func__, urb->status);
				dev->errors = urb->status;
			}else{
														//传输成功
				dev->bulk_in_filled = urb->actual_length;
			}
			dev->ongoing_read = 0;
			spin_unlock(&dev->err_lock);
			
			wake_up_interruptible(&dev->bulk_in_wait);
		}
	8.2static int skel_do_read_io(struct usb_skel *dev, size_t count)
		{
			int rv;
			
			/*1. 初始化urb*/
			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);
				
			/*2. 告诉其他进程正在进行读操作*/
			spin_lock_irq(&dev->err_lock);
			dev->ongoing_read = 1;
			spin_unlock_irq(&dev->err_lock);
			
			/*3. 提交urb到usb核心层*/
			dev->bulk_in_filled = 0;
			dev->bulk_in_copied = 0;

			rv = usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL);
			if (rv < 0) {
				dev_err(&dev->interface->dev, "%s - failed submitting read urb, error %d\n",
					__func__, rv);
				rv = (rv == -ENOMEM) ? rv : -EIO;
				spin_lock_irq(&dev->err_lock);
				dev->ongoing_read = 0;
				spin_unlock_irq(&dev->err_lock);
			}
			
			return rv;
		}
	8.1static ssize_t skel_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
		{
			struct usb_skel *dev;
			int rv;         
			bool ongoing_io;
			
			/*1. 获取接口数据*/
			dev = file->private_data;
			
			/*2. 如果什么也读不到,返回EOF*/
			if (!dev->bulk_in_urb || !count)
			return 0;
		
			/*3. 确保没有并发读操作*/
			rv = mutex_lock_interruptible(&dev->io_mutex);
			if (rv < 0)
				return rv;
			
			/*4. 检查设备是否有接口*/
			if (!dev->interface) {							//disconnect() was called
				rv = -ENODEV;
				goto exit;
			}
			
			/*5. 如果IO在运行,就不能touch things*/
		retry:
			spin_lock_irq(&dev->err_lock);
			ongoing_io = dev->ongoing_read;
			spin_unlock_irq(&dev->err_lock);
				
			if (ongoing_io) {
				if (file->f_flags & O_NONBLOCK) {			//如果时非阻塞,IO则不会wait
					rv = -EAGAIN;
					goto exit;
				}
															//否则,IO会一直等待中断状态
				rv = wait_event_interruptible(dev->bulk_in_wait, (!dev->ongoing_read));
				if (rv < 0)
					goto exit;
			}
			
			/*6. 报告errors*/
			rv = dev->errors;
			if (rv < 0) {
				dev->errors = 0;
				rv = (rv == -EPIPE) ? rv : -EIO;
				goto exit;
			}
			
			/*7. 如果buffer已被填充,就可以进行读操作了;否则需要启动IO*/
			if (dev->bulk_in_filled) {
				size_t available = dev->bulk_in_filled - dev->bulk_in_copied;
				size_t chunk = min(available, count);
				if(!available){									
					rv = skel_do_read_io(dev, count);
					if (rv < 0)
						goto exit;
					else
						goto retry;
				}
				if (copy_to_user(buffer, dev->bulk_in_buffer + dev->bulk_in_copied, chunk))		//复制user space
					rv = -EFAULT;
				else
					rv = chunk;
				dev->bulk_in_copied += chunk;
				
				if (available < count)							//如果要读的count大于可读的数量
					skel_do_read_io(dev, count - chunk);
			}else {
														//无数据可读	
				rv = skel_do_read_io(dev, count);		
				if (rv < 0)
					goto exit;
				else
					goto retry;
			}
		exit:
			mutex_unlock(&dev->io_mutex);
			
			return rv;	
		}

7)编写skel_open和skel_release函数

	static int skel_open(struct inode *inode, struct file *file)
	{
		struct usb_skel *dev;
		struct usb_interface *interface;
		int subminor;
		int retval = 0;
		
		/*1. 获取设备接口*/
		subminor = iminor(inode);
		interface = usb_find_interface(&skel_driver, subminor);
		if (!interface) {
			pr_err("%s - error, can't find device for minor %d\n", __func__, subminor);
			retval = -ENODEV;
			goto exit;
		}
		
		/*2. 获取接口数据*/
		dev = usb_get_intfdata(interface);
		if(!dev) {
			retval = -ENODEV;
			goto exit;
		}
		
		/*3. 增加usb接口的PM-usage计数*/
		retval = usb_autopm_get_interface(interface);
		if (retval)
			goto exit;
		
		/*4. 增加引用计数*/
		kref_get(&dev->kref);
		
		/*5. 保存接口数据到file->private_data*/
		file->private_data = dev;
	
	exit:
		return retval;
	}
	static int skel_release(struct inode *inode, struct file *file)
	{
		struct usb_skel *dev;
		
		/*1. 获取接口数据*/
		dev = file->private_data;
		if (dev == NULL)
			return -ENODEV;
		
		/*2. 减少usb接口的PM-usage计数*/
		mutex_lock(&dev->io_mutex);
		if (dev->interface)
			usb_autopm_put_interface(dev->interface);
		mutex_unlock(&dev->io_mutex);
		
		/*3. 减少引用计数*/
		kref_put(&dev->kref, skel_delete);
		
		return 0;
	}

6)定义skel_class里的成员函数;

	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,
	};

5)定义usb_class_driver结构体skel_class(probe和disconnect函数中注册/注销usb设备时需传入);

	static struct usb_class_driver skel_class = {
		.name =		"skel%d",                    
		.fops =		&skel_fops,                  
		.minor_base =	USB_SKEL_MINOR_BASE,     
	};                                           

4)编写skel_probe和skel_disconnect函数;

	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;
		
		/*1. 为设备分配内存并初始化设备*/
		dev = kzalloc(sizeof(*dev), GFP_KERNEL);
		...
		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_waitqueue_head(&dev->bulk_in_wait);
		
		dev->udev = usb_get_dev(interface_to_usbdev(interface));
		dev->interface = interface; 
		
		/*2. set up端点信息*/
		/*仅使用第一个bulk-in和bulk-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)) {
				buffer_size = usb_endpoint_maxp(endpoint);             
				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)
					...
				dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL);
				if (!dev->bulk_in_urb)
					...
			}
			if (!dev->bulk_out_endpointAddr && usb_endpoint_is_bulk_out(endpoint)) {
				dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
			}
		}
		if (!(dev->bulk_in_endpointAddr && dev->bulk_out_endpointAddr)) {
			dev_err(&interface->dev, "Could not find both bulk-in and bulk-out endpoints\n");
			...
		}
		
		/*3. 保存数据指针到该接口设备*/
		usb_set_intfdata(interface, dev);
		
		/*4. 注册该设备*/
		retval = usb_register_dev(interface, &skel_class);
		if (retval) {
			dev_err(&interface->dev, "Not able to get a minor for this device.\n");
			usb_set_intfdata(interface, NULL);
			...
		}
		
		/*4. 打印设备节点*/
		dev_info(&interface->dev,"USB Skeleton device now attached to USBSkel-%d",
			interface->minor);
			
		return 0;
	}
	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);

		/*1. 注销该usb设备,释放次设备号*/
		usb_deregister_dev(interface, &skel_class);
		
		/*2. 阻止更多的I/O启动*/
		mutex_lock(&dev->io_mutex);  
		dev->interface = NULL;       
		mutex_unlock(&dev->io_mutex);
		
		usb_kill_anchored_urbs(&dev->submitted);
		
		/*3. 减少引用计数*/
		kref_put(&dev->kref, skel_delete);
		
		dev_info(&interface->dev, "USB Skeleton #%d now disconnected", minor);	
	}

3)定义特定的设备数据结构;

	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 */
		bool			ongoing_read;		/* a read is going on */
		spinlock_t		err_lock;		/* lock for errors */
		struct kref		kref;
		struct mutex		io_mutex;		/* synchronize I/O with disconnect */
		wait_queue_head_t	bulk_in_wait;		/* to wait for an ongoing read */
	};

2)定义设备id,初始化skel_table,并导入到用户空间;

	/*定义该设备vendor id和product id*/
	#define USB_SKEL_VENDOR_ID	0xfff0
	#define USB_SKEL_PRODUCT_ID	0xfff0

	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);

1)初始化usb_driver结构体skel_driver,并注册该usb driver;

	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,
	};
	module_usb_driver(skel_driver);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值