ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / usb-skeleton.c
1 /*
2  * USB Skeleton driver - 1.1
3  *
4  * Copyright (C) 2001-2003 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, version 2.
9  *
10  *
11  * This driver is to be used as a skeleton driver to be able to create a
12  * USB driver quickly.  The design of it is based on the usb-serial and
13  * dc2xx drivers.
14  *
15  * Thanks to Oliver Neukum, David Brownell, and Alan Stern for their help
16  * in debugging this driver.
17  *
18  *
19  * History:
20  *
21  * 2003-05-06 - 1.1 - changes due to usb core changes with usb_register_dev()
22  * 2003-02-25 - 1.0 - fix races involving urb->status, unlink_urb(), and
23  *                      disconnect.  Fix transfer amount in read().  Use
24  *                      macros instead of magic numbers in probe().  Change
25  *                      size variables to size_t.  Show how to eliminate
26  *                      DMA bounce buffer.
27  * 2002_12_12 - 0.9 - compile fixes and got rid of fixed minor array.
28  * 2002_09_26 - 0.8 - changes due to USB core conversion to struct device
29  *                      driver.
30  * 2002_02_12 - 0.7 - zero out dev in probe function for devices that do
31  *                      not have both a bulk in and bulk out endpoint.
32  *                      Thanks to Holger Waechtler for the fix.
33  * 2001_11_05 - 0.6 - fix minor locking problem in skel_disconnect.
34  *                      Thanks to Pete Zaitcev for the fix.
35  * 2001_09_04 - 0.5 - fix devfs bug in skel_disconnect. Thanks to wim delvaux
36  * 2001_08_21 - 0.4 - more small bug fixes.
37  * 2001_05_29 - 0.3 - more bug fixes based on review from linux-usb-devel
38  * 2001_05_24 - 0.2 - bug fixes based on review from linux-usb-devel people
39  * 2001_05_01 - 0.1 - first version
40  *
41  */
42
43 #include <linux/config.h>
44 #include <linux/kernel.h>
45 #include <linux/errno.h>
46 #include <linux/init.h>
47 #include <linux/slab.h>
48 #include <linux/module.h>
49 #include <linux/smp_lock.h>
50 #include <linux/completion.h>
51 #include <asm/uaccess.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 "v1.0"
67 #define DRIVER_AUTHOR "Greg Kroah-Hartman, greg@kroah.com"
68 #define DRIVER_DESC "USB Skeleton Driver"
69
70 /* Module parameters */
71 MODULE_PARM(debug, "i");
72 MODULE_PARM_DESC(debug, "Debug enabled or not");
73
74
75 /* Define these values to match your devices */
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         /* "Gadget Zero" firmware runs under Linux */
83         { USB_DEVICE(0x0525, 0xa4a0) },
84         { }                                     /* Terminating entry */
85 };
86
87 MODULE_DEVICE_TABLE (usb, skel_table);
88
89
90 /* Get a minor range for your devices from the usb maintainer */
91 #define USB_SKEL_MINOR_BASE     192
92
93 /* Structure to hold all of our device specific stuff */
94 struct usb_skel {
95         struct usb_device *     udev;                   /* save off the usb device pointer */
96         struct usb_interface *  interface;              /* the interface for this device */
97         unsigned char           minor;                  /* the starting minor number for this device */
98         unsigned char           num_ports;              /* the number of ports this device has */
99         char                    num_interrupt_in;       /* number of interrupt in endpoints we have */
100         char                    num_bulk_in;            /* number of bulk in endpoints we have */
101         char                    num_bulk_out;           /* number of bulk out endpoints we have */
102
103         unsigned char *         bulk_in_buffer;         /* the buffer to receive data */
104         size_t                  bulk_in_size;           /* the size of the receive buffer */
105         __u8                    bulk_in_endpointAddr;   /* the address of the bulk in endpoint */
106
107         unsigned char *         bulk_out_buffer;        /* the buffer to send data */
108         size_t                  bulk_out_size;          /* the size of the send buffer */
109         struct urb *            write_urb;              /* the urb used to send data */
110         __u8                    bulk_out_endpointAddr;  /* the address of the bulk out endpoint */
111         atomic_t                write_busy;             /* true iff write urb is busy */
112         struct completion       write_finished;         /* wait for the write to finish */
113
114         int                     open;                   /* if the port is open or not */
115         int                     present;                /* if the device is not disconnected */
116         struct semaphore        sem;                    /* locks this structure */
117 };
118
119
120 /* prevent races between open() and disconnect() */
121 static DECLARE_MUTEX (disconnect_sem);
122
123 /* local function prototypes */
124 static ssize_t skel_read        (struct file *file, char *buffer, size_t count, loff_t *ppos);
125 static ssize_t skel_write       (struct file *file, const char *buffer, size_t count, loff_t *ppos);
126 static int skel_ioctl           (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg);
127 static int skel_open            (struct inode *inode, struct file *file);
128 static int skel_release         (struct inode *inode, struct file *file);
129
130 static int skel_probe           (struct usb_interface *interface, const struct usb_device_id *id);
131 static void skel_disconnect     (struct usb_interface *interface);
132
133 static void skel_write_bulk_callback    (struct urb *urb, struct pt_regs *regs);
134
135 /*
136  * File operations needed when we register this driver.
137  * This assumes that this driver NEEDS file operations,
138  * of course, which means that the driver is expected
139  * to have a node in the /dev directory. If the USB
140  * device were for a network interface then the driver
141  * would use "struct net_driver" instead, and a serial
142  * device would use "struct tty_driver".
143  */
144 static struct file_operations skel_fops = {
145         /*
146          * The owner field is part of the module-locking
147          * mechanism. The idea is that the kernel knows
148          * which module to increment the use-counter of
149          * BEFORE it calls the device's open() function.
150          * This also means that the kernel can decrement
151          * the use-counter again before calling release()
152          * or should the open() function fail.
153          */
154         .owner =        THIS_MODULE,
155
156         .read =         skel_read,
157         .write =        skel_write,
158         .ioctl =        skel_ioctl,
159         .open =         skel_open,
160         .release =      skel_release,
161 };
162
163 /* 
164  * usb class driver info in order to get a minor number from the usb core,
165  * and to have the device registered with devfs and the driver core
166  */
167 static struct usb_class_driver skel_class = {
168         .name =         "usb/skel%d",
169         .fops =         &skel_fops,
170         .mode =         S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH,
171         .minor_base =   USB_SKEL_MINOR_BASE,
172 };
173
174 /* usb specific object needed to register this driver with the usb subsystem */
175 static struct usb_driver skel_driver = {
176         .owner =        THIS_MODULE,
177         .name =         "skeleton",
178         .probe =        skel_probe,
179         .disconnect =   skel_disconnect,
180         .id_table =     skel_table,
181 };
182
183
184 /**
185  *      usb_skel_debug_data
186  */
187 static inline void usb_skel_debug_data (const char *function, int size, const unsigned char *data)
188 {
189         int i;
190
191         if (!debug)
192                 return;
193
194         printk (KERN_DEBUG __FILE__": %s - length = %d, data = ",
195                 function, size);
196         for (i = 0; i < size; ++i) {
197                 printk ("%.2x ", data[i]);
198         }
199         printk ("\n");
200 }
201
202
203 /**
204  *      skel_delete
205  */
206 static inline void skel_delete (struct usb_skel *dev)
207 {
208         kfree (dev->bulk_in_buffer);
209         usb_buffer_free (dev->udev, dev->bulk_out_size,
210                                 dev->bulk_out_buffer,
211                                 dev->write_urb->transfer_dma);
212         usb_free_urb (dev->write_urb);
213         kfree (dev);
214 }
215
216
217 /**
218  *      skel_open
219  */
220 static int skel_open (struct inode *inode, struct file *file)
221 {
222         struct usb_skel *dev = NULL;
223         struct usb_interface *interface;
224         int subminor;
225         int retval = 0;
226
227         dbg("%s", __FUNCTION__);
228
229         subminor = iminor(inode);
230
231         /* prevent disconnects */
232         down (&disconnect_sem);
233
234         interface = usb_find_interface (&skel_driver, subminor);
235         if (!interface) {
236                 err ("%s - error, can't find device for minor %d",
237                      __FUNCTION__, subminor);
238                 retval = -ENODEV;
239                 goto exit_no_device;
240         }
241
242         dev = usb_get_intfdata(interface);
243         if (!dev) {
244                 retval = -ENODEV;
245                 goto exit_no_device;
246         }
247
248         /* lock this device */
249         down (&dev->sem);
250
251         /* increment our usage count for the driver */
252         ++dev->open;
253
254         /* save our object in the file's private structure */
255         file->private_data = dev;
256
257         /* unlock this device */
258         up (&dev->sem);
259
260 exit_no_device:
261         up (&disconnect_sem);
262         return retval;
263 }
264
265
266 /**
267  *      skel_release
268  */
269 static int skel_release (struct inode *inode, struct file *file)
270 {
271         struct usb_skel *dev;
272         int retval = 0;
273
274         dev = (struct usb_skel *)file->private_data;
275         if (dev == NULL) {
276                 dbg ("%s - object is NULL", __FUNCTION__);
277                 return -ENODEV;
278         }
279
280         dbg("%s - minor %d", __FUNCTION__, dev->minor);
281
282         /* lock our device */
283         down (&dev->sem);
284
285         if (dev->open <= 0) {
286                 dbg ("%s - device not opened", __FUNCTION__);
287                 retval = -ENODEV;
288                 goto exit_not_opened;
289         }
290
291         /* wait for any bulk writes that might be going on to finish up */
292         if (atomic_read (&dev->write_busy))
293                 wait_for_completion (&dev->write_finished);
294
295         --dev->open;
296
297         if (!dev->present && !dev->open) {
298                 /* the device was unplugged before the file was released */
299                 up (&dev->sem);
300                 skel_delete (dev);
301                 return 0;
302         }
303
304 exit_not_opened:
305         up (&dev->sem);
306
307         return retval;
308 }
309
310
311 /**
312  *      skel_read
313  */
314 static ssize_t skel_read (struct file *file, char *buffer, size_t count, loff_t *ppos)
315 {
316         struct usb_skel *dev;
317         int retval = 0;
318
319         dev = (struct usb_skel *)file->private_data;
320
321         dbg("%s - minor %d, count = %d", __FUNCTION__, dev->minor, count);
322
323         /* lock this object */
324         down (&dev->sem);
325
326         /* verify that the device wasn't unplugged */
327         if (!dev->present) {
328                 up (&dev->sem);
329                 return -ENODEV;
330         }
331
332         /* do a blocking bulk read to get data from the device */
333         retval = usb_bulk_msg (dev->udev,
334                                usb_rcvbulkpipe (dev->udev,
335                                                 dev->bulk_in_endpointAddr),
336                                dev->bulk_in_buffer,
337                                min (dev->bulk_in_size, count),
338                                &count, HZ*10);
339
340         /* if the read was successful, copy the data to userspace */
341         if (!retval) {
342                 if (copy_to_user (buffer, dev->bulk_in_buffer, count))
343                         retval = -EFAULT;
344                 else
345                         retval = count;
346         }
347
348         /* unlock the device */
349         up (&dev->sem);
350         return retval;
351 }
352
353
354 /**
355  *      skel_write
356  *
357  *      A device driver has to decide how to report I/O errors back to the
358  *      user.  The safest course is to wait for the transfer to finish before
359  *      returning so that any errors will be reported reliably.  skel_read()
360  *      works like this.  But waiting for I/O is slow, so many drivers only
361  *      check for errors during I/O initiation and do not report problems
362  *      that occur during the actual transfer.  That's what we will do here.
363  *
364  *      A driver concerned with maximum I/O throughput would use double-
365  *      buffering:  Two urbs would be devoted to write transfers, so that
366  *      one urb could always be active while the other was waiting for the
367  *      user to send more data.
368  */
369 static ssize_t skel_write (struct file *file, const char *buffer, size_t count, loff_t *ppos)
370 {
371         struct usb_skel *dev;
372         ssize_t bytes_written = 0;
373         int retval = 0;
374
375         dev = (struct usb_skel *)file->private_data;
376
377         dbg("%s - minor %d, count = %d", __FUNCTION__, dev->minor, count);
378
379         /* lock this object */
380         down (&dev->sem);
381
382         /* verify that the device wasn't unplugged */
383         if (!dev->present) {
384                 retval = -ENODEV;
385                 goto exit;
386         }
387
388         /* verify that we actually have some data to write */
389         if (count == 0) {
390                 dbg("%s - write request of 0 bytes", __FUNCTION__);
391                 goto exit;
392         }
393
394         /* wait for a previous write to finish up; we don't use a timeout
395          * and so a nonresponsive device can delay us indefinitely.
396          */
397         if (atomic_read (&dev->write_busy))
398                 wait_for_completion (&dev->write_finished);
399
400         /* we can only write as much as our buffer will hold */
401         bytes_written = min (dev->bulk_out_size, count);
402
403         /* copy the data from userspace into our transfer buffer;
404          * this is the only copy required.
405          */
406         if (copy_from_user(dev->write_urb->transfer_buffer, buffer,
407                            bytes_written)) {
408                 retval = -EFAULT;
409                 goto exit;
410         }
411
412         usb_skel_debug_data (__FUNCTION__, bytes_written,
413                              dev->write_urb->transfer_buffer);
414
415         /* this urb was already set up, except for this write size */
416         dev->write_urb->transfer_buffer_length = bytes_written;
417
418         /* send the data out the bulk port */
419         /* a character device write uses GFP_KERNEL,
420          unless a spinlock is held */
421         init_completion (&dev->write_finished);
422         atomic_set (&dev->write_busy, 1);
423         retval = usb_submit_urb(dev->write_urb, GFP_KERNEL);
424         if (retval) {
425                 atomic_set (&dev->write_busy, 0);
426                 err("%s - failed submitting write urb, error %d",
427                     __FUNCTION__, retval);
428         } else {
429                 retval = bytes_written;
430         }
431
432 exit:
433         /* unlock the device */
434         up (&dev->sem);
435
436         return retval;
437 }
438
439
440 /**
441  *      skel_ioctl
442  */
443 static int skel_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
444 {
445         struct usb_skel *dev;
446
447         dev = (struct usb_skel *)file->private_data;
448
449         /* lock this object */
450         down (&dev->sem);
451
452         /* verify that the device wasn't unplugged */
453         if (!dev->present) {
454                 up (&dev->sem);
455                 return -ENODEV;
456         }
457
458         dbg("%s - minor %d, cmd 0x%.4x, arg %ld", __FUNCTION__,
459             dev->minor, cmd, arg);
460
461         /* fill in your device specific stuff here */
462
463         /* unlock the device */
464         up (&dev->sem);
465
466         /* return that we did not understand this ioctl call */
467         return -ENOTTY;
468 }
469
470
471 /**
472  *      skel_write_bulk_callback
473  */
474 static void skel_write_bulk_callback (struct urb *urb, struct pt_regs *regs)
475 {
476         struct usb_skel *dev = (struct usb_skel *)urb->context;
477
478         dbg("%s - minor %d", __FUNCTION__, dev->minor);
479
480         /* sync/async unlink faults aren't errors */
481         if (urb->status && !(urb->status == -ENOENT ||
482                                 urb->status == -ECONNRESET)) {
483                 dbg("%s - nonzero write bulk status received: %d",
484                     __FUNCTION__, urb->status);
485         }
486
487         /* notify anyone waiting that the write has finished */
488         atomic_set (&dev->write_busy, 0);
489         complete (&dev->write_finished);
490 }
491
492
493 /**
494  *      skel_probe
495  *
496  *      Called by the usb core when a new device is connected that it thinks
497  *      this driver might be interested in.
498  */
499 static int skel_probe(struct usb_interface *interface, const struct usb_device_id *id)
500 {
501         struct usb_device *udev = interface_to_usbdev(interface);
502         struct usb_skel *dev = NULL;
503         struct usb_host_interface *iface_desc;
504         struct usb_endpoint_descriptor *endpoint;
505         size_t buffer_size;
506         int i;
507         int retval = -ENOMEM;
508
509         /* See if the device offered us matches what we can accept */
510         if ((udev->descriptor.idVendor != USB_SKEL_VENDOR_ID) ||
511             (udev->descriptor.idProduct != USB_SKEL_PRODUCT_ID)) {
512                 return -ENODEV;
513         }
514
515         /* allocate memory for our device state and initialize it */
516         dev = kmalloc (sizeof(struct usb_skel), GFP_KERNEL);
517         if (dev == NULL) {
518                 err ("Out of memory");
519                 return -ENOMEM;
520         }
521         memset (dev, 0x00, sizeof (*dev));
522
523         init_MUTEX (&dev->sem);
524         dev->udev = udev;
525         dev->interface = interface;
526
527         /* set up the endpoint information */
528         /* check out the endpoints */
529         /* use only the first bulk-in and bulk-out endpoints */
530         iface_desc = &interface->altsetting[0];
531         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
532                 endpoint = &iface_desc->endpoint[i].desc;
533
534                 if (!dev->bulk_in_endpointAddr &&
535                     (endpoint->bEndpointAddress & USB_DIR_IN) &&
536                     ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
537                                         == USB_ENDPOINT_XFER_BULK)) {
538                         /* we found a bulk in endpoint */
539                         buffer_size = endpoint->wMaxPacketSize;
540                         dev->bulk_in_size = buffer_size;
541                         dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
542                         dev->bulk_in_buffer = kmalloc (buffer_size, GFP_KERNEL);
543                         if (!dev->bulk_in_buffer) {
544                                 err("Couldn't allocate bulk_in_buffer");
545                                 goto error;
546                         }
547                 }
548
549                 if (!dev->bulk_out_endpointAddr &&
550                     !(endpoint->bEndpointAddress & USB_DIR_IN) &&
551                     ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
552                                         == USB_ENDPOINT_XFER_BULK)) {
553                         /* we found a bulk out endpoint */
554                         /* a probe() may sleep and has no restrictions on memory allocations */
555                         dev->write_urb = usb_alloc_urb(0, GFP_KERNEL);
556                         if (!dev->write_urb) {
557                                 err("No free urbs available");
558                                 goto error;
559                         }
560                         dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
561
562                         /* on some platforms using this kind of buffer alloc
563                          * call eliminates a dma "bounce buffer".
564                          *
565                          * NOTE: you'd normally want i/o buffers that hold
566                          * more than one packet, so that i/o delays between
567                          * packets don't hurt throughput.
568                          */
569                         buffer_size = endpoint->wMaxPacketSize;
570                         dev->bulk_out_size = buffer_size;
571                         dev->write_urb->transfer_flags = (URB_NO_TRANSFER_DMA_MAP |
572                                         URB_ASYNC_UNLINK);
573                         dev->bulk_out_buffer = usb_buffer_alloc (udev,
574                                         buffer_size, GFP_KERNEL,
575                                         &dev->write_urb->transfer_dma);
576                         if (!dev->bulk_out_buffer) {
577                                 err("Couldn't allocate bulk_out_buffer");
578                                 goto error;
579                         }
580                         usb_fill_bulk_urb(dev->write_urb, udev,
581                                       usb_sndbulkpipe(udev,
582                                                       endpoint->bEndpointAddress),
583                                       dev->bulk_out_buffer, buffer_size,
584                                       skel_write_bulk_callback, dev);
585                 }
586         }
587         if (!(dev->bulk_in_endpointAddr && dev->bulk_out_endpointAddr)) {
588                 err("Couldn't find both bulk-in and bulk-out endpoints");
589                 goto error;
590         }
591
592         /* allow device read, write and ioctl */
593         dev->present = 1;
594
595         /* we can register the device now, as it is ready */
596         usb_set_intfdata (interface, dev);
597         retval = usb_register_dev (interface, &skel_class);
598         if (retval) {
599                 /* something prevented us from registering this driver */
600                 err ("Not able to get a minor for this device.");
601                 usb_set_intfdata (interface, NULL);
602                 goto error;
603         }
604
605         dev->minor = interface->minor;
606
607         /* let the user know what node this device is now attached to */
608         info ("USB Skeleton device now attached to USBSkel-%d", dev->minor);
609         return 0;
610
611 error:
612         skel_delete (dev);
613         return retval;
614 }
615
616
617 /**
618  *      skel_disconnect
619  *
620  *      Called by the usb core when the device is removed from the system.
621  *
622  *      This routine guarantees that the driver will not submit any more urbs
623  *      by clearing dev->udev.  It is also supposed to terminate any currently
624  *      active urbs.  Unfortunately, usb_bulk_msg(), used in skel_read(), does
625  *      not provide any way to do this.  But at least we can cancel an active
626  *      write.
627  */
628 static void skel_disconnect(struct usb_interface *interface)
629 {
630         struct usb_skel *dev;
631         int minor;
632
633         /* prevent races with open() */
634         down (&disconnect_sem);
635
636         dev = usb_get_intfdata (interface);
637         usb_set_intfdata (interface, NULL);
638
639         down (&dev->sem);
640
641         minor = dev->minor;
642
643         /* give back our minor */
644         usb_deregister_dev (interface, &skel_class);
645
646         /* terminate an ongoing write */
647         if (atomic_read (&dev->write_busy)) {
648                 usb_unlink_urb (dev->write_urb);
649                 wait_for_completion (&dev->write_finished);
650         }
651
652         /* prevent device read, write and ioctl */
653         dev->present = 0;
654
655         up (&dev->sem);
656
657         /* if the device is opened, skel_release will clean this up */
658         if (!dev->open)
659                 skel_delete (dev);
660
661         up (&disconnect_sem);
662
663         info("USB Skeleton #%d now disconnected", minor);
664 }
665
666
667
668 /**
669  *      usb_skel_init
670  */
671 static int __init usb_skel_init(void)
672 {
673         int result;
674
675         /* register this driver with the USB subsystem */
676         result = usb_register(&skel_driver);
677         if (result) {
678                 err("usb_register failed. Error number %d",
679                     result);
680                 return result;
681         }
682
683         info(DRIVER_DESC " " DRIVER_VERSION);
684         return 0;
685 }
686
687
688 /**
689  *      usb_skel_exit
690  */
691 static void __exit usb_skel_exit(void)
692 {
693         /* deregister this driver with the USB subsystem */
694         usb_deregister(&skel_driver);
695 }
696
697
698 module_init (usb_skel_init);
699 module_exit (usb_skel_exit);
700
701 MODULE_AUTHOR(DRIVER_AUTHOR);
702 MODULE_DESCRIPTION(DRIVER_DESC);
703 MODULE_LICENSE("GPL");