1 /*
2  * USB Skeleton driver - 0.7
3  *
4  * Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
5  *
6  *	This program is free software; you can redistribute it and/or
7  *	modify it under the terms of the GNU General Public License as
8  *	published by the Free Software Foundation; either version 2 of
9  *	the License, or (at your option) any later version.
10  *
11  *
12  * This driver is to be used as a skeleton driver to be able to create a
13  * USB driver quickly.  The design of it is based on the usb-serial and
14  * dc2xx drivers.
15  *
16  * Thanks to Oliver Neukum and David Brownell for their help in debugging
17  * this driver.
18  *
19  * TODO:
20  *	- fix urb->status race condition in write sequence
21  *	- move minor_table to a dynamic list.
22  *
23  * History:
24  *
25  * 2002_02_12 - 0.7 - zero out dev in probe function for devices that do
26  *			not have both a bulk in and bulk out endpoint.
27  *			Thanks to Holger Waechtler for the fix.
28  * 2001_11_05 - 0.6 - fix minor locking problem in skel_disconnect.
29  *			Thanks to Pete Zaitcev for the fix.
30  * 2001_09_04 - 0.5 - fix devfs bug in skel_disconnect. Thanks to wim delvaux
31  * 2001_08_21 - 0.4 - more small bug fixes.
32  * 2001_05_29 - 0.3 - more bug fixes based on review from linux-usb-devel
33  * 2001_05_24 - 0.2 - bug fixes based on review from linux-usb-devel people
34  * 2001_05_01 - 0.1 - first version
35  *
36  */
37 
38 #include <linux/config.h>
39 #include <linux/kernel.h>
40 #include <linux/sched.h>
41 #include <linux/signal.h>
42 #include <linux/errno.h>
43 #include <linux/poll.h>
44 #include <linux/init.h>
45 #include <linux/slab.h>
46 #include <linux/fcntl.h>
47 #include <linux/module.h>
48 #include <linux/spinlock.h>
49 #include <linux/list.h>
50 #include <linux/smp_lock.h>
51 #include <linux/devfs_fs_kernel.h>
52 #include <linux/usb.h>
53 
54 #ifdef CONFIG_USB_DEBUG
55 	static int debug = 1;
56 #else
57 	static int debug;
58 #endif
59 
60 /* Use our own dbg macro */
61 #undef dbg
62 #define dbg(format, arg...) do { if (debug) printk(KERN_DEBUG __FILE__ ": " format "\n" , ## arg); } while (0)
63 
64 
65 /* Version Information */
66 #define DRIVER_VERSION "v0.4"
67 #define DRIVER_AUTHOR "Greg Kroah-Hartman, greg@kroah.com"
68 #define DRIVER_DESC "USB Skeleton Driver"
69 
70 /* Module paramaters */
71 MODULE_PARM(debug, "i");
72 MODULE_PARM_DESC(debug, "Debug enabled or not");
73 
74 
75 /* Define these values to match your device */
76 #define USB_SKEL_VENDOR_ID	0xfff0
77 #define USB_SKEL_PRODUCT_ID	0xfff0
78 
79 /* table of devices that work with this driver */
80 static struct usb_device_id skel_table [] = {
81 	{ USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
82 	{ }					/* Terminating entry */
83 };
84 
85 MODULE_DEVICE_TABLE (usb, skel_table);
86 
87 
88 
89 /* Get a minor range for your devices from the usb maintainer */
90 #define USB_SKEL_MINOR_BASE	192
91 
92 /* we can have up to this number of device plugged in at once */
93 #define MAX_DEVICES		16
94 
95 /* Structure to hold all of our device specific stuff */
96 struct usb_skel {
97 	struct usb_device *	udev;			/* save off the usb device pointer */
98 	struct usb_interface *	interface;		/* the interface for this device */
99 	devfs_handle_t		devfs;			/* devfs device node */
100 	unsigned char		minor;			/* the starting minor number for this device */
101 	unsigned char		num_ports;		/* the number of ports this device has */
102 	char			num_interrupt_in;	/* number of interrupt in endpoints we have */
103 	char			num_bulk_in;		/* number of bulk in endpoints we have */
104 	char			num_bulk_out;		/* number of bulk out endpoints we have */
105 
106 	unsigned char *		bulk_in_buffer;		/* the buffer to receive data */
107 	int			bulk_in_size;		/* the size of the receive buffer */
108 	__u8			bulk_in_endpointAddr;	/* the address of the bulk in endpoint */
109 
110 	unsigned char *		bulk_out_buffer;	/* the buffer to send data */
111 	int			bulk_out_size;		/* the size of the send buffer */
112 	struct urb *		write_urb;		/* the urb used to send data */
113 	__u8			bulk_out_endpointAddr;	/* the address of the bulk out endpoint */
114 
115 	struct tq_struct	tqueue;			/* task queue for line discipline waking up */
116 	int			open_count;		/* number of times this port has been opened */
117 	struct semaphore	sem;			/* locks this structure */
118 };
119 
120 
121 /* the global usb devfs handle */
122 extern devfs_handle_t usb_devfs_handle;
123 
124 
125 /* local function prototypes */
126 static ssize_t skel_read	(struct file *file, char *buffer, size_t count, loff_t *ppos);
127 static ssize_t skel_write	(struct file *file, const char *buffer, size_t count, loff_t *ppos);
128 static int skel_ioctl		(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg);
129 static int skel_open		(struct inode *inode, struct file *file);
130 static int skel_release		(struct inode *inode, struct file *file);
131 
132 static void * skel_probe	(struct usb_device *dev, unsigned int ifnum, const struct usb_device_id *id);
133 static void skel_disconnect	(struct usb_device *dev, void *ptr);
134 
135 static void skel_write_bulk_callback	(struct urb *urb);
136 
137 
138 /* array of pointers to our devices that are currently connected */
139 static struct usb_skel		*minor_table[MAX_DEVICES];
140 
141 /* lock to protect the minor_table structure */
142 static DECLARE_MUTEX (minor_table_mutex);
143 
144 /*
145  * File operations needed when we register this driver.
146  * This assumes that this driver NEEDS file operations,
147  * of course, which means that the driver is expected
148  * to have a node in the /dev directory. If the USB
149  * device were for a network interface then the driver
150  * would use "struct net_driver" instead, and a serial
151  * device would use "struct tty_driver".
152  */
153 static struct file_operations skel_fops = {
154 	/*
155 	 * The owner field is part of the module-locking
156 	 * mechanism. The idea is that the kernel knows
157 	 * which module to increment the use-counter of
158 	 * BEFORE it calls the device's open() function.
159 	 * This also means that the kernel can decrement
160 	 * the use-counter again before calling release()
161 	 * or should the open() function fail.
162 	 *
163 	 * Not all device structures have an "owner" field
164 	 * yet. "struct file_operations" and "struct net_device"
165 	 * do, while "struct tty_driver" does not. If the struct
166 	 * has an "owner" field, then initialize it to the value
167 	 * THIS_MODULE and the kernel will handle all module
168 	 * locking for you automatically. Otherwise, you must
169 	 * increment the use-counter in the open() function
170 	 * and decrement it again in the release() function
171 	 * yourself.
172 	 */
173 	owner:		THIS_MODULE,
174 
175 	read:		skel_read,
176 	write:		skel_write,
177 	ioctl:		skel_ioctl,
178 	open:		skel_open,
179 	release:	skel_release,
180 };
181 
182 
183 /* usb specific object needed to register this driver with the usb subsystem */
184 static struct usb_driver skel_driver = {
185 	name:		"skeleton",
186 	probe:		skel_probe,
187 	disconnect:	skel_disconnect,
188 	fops:		&skel_fops,
189 	minor:		USB_SKEL_MINOR_BASE,
190 	id_table:	skel_table,
191 };
192 
193 
194 
195 
196 
197 /**
198  *	usb_skel_debug_data
199  */
usb_skel_debug_data(const char * function,int size,const unsigned char * data)200 static inline void usb_skel_debug_data (const char *function, int size, const unsigned char *data)
201 {
202 	int i;
203 
204 	if (!debug)
205 		return;
206 
207 	printk (KERN_DEBUG __FILE__": %s - length = %d, data = ",
208 		function, size);
209 	for (i = 0; i < size; ++i) {
210 		printk ("%.2x ", data[i]);
211 	}
212 	printk ("\n");
213 }
214 
215 
216 /**
217  *	skel_delete
218  */
skel_delete(struct usb_skel * dev)219 static inline void skel_delete (struct usb_skel *dev)
220 {
221 	minor_table[dev->minor] = NULL;
222 	if (dev->bulk_in_buffer != NULL)
223 		kfree (dev->bulk_in_buffer);
224 	if (dev->bulk_out_buffer != NULL)
225 		kfree (dev->bulk_out_buffer);
226 	if (dev->write_urb != NULL)
227 		usb_free_urb (dev->write_urb);
228 	kfree (dev);
229 }
230 
231 
232 /**
233  *	skel_open
234  */
skel_open(struct inode * inode,struct file * file)235 static int skel_open (struct inode *inode, struct file *file)
236 {
237 	struct usb_skel *dev = NULL;
238 	int subminor;
239 	int retval = 0;
240 
241 	dbg(__FUNCTION__);
242 
243 	subminor = MINOR (inode->i_rdev) - USB_SKEL_MINOR_BASE;
244 	if ((subminor < 0) ||
245 	    (subminor >= MAX_DEVICES)) {
246 		return -ENODEV;
247 	}
248 
249 	/* Increment our usage count for the module.
250 	 * This is redundant here, because "struct file_operations"
251 	 * has an "owner" field. This line is included here soley as
252 	 * a reference for drivers using lesser structures... ;-)
253 	 */
254 	MOD_INC_USE_COUNT;
255 
256 	/* lock our minor table and get our local data for this minor */
257 	down (&minor_table_mutex);
258 	dev = minor_table[subminor];
259 	if (dev == NULL) {
260 		up (&minor_table_mutex);
261 		MOD_DEC_USE_COUNT;
262 		return -ENODEV;
263 	}
264 
265 	/* lock this device */
266 	down (&dev->sem);
267 
268 	/* unlock the minor table */
269 	up (&minor_table_mutex);
270 
271 	/* increment our usage count for the driver */
272 	++dev->open_count;
273 
274 	/* save our object in the file's private structure */
275 	file->private_data = dev;
276 
277 	/* unlock this device */
278 	up (&dev->sem);
279 
280 	return retval;
281 }
282 
283 
284 /**
285  *	skel_release
286  */
skel_release(struct inode * inode,struct file * file)287 static int skel_release (struct inode *inode, struct file *file)
288 {
289 	struct usb_skel *dev;
290 	int retval = 0;
291 
292 	dev = (struct usb_skel *)file->private_data;
293 	if (dev == NULL) {
294 		dbg (__FUNCTION__ " - object is NULL");
295 		return -ENODEV;
296 	}
297 
298 	dbg(__FUNCTION__ " - minor %d", dev->minor);
299 
300 	/* lock our minor table */
301 	down (&minor_table_mutex);
302 
303 	/* lock our device */
304 	down (&dev->sem);
305 
306 	if (dev->open_count <= 0) {
307 		dbg (__FUNCTION__ " - device not opened");
308 		retval = -ENODEV;
309 		goto exit_not_opened;
310 	}
311 
312 	if (dev->udev == NULL) {
313 		/* the device was unplugged before the file was released */
314 		up (&dev->sem);
315 		skel_delete (dev);
316 		up (&minor_table_mutex);
317 		MOD_DEC_USE_COUNT;
318 		return 0;
319 	}
320 
321 	/* decrement our usage count for the device */
322 	--dev->open_count;
323 	if (dev->open_count <= 0) {
324 		/* shutdown any bulk writes that might be going on */
325 		usb_unlink_urb (dev->write_urb);
326 		dev->open_count = 0;
327 	}
328 
329 	/* decrement our usage count for the module */
330 	MOD_DEC_USE_COUNT;
331 
332 exit_not_opened:
333 	up (&dev->sem);
334 	up (&minor_table_mutex);
335 
336 	return retval;
337 }
338 
339 
340 /**
341  *	skel_read
342  */
skel_read(struct file * file,char * buffer,size_t count,loff_t * ppos)343 static ssize_t skel_read (struct file *file, char *buffer, size_t count, loff_t *ppos)
344 {
345 	struct usb_skel *dev;
346 	int retval = 0;
347 
348 	dev = (struct usb_skel *)file->private_data;
349 
350 	dbg(__FUNCTION__ " - minor %d, count = %d", dev->minor, count);
351 
352 	/* lock this object */
353 	down (&dev->sem);
354 
355 	/* verify that the device wasn't unplugged */
356 	if (dev->udev == NULL) {
357 		up (&dev->sem);
358 		return -ENODEV;
359 	}
360 
361 	/* do an immediate bulk read to get data from the device */
362 	retval = usb_bulk_msg (dev->udev,
363 			       usb_rcvbulkpipe (dev->udev,
364 						dev->bulk_in_endpointAddr),
365 			       dev->bulk_in_buffer, dev->bulk_in_size,
366 			       &count, HZ*10);
367 
368 	/* if the read was successful, copy the data to userspace */
369 	if (!retval) {
370 		if (copy_to_user (buffer, dev->bulk_in_buffer, count))
371 			retval = -EFAULT;
372 		else
373 			retval = count;
374 	}
375 
376 	/* unlock the device */
377 	up (&dev->sem);
378 	return retval;
379 }
380 
381 
382 /**
383  *	skel_write
384  */
skel_write(struct file * file,const char * buffer,size_t count,loff_t * ppos)385 static ssize_t skel_write (struct file *file, const char *buffer, size_t count, loff_t *ppos)
386 {
387 	struct usb_skel *dev;
388 	ssize_t bytes_written = 0;
389 	int retval = 0;
390 
391 	dev = (struct usb_skel *)file->private_data;
392 
393 	dbg(__FUNCTION__ " - minor %d, count = %d", dev->minor, count);
394 
395 	/* lock this object */
396 	down (&dev->sem);
397 
398 	/* verify that the device wasn't unplugged */
399 	if (dev->udev == NULL) {
400 		retval = -ENODEV;
401 		goto exit;
402 	}
403 
404 	/* verify that we actually have some data to write */
405 	if (count == 0) {
406 		dbg(__FUNCTION__ " - write request of 0 bytes");
407 		goto exit;
408 	}
409 
410 	/* see if we are already in the middle of a write */
411 	if (dev->write_urb->status == -EINPROGRESS) {
412 		dbg (__FUNCTION__ " - already writing");
413 		goto exit;
414 	}
415 
416 	/* we can only write as much as 1 urb will hold */
417 	bytes_written = (count > dev->bulk_out_size) ?
418 				dev->bulk_out_size : count;
419 
420 	/* copy the data from userspace into our urb */
421 	if (copy_from_user(dev->write_urb->transfer_buffer, buffer,
422 			   bytes_written)) {
423 		retval = -EFAULT;
424 		goto exit;
425 	}
426 
427 	usb_skel_debug_data (__FUNCTION__, bytes_written,
428 			     dev->write_urb->transfer_buffer);
429 
430 	/* set up our urb */
431 	FILL_BULK_URB(dev->write_urb, dev->udev,
432 		      usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
433 		      dev->write_urb->transfer_buffer, bytes_written,
434 		      skel_write_bulk_callback, dev);
435 
436 	/* send the data out the bulk port */
437 	retval = usb_submit_urb(dev->write_urb);
438 	if (retval) {
439 		err(__FUNCTION__ " - failed submitting write urb, error %d",
440 		    retval);
441 	} else {
442 		retval = bytes_written;
443 	}
444 
445 exit:
446 	/* unlock the device */
447 	up (&dev->sem);
448 
449 	return retval;
450 }
451 
452 
453 /**
454  *	skel_ioctl
455  */
skel_ioctl(struct inode * inode,struct file * file,unsigned int cmd,unsigned long arg)456 static int skel_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
457 {
458 	struct usb_skel *dev;
459 
460 	dev = (struct usb_skel *)file->private_data;
461 
462 	/* lock this object */
463 	down (&dev->sem);
464 
465 	/* verify that the device wasn't unplugged */
466 	if (dev->udev == NULL) {
467 		up (&dev->sem);
468 		return -ENODEV;
469 	}
470 
471 	dbg(__FUNCTION__ " - minor %d, cmd 0x%.4x, arg %ld",
472 	    dev->minor, cmd, arg);
473 
474 
475 	/* fill in your device specific stuff here */
476 
477 	/* unlock the device */
478 	up (&dev->sem);
479 
480 	/* return that we did not understand this ioctl call */
481 	return -ENOTTY;
482 }
483 
484 
485 /**
486  *	skel_write_bulk_callback
487  */
skel_write_bulk_callback(struct urb * urb)488 static void skel_write_bulk_callback (struct urb *urb)
489 {
490 	struct usb_skel *dev = (struct usb_skel *)urb->context;
491 
492 	dbg(__FUNCTION__ " - minor %d", dev->minor);
493 
494 	if ((urb->status != -ENOENT) &&
495 	    (urb->status != -ECONNRESET)) {
496 		dbg(__FUNCTION__ " - nonzero write bulk status received: %d",
497 		    urb->status);
498 		return;
499 	}
500 
501 	return;
502 }
503 
504 
505 /**
506  *	skel_probe
507  *
508  *	Called by the usb core when a new device is connected that it thinks
509  *	this driver might be interested in.
510  */
skel_probe(struct usb_device * udev,unsigned int ifnum,const struct usb_device_id * id)511 static void * skel_probe(struct usb_device *udev, unsigned int ifnum, const struct usb_device_id *id)
512 {
513 	struct usb_skel *dev = NULL;
514 	struct usb_interface *interface;
515 	struct usb_interface_descriptor *iface_desc;
516 	struct usb_endpoint_descriptor *endpoint;
517 	int minor;
518 	int buffer_size;
519 	int i;
520 	char name[10];
521 
522 
523 	/* See if the device offered us matches what we can accept */
524 	if ((udev->descriptor.idVendor != USB_SKEL_VENDOR_ID) ||
525 	    (udev->descriptor.idProduct != USB_SKEL_PRODUCT_ID)) {
526 		return NULL;
527 	}
528 
529 	/* select a "subminor" number (part of a minor number) */
530 	down (&minor_table_mutex);
531 	for (minor = 0; minor < MAX_DEVICES; ++minor) {
532 		if (minor_table[minor] == NULL)
533 			break;
534 	}
535 	if (minor >= MAX_DEVICES) {
536 		info ("Too many devices plugged in, can not handle this device.");
537 		goto exit;
538 	}
539 
540 	/* allocate memory for our device state and intialize it */
541 	dev = kmalloc (sizeof(struct usb_skel), GFP_KERNEL);
542 	if (dev == NULL) {
543 		err ("Out of memory");
544 		goto exit;
545 	}
546 	memset (dev, 0x00, sizeof (*dev));
547 	minor_table[minor] = dev;
548 
549 	interface = &udev->actconfig->interface[ifnum];
550 
551 	init_MUTEX (&dev->sem);
552 	dev->udev = udev;
553 	dev->interface = interface;
554 	dev->minor = minor;
555 
556 	/* set up the endpoint information */
557 	/* check out the endpoints */
558 	iface_desc = &interface->altsetting[0];
559 	for (i = 0; i < iface_desc->bNumEndpoints; ++i) {
560 		endpoint = &iface_desc->endpoint[i];
561 
562 		if ((endpoint->bEndpointAddress & 0x80) &&
563 		    ((endpoint->bmAttributes & 3) == 0x02)) {
564 			/* we found a bulk in endpoint */
565 			buffer_size = endpoint->wMaxPacketSize;
566 			dev->bulk_in_size = buffer_size;
567 			dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
568 			dev->bulk_in_buffer = kmalloc (buffer_size, GFP_KERNEL);
569 			if (!dev->bulk_in_buffer) {
570 				err("Couldn't allocate bulk_in_buffer");
571 				goto error;
572 			}
573 		}
574 
575 		if (((endpoint->bEndpointAddress & 0x80) == 0x00) &&
576 		    ((endpoint->bmAttributes & 3) == 0x02)) {
577 			/* we found a bulk out endpoint */
578 			dev->write_urb = usb_alloc_urb(0);
579 			if (!dev->write_urb) {
580 				err("No free urbs available");
581 				goto error;
582 			}
583 			buffer_size = endpoint->wMaxPacketSize;
584 			dev->bulk_out_size = buffer_size;
585 			dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
586 			dev->bulk_out_buffer = kmalloc (buffer_size, GFP_KERNEL);
587 			if (!dev->bulk_out_buffer) {
588 				err("Couldn't allocate bulk_out_buffer");
589 				goto error;
590 			}
591 			FILL_BULK_URB(dev->write_urb, udev,
592 				      usb_sndbulkpipe(udev,
593 						      endpoint->bEndpointAddress),
594 				      dev->bulk_out_buffer, buffer_size,
595 				      skel_write_bulk_callback, dev);
596 		}
597 	}
598 
599 	/* initialize the devfs node for this device and register it */
600 	sprintf(name, "skel%d", dev->minor);
601 
602 	dev->devfs = devfs_register (usb_devfs_handle, name,
603 				     DEVFS_FL_DEFAULT, USB_MAJOR,
604 				     USB_SKEL_MINOR_BASE + dev->minor,
605 				     S_IFCHR | S_IRUSR | S_IWUSR |
606 				     S_IRGRP | S_IWGRP | S_IROTH,
607 				     &skel_fops, NULL);
608 
609 	/* let the user know what node this device is now attached to */
610 	info ("USB Skeleton device now attached to USBSkel%d", dev->minor);
611 	goto exit;
612 
613 error:
614 	skel_delete (dev);
615 	dev = NULL;
616 
617 exit:
618 	up (&minor_table_mutex);
619 	return dev;
620 }
621 
622 
623 /**
624  *	skel_disconnect
625  *
626  *	Called by the usb core when the device is removed from the system.
627  */
skel_disconnect(struct usb_device * udev,void * ptr)628 static void skel_disconnect(struct usb_device *udev, void *ptr)
629 {
630 	struct usb_skel *dev;
631 	int minor;
632 
633 	dev = (struct usb_skel *)ptr;
634 
635 	down (&minor_table_mutex);
636 	down (&dev->sem);
637 
638 	minor = dev->minor;
639 
640 	/* remove our devfs node */
641 	devfs_unregister(dev->devfs);
642 
643 	/* if the device is not opened, then we clean up right now */
644 	if (!dev->open_count) {
645 		up (&dev->sem);
646 		skel_delete (dev);
647 	} else {
648 		dev->udev = NULL;
649 		up (&dev->sem);
650 	}
651 
652 	info("USB Skeleton #%d now disconnected", minor);
653 	up (&minor_table_mutex);
654 }
655 
656 
657 
658 /**
659  *	usb_skel_init
660  */
usb_skel_init(void)661 static int __init usb_skel_init(void)
662 {
663 	int result;
664 
665 	/* register this driver with the USB subsystem */
666 	result = usb_register(&skel_driver);
667 	if (result < 0) {
668 		err("usb_register failed for the "__FILE__" driver. Error number %d",
669 		    result);
670 		return -1;
671 	}
672 
673 	info(DRIVER_DESC " " DRIVER_VERSION);
674 	return 0;
675 }
676 
677 
678 /**
679  *	usb_skel_exit
680  */
usb_skel_exit(void)681 static void __exit usb_skel_exit(void)
682 {
683 	/* deregister this driver with the USB subsystem */
684 	usb_deregister(&skel_driver);
685 }
686 
687 
688 module_init (usb_skel_init);
689 module_exit (usb_skel_exit);
690 
691 MODULE_AUTHOR(DRIVER_AUTHOR);
692 MODULE_DESCRIPTION(DRIVER_DESC);
693 MODULE_LICENSE("GPL");
694 
695