USB: Push BKL on open down into the drivers
[profile/ivi/kernel-x86-ivi.git] / drivers / usb / usb-skeleton.c
1 /*
2  * USB Skeleton driver - 2.2
3  *
4  * Copyright (C) 2001-2004 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  * This driver is based on the 2.6.3 version of drivers/usb/usb-skeleton.c
11  * but has been rewritten to be easier to read and use.
12  *
13  */
14
15 #include <linux/kernel.h>
16 #include <linux/errno.h>
17 #include <linux/init.h>
18 #include <linux/slab.h>
19 #include <linux/module.h>
20 #include <linux/kref.h>
21 #include <linux/smp_lock.h>
22 #include <linux/uaccess.h>
23 #include <linux/usb.h>
24 #include <linux/mutex.h>
25
26
27 /* Define these values to match your devices */
28 #define USB_SKEL_VENDOR_ID      0xfff0
29 #define USB_SKEL_PRODUCT_ID     0xfff0
30
31 /* table of devices that work with this driver */
32 static const struct usb_device_id skel_table[] = {
33         { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
34         { }                                     /* Terminating entry */
35 };
36 MODULE_DEVICE_TABLE(usb, skel_table);
37
38
39 /* Get a minor range for your devices from the usb maintainer */
40 #define USB_SKEL_MINOR_BASE     192
41
42 /* our private defines. if this grows any larger, use your own .h file */
43 #define MAX_TRANSFER            (PAGE_SIZE - 512)
44 /* MAX_TRANSFER is chosen so that the VM is not stressed by
45    allocations > PAGE_SIZE and the number of packets in a page
46    is an integer 512 is the largest possible packet on EHCI */
47 #define WRITES_IN_FLIGHT        8
48 /* arbitrarily chosen */
49
50 /* Structure to hold all of our device specific stuff */
51 struct usb_skel {
52         struct usb_device       *udev;                  /* the usb device for this device */
53         struct usb_interface    *interface;             /* the interface for this device */
54         struct semaphore        limit_sem;              /* limiting the number of writes in progress */
55         struct usb_anchor       submitted;              /* in case we need to retract our submissions */
56         struct urb              *bulk_in_urb;           /* the urb to read data with */
57         unsigned char           *bulk_in_buffer;        /* the buffer to receive data */
58         size_t                  bulk_in_size;           /* the size of the receive buffer */
59         size_t                  bulk_in_filled;         /* number of bytes in the buffer */
60         size_t                  bulk_in_copied;         /* already copied to user space */
61         __u8                    bulk_in_endpointAddr;   /* the address of the bulk in endpoint */
62         __u8                    bulk_out_endpointAddr;  /* the address of the bulk out endpoint */
63         int                     errors;                 /* the last request tanked */
64         int                     open_count;             /* count the number of openers */
65         bool                    ongoing_read;           /* a read is going on */
66         bool                    processed_urb;          /* indicates we haven't processed the urb */
67         spinlock_t              err_lock;               /* lock for errors */
68         struct kref             kref;
69         struct mutex            io_mutex;               /* synchronize I/O with disconnect */
70         struct completion       bulk_in_completion;     /* to wait for an ongoing read */
71 };
72 #define to_skel_dev(d) container_of(d, struct usb_skel, kref)
73
74 static struct usb_driver skel_driver;
75 static void skel_draw_down(struct usb_skel *dev);
76
77 static void skel_delete(struct kref *kref)
78 {
79         struct usb_skel *dev = to_skel_dev(kref);
80
81         usb_free_urb(dev->bulk_in_urb);
82         usb_put_dev(dev->udev);
83         kfree(dev->bulk_in_buffer);
84         kfree(dev);
85 }
86
87 static int skel_open(struct inode *inode, struct file *file)
88 {
89         struct usb_skel *dev;
90         struct usb_interface *interface;
91         int subminor;
92         int retval = 0;
93
94         lock_kernel();
95         subminor = iminor(inode);
96
97         interface = usb_find_interface(&skel_driver, subminor);
98         if (!interface) {
99                 err("%s - error, can't find device for minor %d",
100                      __func__, subminor);
101                 retval = -ENODEV;
102                 goto exit;
103         }
104
105         dev = usb_get_intfdata(interface);
106         if (!dev) {
107                 retval = -ENODEV;
108                 goto exit;
109         }
110
111         /* increment our usage count for the device */
112         kref_get(&dev->kref);
113
114         /* lock the device to allow correctly handling errors
115          * in resumption */
116         mutex_lock(&dev->io_mutex);
117
118         if (!dev->open_count++) {
119                 retval = usb_autopm_get_interface(interface);
120                         if (retval) {
121                                 dev->open_count--;
122                                 mutex_unlock(&dev->io_mutex);
123                                 kref_put(&dev->kref, skel_delete);
124                                 goto exit;
125                         }
126         } /* else { //uncomment this block if you want exclusive open
127                 retval = -EBUSY;
128                 dev->open_count--;
129                 mutex_unlock(&dev->io_mutex);
130                 kref_put(&dev->kref, skel_delete);
131                 goto exit;
132         } */
133         /* prevent the device from being autosuspended */
134
135         /* save our object in the file's private structure */
136         file->private_data = dev;
137         mutex_unlock(&dev->io_mutex);
138
139 exit:
140         unlock_kernel();
141         return retval;
142 }
143
144 static int skel_release(struct inode *inode, struct file *file)
145 {
146         struct usb_skel *dev;
147
148         dev = (struct usb_skel *)file->private_data;
149         if (dev == NULL)
150                 return -ENODEV;
151
152         /* allow the device to be autosuspended */
153         mutex_lock(&dev->io_mutex);
154         if (!--dev->open_count && dev->interface)
155                 usb_autopm_put_interface(dev->interface);
156         mutex_unlock(&dev->io_mutex);
157
158         /* decrement the count on our device */
159         kref_put(&dev->kref, skel_delete);
160         return 0;
161 }
162
163 static int skel_flush(struct file *file, fl_owner_t id)
164 {
165         struct usb_skel *dev;
166         int res;
167
168         dev = (struct usb_skel *)file->private_data;
169         if (dev == NULL)
170                 return -ENODEV;
171
172         /* wait for io to stop */
173         mutex_lock(&dev->io_mutex);
174         skel_draw_down(dev);
175
176         /* read out errors, leave subsequent opens a clean slate */
177         spin_lock_irq(&dev->err_lock);
178         res = dev->errors ? (dev->errors == -EPIPE ? -EPIPE : -EIO) : 0;
179         dev->errors = 0;
180         spin_unlock_irq(&dev->err_lock);
181
182         mutex_unlock(&dev->io_mutex);
183
184         return res;
185 }
186
187 static void skel_read_bulk_callback(struct urb *urb)
188 {
189         struct usb_skel *dev;
190
191         dev = urb->context;
192
193         spin_lock(&dev->err_lock);
194         /* sync/async unlink faults aren't errors */
195         if (urb->status) {
196                 if (!(urb->status == -ENOENT ||
197                     urb->status == -ECONNRESET ||
198                     urb->status == -ESHUTDOWN))
199                         err("%s - nonzero write bulk status received: %d",
200                             __func__, urb->status);
201
202                 dev->errors = urb->status;
203         } else {
204                 dev->bulk_in_filled = urb->actual_length;
205         }
206         dev->ongoing_read = 0;
207         spin_unlock(&dev->err_lock);
208
209         complete(&dev->bulk_in_completion);
210 }
211
212 static int skel_do_read_io(struct usb_skel *dev, size_t count)
213 {
214         int rv;
215
216         /* prepare a read */
217         usb_fill_bulk_urb(dev->bulk_in_urb,
218                         dev->udev,
219                         usb_rcvbulkpipe(dev->udev,
220                                 dev->bulk_in_endpointAddr),
221                         dev->bulk_in_buffer,
222                         min(dev->bulk_in_size, count),
223                         skel_read_bulk_callback,
224                         dev);
225         /* tell everybody to leave the URB alone */
226         spin_lock_irq(&dev->err_lock);
227         dev->ongoing_read = 1;
228         spin_unlock_irq(&dev->err_lock);
229
230         /* do it */
231         rv = usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL);
232         if (rv < 0) {
233                 err("%s - failed submitting read urb, error %d",
234                         __func__, rv);
235                 dev->bulk_in_filled = 0;
236                 rv = (rv == -ENOMEM) ? rv : -EIO;
237                 spin_lock_irq(&dev->err_lock);
238                 dev->ongoing_read = 0;
239                 spin_unlock_irq(&dev->err_lock);
240         }
241
242         return rv;
243 }
244
245 static ssize_t skel_read(struct file *file, char *buffer, size_t count,
246                          loff_t *ppos)
247 {
248         struct usb_skel *dev;
249         int rv;
250         bool ongoing_io;
251
252         dev = (struct usb_skel *)file->private_data;
253
254         /* if we cannot read at all, return EOF */
255         if (!dev->bulk_in_urb || !count)
256                 return 0;
257
258         /* no concurrent readers */
259         rv = mutex_lock_interruptible(&dev->io_mutex);
260         if (rv < 0)
261                 return rv;
262
263         if (!dev->interface) {          /* disconnect() was called */
264                 rv = -ENODEV;
265                 goto exit;
266         }
267
268         /* if IO is under way, we must not touch things */
269 retry:
270         spin_lock_irq(&dev->err_lock);
271         ongoing_io = dev->ongoing_read;
272         spin_unlock_irq(&dev->err_lock);
273
274         if (ongoing_io) {
275                 /* nonblocking IO shall not wait */
276                 if (file->f_flags & O_NONBLOCK) {
277                         rv = -EAGAIN;
278                         goto exit;
279                 }
280                 /*
281                  * IO may take forever
282                  * hence wait in an interruptible state
283                  */
284                 rv = wait_for_completion_interruptible(&dev->bulk_in_completion);
285                 if (rv < 0)
286                         goto exit;
287                 /*
288                  * by waiting we also semiprocessed the urb
289                  * we must finish now
290                  */
291                 dev->bulk_in_copied = 0;
292                 dev->processed_urb = 1;
293         }
294
295         if (!dev->processed_urb) {
296                 /*
297                  * the URB hasn't been processed
298                  * do it now
299                  */
300                 wait_for_completion(&dev->bulk_in_completion);
301                 dev->bulk_in_copied = 0;
302                 dev->processed_urb = 1;
303         }
304
305         /* errors must be reported */
306         rv = dev->errors;
307         if (rv < 0) {
308                 /* any error is reported once */
309                 dev->errors = 0;
310                 /* to preserve notifications about reset */
311                 rv = (rv == -EPIPE) ? rv : -EIO;
312                 /* no data to deliver */
313                 dev->bulk_in_filled = 0;
314                 /* report it */
315                 goto exit;
316         }
317
318         /*
319          * if the buffer is filled we may satisfy the read
320          * else we need to start IO
321          */
322
323         if (dev->bulk_in_filled) {
324                 /* we had read data */
325                 size_t available = dev->bulk_in_filled - dev->bulk_in_copied;
326                 size_t chunk = min(available, count);
327
328                 if (!available) {
329                         /*
330                          * all data has been used
331                          * actual IO needs to be done
332                          */
333                         rv = skel_do_read_io(dev, count);
334                         if (rv < 0)
335                                 goto exit;
336                         else
337                                 goto retry;
338                 }
339                 /*
340                  * data is available
341                  * chunk tells us how much shall be copied
342                  */
343
344                 if (copy_to_user(buffer,
345                                  dev->bulk_in_buffer + dev->bulk_in_copied,
346                                  chunk))
347                         rv = -EFAULT;
348                 else
349                         rv = chunk;
350
351                 dev->bulk_in_copied += chunk;
352
353                 /*
354                  * if we are asked for more than we have,
355                  * we start IO but don't wait
356                  */
357                 if (available < count)
358                         skel_do_read_io(dev, count - chunk);
359         } else {
360                 /* no data in the buffer */
361                 rv = skel_do_read_io(dev, count);
362                 if (rv < 0)
363                         goto exit;
364                 else if (!(file->f_flags & O_NONBLOCK))
365                         goto retry;
366                 rv = -EAGAIN;
367         }
368 exit:
369         mutex_unlock(&dev->io_mutex);
370         return rv;
371 }
372
373 static void skel_write_bulk_callback(struct urb *urb)
374 {
375         struct usb_skel *dev;
376
377         dev = urb->context;
378
379         /* sync/async unlink faults aren't errors */
380         if (urb->status) {
381                 if (!(urb->status == -ENOENT ||
382                     urb->status == -ECONNRESET ||
383                     urb->status == -ESHUTDOWN))
384                         err("%s - nonzero write bulk status received: %d",
385                             __func__, urb->status);
386
387                 spin_lock(&dev->err_lock);
388                 dev->errors = urb->status;
389                 spin_unlock(&dev->err_lock);
390         }
391
392         /* free up our allocated buffer */
393         usb_buffer_free(urb->dev, urb->transfer_buffer_length,
394                         urb->transfer_buffer, urb->transfer_dma);
395         up(&dev->limit_sem);
396 }
397
398 static ssize_t skel_write(struct file *file, const char *user_buffer,
399                           size_t count, loff_t *ppos)
400 {
401         struct usb_skel *dev;
402         int retval = 0;
403         struct urb *urb = NULL;
404         char *buf = NULL;
405         size_t writesize = min(count, (size_t)MAX_TRANSFER);
406
407         dev = (struct usb_skel *)file->private_data;
408
409         /* verify that we actually have some data to write */
410         if (count == 0)
411                 goto exit;
412
413         /*
414          * limit the number of URBs in flight to stop a user from using up all
415          * RAM
416          */
417         if (!(file->f_flags & O_NONBLOCK)) {
418                 if (down_interruptible(&dev->limit_sem)) {
419                         retval = -ERESTARTSYS;
420                         goto exit;
421                 }
422         } else {
423                 if (down_trylock(&dev->limit_sem)) {
424                         retval = -EAGAIN;
425                         goto exit;
426                 }
427         }
428
429         spin_lock_irq(&dev->err_lock);
430         retval = dev->errors;
431         if (retval < 0) {
432                 /* any error is reported once */
433                 dev->errors = 0;
434                 /* to preserve notifications about reset */
435                 retval = (retval == -EPIPE) ? retval : -EIO;
436         }
437         spin_unlock_irq(&dev->err_lock);
438         if (retval < 0)
439                 goto error;
440
441         /* create a urb, and a buffer for it, and copy the data to the urb */
442         urb = usb_alloc_urb(0, GFP_KERNEL);
443         if (!urb) {
444                 retval = -ENOMEM;
445                 goto error;
446         }
447
448         buf = usb_buffer_alloc(dev->udev, writesize, GFP_KERNEL,
449                                &urb->transfer_dma);
450         if (!buf) {
451                 retval = -ENOMEM;
452                 goto error;
453         }
454
455         if (copy_from_user(buf, user_buffer, writesize)) {
456                 retval = -EFAULT;
457                 goto error;
458         }
459
460         /* this lock makes sure we don't submit URBs to gone devices */
461         mutex_lock(&dev->io_mutex);
462         if (!dev->interface) {          /* disconnect() was called */
463                 mutex_unlock(&dev->io_mutex);
464                 retval = -ENODEV;
465                 goto error;
466         }
467
468         /* initialize the urb properly */
469         usb_fill_bulk_urb(urb, dev->udev,
470                           usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
471                           buf, writesize, skel_write_bulk_callback, dev);
472         urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
473         usb_anchor_urb(urb, &dev->submitted);
474
475         /* send the data out the bulk port */
476         retval = usb_submit_urb(urb, GFP_KERNEL);
477         mutex_unlock(&dev->io_mutex);
478         if (retval) {
479                 err("%s - failed submitting write urb, error %d", __func__,
480                     retval);
481                 goto error_unanchor;
482         }
483
484         /*
485          * release our reference to this urb, the USB core will eventually free
486          * it entirely
487          */
488         usb_free_urb(urb);
489
490
491         return writesize;
492
493 error_unanchor:
494         usb_unanchor_urb(urb);
495 error:
496         if (urb) {
497                 usb_buffer_free(dev->udev, writesize, buf, urb->transfer_dma);
498                 usb_free_urb(urb);
499         }
500         up(&dev->limit_sem);
501
502 exit:
503         return retval;
504 }
505
506 static const struct file_operations skel_fops = {
507         .owner =        THIS_MODULE,
508         .read =         skel_read,
509         .write =        skel_write,
510         .open =         skel_open,
511         .release =      skel_release,
512         .flush =        skel_flush,
513 };
514
515 /*
516  * usb class driver info in order to get a minor number from the usb core,
517  * and to have the device registered with the driver core
518  */
519 static struct usb_class_driver skel_class = {
520         .name =         "skel%d",
521         .fops =         &skel_fops,
522         .minor_base =   USB_SKEL_MINOR_BASE,
523 };
524
525 static int skel_probe(struct usb_interface *interface,
526                       const struct usb_device_id *id)
527 {
528         struct usb_skel *dev;
529         struct usb_host_interface *iface_desc;
530         struct usb_endpoint_descriptor *endpoint;
531         size_t buffer_size;
532         int i;
533         int retval = -ENOMEM;
534
535         /* allocate memory for our device state and initialize it */
536         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
537         if (!dev) {
538                 err("Out of memory");
539                 goto error;
540         }
541         kref_init(&dev->kref);
542         sema_init(&dev->limit_sem, WRITES_IN_FLIGHT);
543         mutex_init(&dev->io_mutex);
544         spin_lock_init(&dev->err_lock);
545         init_usb_anchor(&dev->submitted);
546         init_completion(&dev->bulk_in_completion);
547
548         dev->udev = usb_get_dev(interface_to_usbdev(interface));
549         dev->interface = interface;
550
551         /* set up the endpoint information */
552         /* use only the first bulk-in and bulk-out endpoints */
553         iface_desc = interface->cur_altsetting;
554         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
555                 endpoint = &iface_desc->endpoint[i].desc;
556
557                 if (!dev->bulk_in_endpointAddr &&
558                     usb_endpoint_is_bulk_in(endpoint)) {
559                         /* we found a bulk in endpoint */
560                         buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
561                         dev->bulk_in_size = buffer_size;
562                         dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
563                         dev->bulk_in_buffer = kmalloc(buffer_size, GFP_KERNEL);
564                         if (!dev->bulk_in_buffer) {
565                                 err("Could not allocate bulk_in_buffer");
566                                 goto error;
567                         }
568                         dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL);
569                         if (!dev->bulk_in_urb) {
570                                 err("Could not allocate bulk_in_urb");
571                                 goto error;
572                         }
573                 }
574
575                 if (!dev->bulk_out_endpointAddr &&
576                     usb_endpoint_is_bulk_out(endpoint)) {
577                         /* we found a bulk out endpoint */
578                         dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
579                 }
580         }
581         if (!(dev->bulk_in_endpointAddr && dev->bulk_out_endpointAddr)) {
582                 err("Could not find both bulk-in and bulk-out endpoints");
583                 goto error;
584         }
585
586         /* save our data pointer in this interface device */
587         usb_set_intfdata(interface, dev);
588
589         /* we can register the device now, as it is ready */
590         retval = usb_register_dev(interface, &skel_class);
591         if (retval) {
592                 /* something prevented us from registering this driver */
593                 err("Not able to get a minor for this device.");
594                 usb_set_intfdata(interface, NULL);
595                 goto error;
596         }
597
598         /* let the user know what node this device is now attached to */
599         dev_info(&interface->dev,
600                  "USB Skeleton device now attached to USBSkel-%d",
601                  interface->minor);
602         return 0;
603
604 error:
605         if (dev)
606                 /* this frees allocated memory */
607                 kref_put(&dev->kref, skel_delete);
608         return retval;
609 }
610
611 static void skel_disconnect(struct usb_interface *interface)
612 {
613         struct usb_skel *dev;
614         int minor = interface->minor;
615
616         dev = usb_get_intfdata(interface);
617         usb_set_intfdata(interface, NULL);
618
619         /* give back our minor */
620         usb_deregister_dev(interface, &skel_class);
621
622         /* prevent more I/O from starting */
623         mutex_lock(&dev->io_mutex);
624         dev->interface = NULL;
625         mutex_unlock(&dev->io_mutex);
626
627         usb_kill_anchored_urbs(&dev->submitted);
628
629         /* decrement our usage count */
630         kref_put(&dev->kref, skel_delete);
631
632         dev_info(&interface->dev, "USB Skeleton #%d now disconnected", minor);
633 }
634
635 static void skel_draw_down(struct usb_skel *dev)
636 {
637         int time;
638
639         time = usb_wait_anchor_empty_timeout(&dev->submitted, 1000);
640         if (!time)
641                 usb_kill_anchored_urbs(&dev->submitted);
642         usb_kill_urb(dev->bulk_in_urb);
643 }
644
645 static int skel_suspend(struct usb_interface *intf, pm_message_t message)
646 {
647         struct usb_skel *dev = usb_get_intfdata(intf);
648
649         if (!dev)
650                 return 0;
651         skel_draw_down(dev);
652         return 0;
653 }
654
655 static int skel_resume(struct usb_interface *intf)
656 {
657         return 0;
658 }
659
660 static int skel_pre_reset(struct usb_interface *intf)
661 {
662         struct usb_skel *dev = usb_get_intfdata(intf);
663
664         mutex_lock(&dev->io_mutex);
665         skel_draw_down(dev);
666
667         return 0;
668 }
669
670 static int skel_post_reset(struct usb_interface *intf)
671 {
672         struct usb_skel *dev = usb_get_intfdata(intf);
673
674         /* we are sure no URBs are active - no locking needed */
675         dev->errors = -EPIPE;
676         mutex_unlock(&dev->io_mutex);
677
678         return 0;
679 }
680
681 static struct usb_driver skel_driver = {
682         .name =         "skeleton",
683         .probe =        skel_probe,
684         .disconnect =   skel_disconnect,
685         .suspend =      skel_suspend,
686         .resume =       skel_resume,
687         .pre_reset =    skel_pre_reset,
688         .post_reset =   skel_post_reset,
689         .id_table =     skel_table,
690         .supports_autosuspend = 1,
691 };
692
693 static int __init usb_skel_init(void)
694 {
695         int result;
696
697         /* register this driver with the USB subsystem */
698         result = usb_register(&skel_driver);
699         if (result)
700                 err("usb_register failed. Error number %d", result);
701
702         return result;
703 }
704
705 static void __exit usb_skel_exit(void)
706 {
707         /* deregister this driver with the USB subsystem */
708         usb_deregister(&skel_driver);
709 }
710
711 module_init(usb_skel_init);
712 module_exit(usb_skel_exit);
713
714 MODULE_LICENSE("GPL");