Merge branch 'timers-core-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[cascardo/linux.git] / drivers / usb / gadget / printer.c
1 /*
2  * printer.c -- Printer gadget driver
3  *
4  * Copyright (C) 2003-2005 David Brownell
5  * Copyright (C) 2006 Craig W. Nadler
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  */
12
13 #include <linux/module.h>
14 #include <linux/kernel.h>
15 #include <linux/delay.h>
16 #include <linux/ioport.h>
17 #include <linux/sched.h>
18 #include <linux/slab.h>
19 #include <linux/mutex.h>
20 #include <linux/errno.h>
21 #include <linux/init.h>
22 #include <linux/timer.h>
23 #include <linux/list.h>
24 #include <linux/interrupt.h>
25 #include <linux/utsname.h>
26 #include <linux/device.h>
27 #include <linux/moduleparam.h>
28 #include <linux/fs.h>
29 #include <linux/poll.h>
30 #include <linux/types.h>
31 #include <linux/ctype.h>
32 #include <linux/cdev.h>
33
34 #include <asm/byteorder.h>
35 #include <linux/io.h>
36 #include <linux/irq.h>
37 #include <linux/uaccess.h>
38 #include <asm/unaligned.h>
39
40 #include <linux/usb/ch9.h>
41 #include <linux/usb/gadget.h>
42 #include <linux/usb/g_printer.h>
43
44 #include "gadget_chips.h"
45
46
47 /*
48  * Kbuild is not very cooperative with respect to linking separately
49  * compiled library objects into one module.  So for now we won't use
50  * separate compilation ... ensuring init/exit sections work to shrink
51  * the runtime footprint, and giving us at least some parts of what
52  * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
53  */
54 #include "usbstring.c"
55 #include "config.c"
56 #include "epautoconf.c"
57
58 /*-------------------------------------------------------------------------*/
59
60 #define DRIVER_DESC             "Printer Gadget"
61 #define DRIVER_VERSION          "2007 OCT 06"
62
63 static DEFINE_MUTEX(printer_mutex);
64 static const char shortname [] = "printer";
65 static const char driver_desc [] = DRIVER_DESC;
66
67 static dev_t g_printer_devno;
68
69 static struct class *usb_gadget_class;
70
71 /*-------------------------------------------------------------------------*/
72
73 struct printer_dev {
74         spinlock_t              lock;           /* lock this structure */
75         /* lock buffer lists during read/write calls */
76         struct mutex            lock_printer_io;
77         struct usb_gadget       *gadget;
78         struct usb_request      *req;           /* for control responses */
79         u8                      config;
80         s8                      interface;
81         struct usb_ep           *in_ep, *out_ep;
82
83         struct list_head        rx_reqs;        /* List of free RX structs */
84         struct list_head        rx_reqs_active; /* List of Active RX xfers */
85         struct list_head        rx_buffers;     /* List of completed xfers */
86         /* wait until there is data to be read. */
87         wait_queue_head_t       rx_wait;
88         struct list_head        tx_reqs;        /* List of free TX structs */
89         struct list_head        tx_reqs_active; /* List of Active TX xfers */
90         /* Wait until there are write buffers available to use. */
91         wait_queue_head_t       tx_wait;
92         /* Wait until all write buffers have been sent. */
93         wait_queue_head_t       tx_flush_wait;
94         struct usb_request      *current_rx_req;
95         size_t                  current_rx_bytes;
96         u8                      *current_rx_buf;
97         u8                      printer_status;
98         u8                      reset_printer;
99         struct cdev             printer_cdev;
100         struct device           *pdev;
101         u8                      printer_cdev_open;
102         wait_queue_head_t       wait;
103 };
104
105 static struct printer_dev usb_printer_gadget;
106
107 /*-------------------------------------------------------------------------*/
108
109 /* DO NOT REUSE THESE IDs with a protocol-incompatible driver!!  Ever!!
110  * Instead:  allocate your own, using normal USB-IF procedures.
111  */
112
113 /* Thanks to NetChip Technologies for donating this product ID.
114  */
115 #define PRINTER_VENDOR_NUM      0x0525          /* NetChip */
116 #define PRINTER_PRODUCT_NUM     0xa4a8          /* Linux-USB Printer Gadget */
117
118 /* Some systems will want different product identifiers published in the
119  * device descriptor, either numbers or strings or both.  These string
120  * parameters are in UTF-8 (superset of ASCII's 7 bit characters).
121  */
122
123 static ushort idVendor;
124 module_param(idVendor, ushort, S_IRUGO);
125 MODULE_PARM_DESC(idVendor, "USB Vendor ID");
126
127 static ushort idProduct;
128 module_param(idProduct, ushort, S_IRUGO);
129 MODULE_PARM_DESC(idProduct, "USB Product ID");
130
131 static ushort bcdDevice;
132 module_param(bcdDevice, ushort, S_IRUGO);
133 MODULE_PARM_DESC(bcdDevice, "USB Device version (BCD)");
134
135 static char *iManufacturer;
136 module_param(iManufacturer, charp, S_IRUGO);
137 MODULE_PARM_DESC(iManufacturer, "USB Manufacturer string");
138
139 static char *iProduct;
140 module_param(iProduct, charp, S_IRUGO);
141 MODULE_PARM_DESC(iProduct, "USB Product string");
142
143 static char *iSerialNum;
144 module_param(iSerialNum, charp, S_IRUGO);
145 MODULE_PARM_DESC(iSerialNum, "1");
146
147 static char *iPNPstring;
148 module_param(iPNPstring, charp, S_IRUGO);
149 MODULE_PARM_DESC(iPNPstring, "MFG:linux;MDL:g_printer;CLS:PRINTER;SN:1;");
150
151 /* Number of requests to allocate per endpoint, not used for ep0. */
152 static unsigned qlen = 10;
153 module_param(qlen, uint, S_IRUGO|S_IWUSR);
154
155 #define QLEN    qlen
156
157 #ifdef CONFIG_USB_GADGET_DUALSPEED
158 #define DEVSPEED        USB_SPEED_HIGH
159 #else   /* full speed (low speed doesn't do bulk) */
160 #define DEVSPEED        USB_SPEED_FULL
161 #endif
162
163 /*-------------------------------------------------------------------------*/
164
165 #define xprintk(d, level, fmt, args...) \
166         printk(level "%s: " fmt, DRIVER_DESC, ## args)
167
168 #ifdef DEBUG
169 #define DBG(dev, fmt, args...) \
170         xprintk(dev, KERN_DEBUG, fmt, ## args)
171 #else
172 #define DBG(dev, fmt, args...) \
173         do { } while (0)
174 #endif /* DEBUG */
175
176 #ifdef VERBOSE
177 #define VDBG(dev, fmt, args...) \
178         xprintk(dev, KERN_DEBUG, fmt, ## args)
179 #else
180 #define VDBG(dev, fmt, args...) \
181         do { } while (0)
182 #endif /* VERBOSE */
183
184 #define ERROR(dev, fmt, args...) \
185         xprintk(dev, KERN_ERR, fmt, ## args)
186 #define WARNING(dev, fmt, args...) \
187         xprintk(dev, KERN_WARNING, fmt, ## args)
188 #define INFO(dev, fmt, args...) \
189         xprintk(dev, KERN_INFO, fmt, ## args)
190
191 /*-------------------------------------------------------------------------*/
192
193 /* USB DRIVER HOOKUP (to the hardware driver, below us), mostly
194  * ep0 implementation:  descriptors, config management, setup().
195  * also optional class-specific notification interrupt transfer.
196  */
197
198 /*
199  * DESCRIPTORS ... most are static, but strings and (full) configuration
200  * descriptors are built on demand.
201  */
202
203 #define STRING_MANUFACTURER             1
204 #define STRING_PRODUCT                  2
205 #define STRING_SERIALNUM                3
206
207 /* holds our biggest descriptor */
208 #define USB_DESC_BUFSIZE                256
209 #define USB_BUFSIZE                     8192
210
211 /* This device advertises one configuration. */
212 #define DEV_CONFIG_VALUE                1
213 #define PRINTER_INTERFACE               0
214
215 static struct usb_device_descriptor device_desc = {
216         .bLength =              sizeof device_desc,
217         .bDescriptorType =      USB_DT_DEVICE,
218         .bcdUSB =               cpu_to_le16(0x0200),
219         .bDeviceClass =         USB_CLASS_PER_INTERFACE,
220         .bDeviceSubClass =      0,
221         .bDeviceProtocol =      0,
222         .idVendor =             cpu_to_le16(PRINTER_VENDOR_NUM),
223         .idProduct =            cpu_to_le16(PRINTER_PRODUCT_NUM),
224         .iManufacturer =        STRING_MANUFACTURER,
225         .iProduct =             STRING_PRODUCT,
226         .iSerialNumber =        STRING_SERIALNUM,
227         .bNumConfigurations =   1
228 };
229
230 static struct usb_otg_descriptor otg_desc = {
231         .bLength =              sizeof otg_desc,
232         .bDescriptorType =      USB_DT_OTG,
233         .bmAttributes =         USB_OTG_SRP
234 };
235
236 static struct usb_config_descriptor config_desc = {
237         .bLength =              sizeof config_desc,
238         .bDescriptorType =      USB_DT_CONFIG,
239
240         /* compute wTotalLength on the fly */
241         .bNumInterfaces =       1,
242         .bConfigurationValue =  DEV_CONFIG_VALUE,
243         .iConfiguration =       0,
244         .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
245         .bMaxPower =            CONFIG_USB_GADGET_VBUS_DRAW / 2,
246 };
247
248 static struct usb_interface_descriptor intf_desc = {
249         .bLength =              sizeof intf_desc,
250         .bDescriptorType =      USB_DT_INTERFACE,
251         .bInterfaceNumber =     PRINTER_INTERFACE,
252         .bNumEndpoints =        2,
253         .bInterfaceClass =      USB_CLASS_PRINTER,
254         .bInterfaceSubClass =   1,      /* Printer Sub-Class */
255         .bInterfaceProtocol =   2,      /* Bi-Directional */
256         .iInterface =           0
257 };
258
259 static struct usb_endpoint_descriptor fs_ep_in_desc = {
260         .bLength =              USB_DT_ENDPOINT_SIZE,
261         .bDescriptorType =      USB_DT_ENDPOINT,
262         .bEndpointAddress =     USB_DIR_IN,
263         .bmAttributes =         USB_ENDPOINT_XFER_BULK
264 };
265
266 static struct usb_endpoint_descriptor fs_ep_out_desc = {
267         .bLength =              USB_DT_ENDPOINT_SIZE,
268         .bDescriptorType =      USB_DT_ENDPOINT,
269         .bEndpointAddress =     USB_DIR_OUT,
270         .bmAttributes =         USB_ENDPOINT_XFER_BULK
271 };
272
273 static const struct usb_descriptor_header *fs_printer_function [11] = {
274         (struct usb_descriptor_header *) &otg_desc,
275         (struct usb_descriptor_header *) &intf_desc,
276         (struct usb_descriptor_header *) &fs_ep_in_desc,
277         (struct usb_descriptor_header *) &fs_ep_out_desc,
278         NULL
279 };
280
281 #ifdef  CONFIG_USB_GADGET_DUALSPEED
282
283 /*
284  * usb 2.0 devices need to expose both high speed and full speed
285  * descriptors, unless they only run at full speed.
286  */
287
288 static struct usb_endpoint_descriptor hs_ep_in_desc = {
289         .bLength =              USB_DT_ENDPOINT_SIZE,
290         .bDescriptorType =      USB_DT_ENDPOINT,
291         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
292         .wMaxPacketSize =       cpu_to_le16(512)
293 };
294
295 static struct usb_endpoint_descriptor hs_ep_out_desc = {
296         .bLength =              USB_DT_ENDPOINT_SIZE,
297         .bDescriptorType =      USB_DT_ENDPOINT,
298         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
299         .wMaxPacketSize =       cpu_to_le16(512)
300 };
301
302 static struct usb_qualifier_descriptor dev_qualifier = {
303         .bLength =              sizeof dev_qualifier,
304         .bDescriptorType =      USB_DT_DEVICE_QUALIFIER,
305         .bcdUSB =               cpu_to_le16(0x0200),
306         .bDeviceClass =         USB_CLASS_PRINTER,
307         .bNumConfigurations =   1
308 };
309
310 static const struct usb_descriptor_header *hs_printer_function [11] = {
311         (struct usb_descriptor_header *) &otg_desc,
312         (struct usb_descriptor_header *) &intf_desc,
313         (struct usb_descriptor_header *) &hs_ep_in_desc,
314         (struct usb_descriptor_header *) &hs_ep_out_desc,
315         NULL
316 };
317
318 /* maxpacket and other transfer characteristics vary by speed. */
319 #define ep_desc(g, hs, fs) (((g)->speed == USB_SPEED_HIGH)?(hs):(fs))
320
321 #else
322
323 /* if there's no high speed support, maxpacket doesn't change. */
324 #define ep_desc(g, hs, fs) (((void)(g)), (fs))
325
326 #endif  /* !CONFIG_USB_GADGET_DUALSPEED */
327
328 /*-------------------------------------------------------------------------*/
329
330 /* descriptors that are built on-demand */
331
332 static char                             manufacturer [50];
333 static char                             product_desc [40] = DRIVER_DESC;
334 static char                             serial_num [40] = "1";
335 static char                             pnp_string [1024] =
336         "XXMFG:linux;MDL:g_printer;CLS:PRINTER;SN:1;";
337
338 /* static strings, in UTF-8 */
339 static struct usb_string                strings [] = {
340         { STRING_MANUFACTURER,  manufacturer, },
341         { STRING_PRODUCT,       product_desc, },
342         { STRING_SERIALNUM,     serial_num, },
343         {  }            /* end of list */
344 };
345
346 static struct usb_gadget_strings        stringtab = {
347         .language       = 0x0409,       /* en-us */
348         .strings        = strings,
349 };
350
351 /*-------------------------------------------------------------------------*/
352
353 static struct usb_request *
354 printer_req_alloc(struct usb_ep *ep, unsigned len, gfp_t gfp_flags)
355 {
356         struct usb_request      *req;
357
358         req = usb_ep_alloc_request(ep, gfp_flags);
359
360         if (req != NULL) {
361                 req->length = len;
362                 req->buf = kmalloc(len, gfp_flags);
363                 if (req->buf == NULL) {
364                         usb_ep_free_request(ep, req);
365                         return NULL;
366                 }
367         }
368
369         return req;
370 }
371
372 static void
373 printer_req_free(struct usb_ep *ep, struct usb_request *req)
374 {
375         if (ep != NULL && req != NULL) {
376                 kfree(req->buf);
377                 usb_ep_free_request(ep, req);
378         }
379 }
380
381 /*-------------------------------------------------------------------------*/
382
383 static void rx_complete(struct usb_ep *ep, struct usb_request *req)
384 {
385         struct printer_dev      *dev = ep->driver_data;
386         int                     status = req->status;
387         unsigned long           flags;
388
389         spin_lock_irqsave(&dev->lock, flags);
390
391         list_del_init(&req->list);      /* Remode from Active List */
392
393         switch (status) {
394
395         /* normal completion */
396         case 0:
397                 if (req->actual > 0) {
398                         list_add_tail(&req->list, &dev->rx_buffers);
399                         DBG(dev, "G_Printer : rx length %d\n", req->actual);
400                 } else {
401                         list_add(&req->list, &dev->rx_reqs);
402                 }
403                 break;
404
405         /* software-driven interface shutdown */
406         case -ECONNRESET:               /* unlink */
407         case -ESHUTDOWN:                /* disconnect etc */
408                 VDBG(dev, "rx shutdown, code %d\n", status);
409                 list_add(&req->list, &dev->rx_reqs);
410                 break;
411
412         /* for hardware automagic (such as pxa) */
413         case -ECONNABORTED:             /* endpoint reset */
414                 DBG(dev, "rx %s reset\n", ep->name);
415                 list_add(&req->list, &dev->rx_reqs);
416                 break;
417
418         /* data overrun */
419         case -EOVERFLOW:
420                 /* FALLTHROUGH */
421
422         default:
423                 DBG(dev, "rx status %d\n", status);
424                 list_add(&req->list, &dev->rx_reqs);
425                 break;
426         }
427
428         wake_up_interruptible(&dev->rx_wait);
429         spin_unlock_irqrestore(&dev->lock, flags);
430 }
431
432 static void tx_complete(struct usb_ep *ep, struct usb_request *req)
433 {
434         struct printer_dev      *dev = ep->driver_data;
435
436         switch (req->status) {
437         default:
438                 VDBG(dev, "tx err %d\n", req->status);
439                 /* FALLTHROUGH */
440         case -ECONNRESET:               /* unlink */
441         case -ESHUTDOWN:                /* disconnect etc */
442                 break;
443         case 0:
444                 break;
445         }
446
447         spin_lock(&dev->lock);
448         /* Take the request struct off the active list and put it on the
449          * free list.
450          */
451         list_del_init(&req->list);
452         list_add(&req->list, &dev->tx_reqs);
453         wake_up_interruptible(&dev->tx_wait);
454         if (likely(list_empty(&dev->tx_reqs_active)))
455                 wake_up_interruptible(&dev->tx_flush_wait);
456
457         spin_unlock(&dev->lock);
458 }
459
460 /*-------------------------------------------------------------------------*/
461
462 static int
463 printer_open(struct inode *inode, struct file *fd)
464 {
465         struct printer_dev      *dev;
466         unsigned long           flags;
467         int                     ret = -EBUSY;
468
469         mutex_lock(&printer_mutex);
470         dev = container_of(inode->i_cdev, struct printer_dev, printer_cdev);
471
472         spin_lock_irqsave(&dev->lock, flags);
473
474         if (!dev->printer_cdev_open) {
475                 dev->printer_cdev_open = 1;
476                 fd->private_data = dev;
477                 ret = 0;
478                 /* Change the printer status to show that it's on-line. */
479                 dev->printer_status |= PRINTER_SELECTED;
480         }
481
482         spin_unlock_irqrestore(&dev->lock, flags);
483
484         DBG(dev, "printer_open returned %x\n", ret);
485         mutex_unlock(&printer_mutex);
486         return ret;
487 }
488
489 static int
490 printer_close(struct inode *inode, struct file *fd)
491 {
492         struct printer_dev      *dev = fd->private_data;
493         unsigned long           flags;
494
495         spin_lock_irqsave(&dev->lock, flags);
496         dev->printer_cdev_open = 0;
497         fd->private_data = NULL;
498         /* Change printer status to show that the printer is off-line. */
499         dev->printer_status &= ~PRINTER_SELECTED;
500         spin_unlock_irqrestore(&dev->lock, flags);
501
502         DBG(dev, "printer_close\n");
503
504         return 0;
505 }
506
507 /* This function must be called with interrupts turned off. */
508 static void
509 setup_rx_reqs(struct printer_dev *dev)
510 {
511         struct usb_request              *req;
512
513         while (likely(!list_empty(&dev->rx_reqs))) {
514                 int error;
515
516                 req = container_of(dev->rx_reqs.next,
517                                 struct usb_request, list);
518                 list_del_init(&req->list);
519
520                 /* The USB Host sends us whatever amount of data it wants to
521                  * so we always set the length field to the full USB_BUFSIZE.
522                  * If the amount of data is more than the read() caller asked
523                  * for it will be stored in the request buffer until it is
524                  * asked for by read().
525                  */
526                 req->length = USB_BUFSIZE;
527                 req->complete = rx_complete;
528
529                 error = usb_ep_queue(dev->out_ep, req, GFP_ATOMIC);
530                 if (error) {
531                         DBG(dev, "rx submit --> %d\n", error);
532                         list_add(&req->list, &dev->rx_reqs);
533                         break;
534                 } else {
535                         list_add(&req->list, &dev->rx_reqs_active);
536                 }
537         }
538 }
539
540 static ssize_t
541 printer_read(struct file *fd, char __user *buf, size_t len, loff_t *ptr)
542 {
543         struct printer_dev              *dev = fd->private_data;
544         unsigned long                   flags;
545         size_t                          size;
546         size_t                          bytes_copied;
547         struct usb_request              *req;
548         /* This is a pointer to the current USB rx request. */
549         struct usb_request              *current_rx_req;
550         /* This is the number of bytes in the current rx buffer. */
551         size_t                          current_rx_bytes;
552         /* This is a pointer to the current rx buffer. */
553         u8                              *current_rx_buf;
554
555         if (len == 0)
556                 return -EINVAL;
557
558         DBG(dev, "printer_read trying to read %d bytes\n", (int)len);
559
560         mutex_lock(&dev->lock_printer_io);
561         spin_lock_irqsave(&dev->lock, flags);
562
563         /* We will use this flag later to check if a printer reset happened
564          * after we turn interrupts back on.
565          */
566         dev->reset_printer = 0;
567
568         setup_rx_reqs(dev);
569
570         bytes_copied = 0;
571         current_rx_req = dev->current_rx_req;
572         current_rx_bytes = dev->current_rx_bytes;
573         current_rx_buf = dev->current_rx_buf;
574         dev->current_rx_req = NULL;
575         dev->current_rx_bytes = 0;
576         dev->current_rx_buf = NULL;
577
578         /* Check if there is any data in the read buffers. Please note that
579          * current_rx_bytes is the number of bytes in the current rx buffer.
580          * If it is zero then check if there are any other rx_buffers that
581          * are on the completed list. We are only out of data if all rx
582          * buffers are empty.
583          */
584         if ((current_rx_bytes == 0) &&
585                         (likely(list_empty(&dev->rx_buffers)))) {
586                 /* Turn interrupts back on before sleeping. */
587                 spin_unlock_irqrestore(&dev->lock, flags);
588
589                 /*
590                  * If no data is available check if this is a NON-Blocking
591                  * call or not.
592                  */
593                 if (fd->f_flags & (O_NONBLOCK|O_NDELAY)) {
594                         mutex_unlock(&dev->lock_printer_io);
595                         return -EAGAIN;
596                 }
597
598                 /* Sleep until data is available */
599                 wait_event_interruptible(dev->rx_wait,
600                                 (likely(!list_empty(&dev->rx_buffers))));
601                 spin_lock_irqsave(&dev->lock, flags);
602         }
603
604         /* We have data to return then copy it to the caller's buffer.*/
605         while ((current_rx_bytes || likely(!list_empty(&dev->rx_buffers)))
606                         && len) {
607                 if (current_rx_bytes == 0) {
608                         req = container_of(dev->rx_buffers.next,
609                                         struct usb_request, list);
610                         list_del_init(&req->list);
611
612                         if (req->actual && req->buf) {
613                                 current_rx_req = req;
614                                 current_rx_bytes = req->actual;
615                                 current_rx_buf = req->buf;
616                         } else {
617                                 list_add(&req->list, &dev->rx_reqs);
618                                 continue;
619                         }
620                 }
621
622                 /* Don't leave irqs off while doing memory copies */
623                 spin_unlock_irqrestore(&dev->lock, flags);
624
625                 if (len > current_rx_bytes)
626                         size = current_rx_bytes;
627                 else
628                         size = len;
629
630                 size -= copy_to_user(buf, current_rx_buf, size);
631                 bytes_copied += size;
632                 len -= size;
633                 buf += size;
634
635                 spin_lock_irqsave(&dev->lock, flags);
636
637                 /* We've disconnected or reset so return. */
638                 if (dev->reset_printer) {
639                         list_add(&current_rx_req->list, &dev->rx_reqs);
640                         spin_unlock_irqrestore(&dev->lock, flags);
641                         mutex_unlock(&dev->lock_printer_io);
642                         return -EAGAIN;
643                 }
644
645                 /* If we not returning all the data left in this RX request
646                  * buffer then adjust the amount of data left in the buffer.
647                  * Othewise if we are done with this RX request buffer then
648                  * requeue it to get any incoming data from the USB host.
649                  */
650                 if (size < current_rx_bytes) {
651                         current_rx_bytes -= size;
652                         current_rx_buf += size;
653                 } else {
654                         list_add(&current_rx_req->list, &dev->rx_reqs);
655                         current_rx_bytes = 0;
656                         current_rx_buf = NULL;
657                         current_rx_req = NULL;
658                 }
659         }
660
661         dev->current_rx_req = current_rx_req;
662         dev->current_rx_bytes = current_rx_bytes;
663         dev->current_rx_buf = current_rx_buf;
664
665         spin_unlock_irqrestore(&dev->lock, flags);
666         mutex_unlock(&dev->lock_printer_io);
667
668         DBG(dev, "printer_read returned %d bytes\n", (int)bytes_copied);
669
670         if (bytes_copied)
671                 return bytes_copied;
672         else
673                 return -EAGAIN;
674 }
675
676 static ssize_t
677 printer_write(struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
678 {
679         struct printer_dev      *dev = fd->private_data;
680         unsigned long           flags;
681         size_t                  size;   /* Amount of data in a TX request. */
682         size_t                  bytes_copied = 0;
683         struct usb_request      *req;
684
685         DBG(dev, "printer_write trying to send %d bytes\n", (int)len);
686
687         if (len == 0)
688                 return -EINVAL;
689
690         mutex_lock(&dev->lock_printer_io);
691         spin_lock_irqsave(&dev->lock, flags);
692
693         /* Check if a printer reset happens while we have interrupts on */
694         dev->reset_printer = 0;
695
696         /* Check if there is any available write buffers */
697         if (likely(list_empty(&dev->tx_reqs))) {
698                 /* Turn interrupts back on before sleeping. */
699                 spin_unlock_irqrestore(&dev->lock, flags);
700
701                 /*
702                  * If write buffers are available check if this is
703                  * a NON-Blocking call or not.
704                  */
705                 if (fd->f_flags & (O_NONBLOCK|O_NDELAY)) {
706                         mutex_unlock(&dev->lock_printer_io);
707                         return -EAGAIN;
708                 }
709
710                 /* Sleep until a write buffer is available */
711                 wait_event_interruptible(dev->tx_wait,
712                                 (likely(!list_empty(&dev->tx_reqs))));
713                 spin_lock_irqsave(&dev->lock, flags);
714         }
715
716         while (likely(!list_empty(&dev->tx_reqs)) && len) {
717
718                 if (len > USB_BUFSIZE)
719                         size = USB_BUFSIZE;
720                 else
721                         size = len;
722
723                 req = container_of(dev->tx_reqs.next, struct usb_request,
724                                 list);
725                 list_del_init(&req->list);
726
727                 req->complete = tx_complete;
728                 req->length = size;
729
730                 /* Check if we need to send a zero length packet. */
731                 if (len > size)
732                         /* They will be more TX requests so no yet. */
733                         req->zero = 0;
734                 else
735                         /* If the data amount is not a multple of the
736                          * maxpacket size then send a zero length packet.
737                          */
738                         req->zero = ((len % dev->in_ep->maxpacket) == 0);
739
740                 /* Don't leave irqs off while doing memory copies */
741                 spin_unlock_irqrestore(&dev->lock, flags);
742
743                 if (copy_from_user(req->buf, buf, size)) {
744                         list_add(&req->list, &dev->tx_reqs);
745                         mutex_unlock(&dev->lock_printer_io);
746                         return bytes_copied;
747                 }
748
749                 bytes_copied += size;
750                 len -= size;
751                 buf += size;
752
753                 spin_lock_irqsave(&dev->lock, flags);
754
755                 /* We've disconnected or reset so free the req and buffer */
756                 if (dev->reset_printer) {
757                         list_add(&req->list, &dev->tx_reqs);
758                         spin_unlock_irqrestore(&dev->lock, flags);
759                         mutex_unlock(&dev->lock_printer_io);
760                         return -EAGAIN;
761                 }
762
763                 if (usb_ep_queue(dev->in_ep, req, GFP_ATOMIC)) {
764                         list_add(&req->list, &dev->tx_reqs);
765                         spin_unlock_irqrestore(&dev->lock, flags);
766                         mutex_unlock(&dev->lock_printer_io);
767                         return -EAGAIN;
768                 }
769
770                 list_add(&req->list, &dev->tx_reqs_active);
771
772         }
773
774         spin_unlock_irqrestore(&dev->lock, flags);
775         mutex_unlock(&dev->lock_printer_io);
776
777         DBG(dev, "printer_write sent %d bytes\n", (int)bytes_copied);
778
779         if (bytes_copied) {
780                 return bytes_copied;
781         } else {
782                 return -EAGAIN;
783         }
784 }
785
786 static int
787 printer_fsync(struct file *fd, loff_t start, loff_t end, int datasync)
788 {
789         struct printer_dev      *dev = fd->private_data;
790         struct inode *inode = fd->f_path.dentry->d_inode;
791         unsigned long           flags;
792         int                     tx_list_empty;
793
794         mutex_lock(&inode->i_mutex);
795         spin_lock_irqsave(&dev->lock, flags);
796         tx_list_empty = (likely(list_empty(&dev->tx_reqs)));
797         spin_unlock_irqrestore(&dev->lock, flags);
798
799         if (!tx_list_empty) {
800                 /* Sleep until all data has been sent */
801                 wait_event_interruptible(dev->tx_flush_wait,
802                                 (likely(list_empty(&dev->tx_reqs_active))));
803         }
804         mutex_unlock(&inode->i_mutex);
805
806         return 0;
807 }
808
809 static unsigned int
810 printer_poll(struct file *fd, poll_table *wait)
811 {
812         struct printer_dev      *dev = fd->private_data;
813         unsigned long           flags;
814         int                     status = 0;
815
816         mutex_lock(&dev->lock_printer_io);
817         spin_lock_irqsave(&dev->lock, flags);
818         setup_rx_reqs(dev);
819         spin_unlock_irqrestore(&dev->lock, flags);
820         mutex_unlock(&dev->lock_printer_io);
821
822         poll_wait(fd, &dev->rx_wait, wait);
823         poll_wait(fd, &dev->tx_wait, wait);
824
825         spin_lock_irqsave(&dev->lock, flags);
826         if (likely(!list_empty(&dev->tx_reqs)))
827                 status |= POLLOUT | POLLWRNORM;
828
829         if (likely(dev->current_rx_bytes) ||
830                         likely(!list_empty(&dev->rx_buffers)))
831                 status |= POLLIN | POLLRDNORM;
832
833         spin_unlock_irqrestore(&dev->lock, flags);
834
835         return status;
836 }
837
838 static long
839 printer_ioctl(struct file *fd, unsigned int code, unsigned long arg)
840 {
841         struct printer_dev      *dev = fd->private_data;
842         unsigned long           flags;
843         int                     status = 0;
844
845         DBG(dev, "printer_ioctl: cmd=0x%4.4x, arg=%lu\n", code, arg);
846
847         /* handle ioctls */
848
849         spin_lock_irqsave(&dev->lock, flags);
850
851         switch (code) {
852         case GADGET_GET_PRINTER_STATUS:
853                 status = (int)dev->printer_status;
854                 break;
855         case GADGET_SET_PRINTER_STATUS:
856                 dev->printer_status = (u8)arg;
857                 break;
858         default:
859                 /* could not handle ioctl */
860                 DBG(dev, "printer_ioctl: ERROR cmd=0x%4.4xis not supported\n",
861                                 code);
862                 status = -ENOTTY;
863         }
864
865         spin_unlock_irqrestore(&dev->lock, flags);
866
867         return status;
868 }
869
870 /* used after endpoint configuration */
871 static const struct file_operations printer_io_operations = {
872         .owner =        THIS_MODULE,
873         .open =         printer_open,
874         .read =         printer_read,
875         .write =        printer_write,
876         .fsync =        printer_fsync,
877         .poll =         printer_poll,
878         .unlocked_ioctl = printer_ioctl,
879         .release =      printer_close,
880         .llseek =       noop_llseek,
881 };
882
883 /*-------------------------------------------------------------------------*/
884
885 static int
886 set_printer_interface(struct printer_dev *dev)
887 {
888         int                     result = 0;
889
890         dev->in_ep->desc = ep_desc(dev->gadget, &hs_ep_in_desc, &fs_ep_in_desc);
891         dev->in_ep->driver_data = dev;
892
893         dev->out_ep->desc = ep_desc(dev->gadget, &hs_ep_out_desc,
894                                     &fs_ep_out_desc);
895         dev->out_ep->driver_data = dev;
896
897         result = usb_ep_enable(dev->in_ep);
898         if (result != 0) {
899                 DBG(dev, "enable %s --> %d\n", dev->in_ep->name, result);
900                 goto done;
901         }
902
903         result = usb_ep_enable(dev->out_ep);
904         if (result != 0) {
905                 DBG(dev, "enable %s --> %d\n", dev->in_ep->name, result);
906                 goto done;
907         }
908
909 done:
910         /* on error, disable any endpoints  */
911         if (result != 0) {
912                 (void) usb_ep_disable(dev->in_ep);
913                 (void) usb_ep_disable(dev->out_ep);
914                 dev->in_ep->desc = NULL;
915                 dev->out_ep->desc = NULL;
916         }
917
918         /* caller is responsible for cleanup on error */
919         return result;
920 }
921
922 static void printer_reset_interface(struct printer_dev *dev)
923 {
924         if (dev->interface < 0)
925                 return;
926
927         DBG(dev, "%s\n", __func__);
928
929         if (dev->in_ep->desc)
930                 usb_ep_disable(dev->in_ep);
931
932         if (dev->out_ep->desc)
933                 usb_ep_disable(dev->out_ep);
934
935         dev->in_ep->desc = NULL;
936         dev->out_ep->desc = NULL;
937         dev->interface = -1;
938 }
939
940 /* change our operational config.  must agree with the code
941  * that returns config descriptors, and altsetting code.
942  */
943 static int
944 printer_set_config(struct printer_dev *dev, unsigned number)
945 {
946         int                     result = 0;
947         struct usb_gadget       *gadget = dev->gadget;
948
949         switch (number) {
950         case DEV_CONFIG_VALUE:
951                 result = 0;
952                 break;
953         default:
954                 result = -EINVAL;
955                 /* FALL THROUGH */
956         case 0:
957                 break;
958         }
959
960         if (result) {
961                 usb_gadget_vbus_draw(dev->gadget,
962                                 dev->gadget->is_otg ? 8 : 100);
963         } else {
964                 unsigned power;
965
966                 power = 2 * config_desc.bMaxPower;
967                 usb_gadget_vbus_draw(dev->gadget, power);
968
969                 dev->config = number;
970                 INFO(dev, "%s config #%d: %d mA, %s\n",
971                      usb_speed_string(gadget->speed),
972                      number, power, driver_desc);
973         }
974         return result;
975 }
976
977 static int
978 config_buf(enum usb_device_speed speed, u8 *buf, u8 type, unsigned index,
979                 int is_otg)
980 {
981         int                                     len;
982         const struct usb_descriptor_header      **function;
983 #ifdef CONFIG_USB_GADGET_DUALSPEED
984         int                                     hs = (speed == USB_SPEED_HIGH);
985
986         if (type == USB_DT_OTHER_SPEED_CONFIG)
987                 hs = !hs;
988
989         if (hs) {
990                 function = hs_printer_function;
991         } else {
992                 function = fs_printer_function;
993         }
994 #else
995         function = fs_printer_function;
996 #endif
997
998         if (index >= device_desc.bNumConfigurations)
999                 return -EINVAL;
1000
1001         /* for now, don't advertise srp-only devices */
1002         if (!is_otg)
1003                 function++;
1004
1005         len = usb_gadget_config_buf(&config_desc, buf, USB_DESC_BUFSIZE,
1006                         function);
1007         if (len < 0)
1008                 return len;
1009         ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1010         return len;
1011 }
1012
1013 /* Change our operational Interface. */
1014 static int
1015 set_interface(struct printer_dev *dev, unsigned number)
1016 {
1017         int                     result = 0;
1018
1019         /* Free the current interface */
1020         switch (dev->interface) {
1021         case PRINTER_INTERFACE:
1022                 printer_reset_interface(dev);
1023                 break;
1024         }
1025
1026         switch (number) {
1027         case PRINTER_INTERFACE:
1028                 result = set_printer_interface(dev);
1029                 if (result) {
1030                         printer_reset_interface(dev);
1031                 } else {
1032                         dev->interface = PRINTER_INTERFACE;
1033                 }
1034                 break;
1035         default:
1036                 result = -EINVAL;
1037                 /* FALL THROUGH */
1038         }
1039
1040         if (!result)
1041                 INFO(dev, "Using interface %x\n", number);
1042
1043         return result;
1044 }
1045
1046 static void printer_setup_complete(struct usb_ep *ep, struct usb_request *req)
1047 {
1048         if (req->status || req->actual != req->length)
1049                 DBG((struct printer_dev *) ep->driver_data,
1050                                 "setup complete --> %d, %d/%d\n",
1051                                 req->status, req->actual, req->length);
1052 }
1053
1054 static void printer_soft_reset(struct printer_dev *dev)
1055 {
1056         struct usb_request      *req;
1057
1058         INFO(dev, "Received Printer Reset Request\n");
1059
1060         if (usb_ep_disable(dev->in_ep))
1061                 DBG(dev, "Failed to disable USB in_ep\n");
1062         if (usb_ep_disable(dev->out_ep))
1063                 DBG(dev, "Failed to disable USB out_ep\n");
1064
1065         if (dev->current_rx_req != NULL) {
1066                 list_add(&dev->current_rx_req->list, &dev->rx_reqs);
1067                 dev->current_rx_req = NULL;
1068         }
1069         dev->current_rx_bytes = 0;
1070         dev->current_rx_buf = NULL;
1071         dev->reset_printer = 1;
1072
1073         while (likely(!(list_empty(&dev->rx_buffers)))) {
1074                 req = container_of(dev->rx_buffers.next, struct usb_request,
1075                                 list);
1076                 list_del_init(&req->list);
1077                 list_add(&req->list, &dev->rx_reqs);
1078         }
1079
1080         while (likely(!(list_empty(&dev->rx_reqs_active)))) {
1081                 req = container_of(dev->rx_buffers.next, struct usb_request,
1082                                 list);
1083                 list_del_init(&req->list);
1084                 list_add(&req->list, &dev->rx_reqs);
1085         }
1086
1087         while (likely(!(list_empty(&dev->tx_reqs_active)))) {
1088                 req = container_of(dev->tx_reqs_active.next,
1089                                 struct usb_request, list);
1090                 list_del_init(&req->list);
1091                 list_add(&req->list, &dev->tx_reqs);
1092         }
1093
1094         if (usb_ep_enable(dev->in_ep))
1095                 DBG(dev, "Failed to enable USB in_ep\n");
1096         if (usb_ep_enable(dev->out_ep))
1097                 DBG(dev, "Failed to enable USB out_ep\n");
1098
1099         wake_up_interruptible(&dev->rx_wait);
1100         wake_up_interruptible(&dev->tx_wait);
1101         wake_up_interruptible(&dev->tx_flush_wait);
1102 }
1103
1104 /*-------------------------------------------------------------------------*/
1105
1106 /*
1107  * The setup() callback implements all the ep0 functionality that's not
1108  * handled lower down.
1109  */
1110 static int
1111 printer_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1112 {
1113         struct printer_dev      *dev = get_gadget_data(gadget);
1114         struct usb_request      *req = dev->req;
1115         int                     value = -EOPNOTSUPP;
1116         u16                     wIndex = le16_to_cpu(ctrl->wIndex);
1117         u16                     wValue = le16_to_cpu(ctrl->wValue);
1118         u16                     wLength = le16_to_cpu(ctrl->wLength);
1119
1120         DBG(dev, "ctrl req%02x.%02x v%04x i%04x l%d\n",
1121                 ctrl->bRequestType, ctrl->bRequest, wValue, wIndex, wLength);
1122
1123         req->complete = printer_setup_complete;
1124
1125         switch (ctrl->bRequestType&USB_TYPE_MASK) {
1126
1127         case USB_TYPE_STANDARD:
1128                 switch (ctrl->bRequest) {
1129
1130                 case USB_REQ_GET_DESCRIPTOR:
1131                         if (ctrl->bRequestType != USB_DIR_IN)
1132                                 break;
1133                         switch (wValue >> 8) {
1134
1135                         case USB_DT_DEVICE:
1136                                 device_desc.bMaxPacketSize0 =
1137                                         gadget->ep0->maxpacket;
1138                                 value = min(wLength, (u16) sizeof device_desc);
1139                                 memcpy(req->buf, &device_desc, value);
1140                                 break;
1141 #ifdef CONFIG_USB_GADGET_DUALSPEED
1142                         case USB_DT_DEVICE_QUALIFIER:
1143                                 if (!gadget_is_dualspeed(gadget))
1144                                         break;
1145                                 /*
1146                                  * assumes ep0 uses the same value for both
1147                                  * speeds
1148                                  */
1149                                 dev_qualifier.bMaxPacketSize0 =
1150                                         gadget->ep0->maxpacket;
1151                                 value = min(wLength,
1152                                                 (u16) sizeof dev_qualifier);
1153                                 memcpy(req->buf, &dev_qualifier, value);
1154                                 break;
1155
1156                         case USB_DT_OTHER_SPEED_CONFIG:
1157                                 if (!gadget_is_dualspeed(gadget))
1158                                         break;
1159                                 /* FALLTHROUGH */
1160 #endif /* CONFIG_USB_GADGET_DUALSPEED */
1161                         case USB_DT_CONFIG:
1162                                 value = config_buf(gadget->speed, req->buf,
1163                                                 wValue >> 8,
1164                                                 wValue & 0xff,
1165                                                 gadget->is_otg);
1166                                 if (value >= 0)
1167                                         value = min(wLength, (u16) value);
1168                                 break;
1169
1170                         case USB_DT_STRING:
1171                                 value = usb_gadget_get_string(&stringtab,
1172                                                 wValue & 0xff, req->buf);
1173                                 if (value >= 0)
1174                                         value = min(wLength, (u16) value);
1175                                 break;
1176                         }
1177                         break;
1178
1179                 case USB_REQ_SET_CONFIGURATION:
1180                         if (ctrl->bRequestType != 0)
1181                                 break;
1182                         if (gadget->a_hnp_support)
1183                                 DBG(dev, "HNP available\n");
1184                         else if (gadget->a_alt_hnp_support)
1185                                 DBG(dev, "HNP needs a different root port\n");
1186                         value = printer_set_config(dev, wValue);
1187                         if (!value)
1188                                 value = set_interface(dev, PRINTER_INTERFACE);
1189                         break;
1190                 case USB_REQ_GET_CONFIGURATION:
1191                         if (ctrl->bRequestType != USB_DIR_IN)
1192                                 break;
1193                         *(u8 *)req->buf = dev->config;
1194                         value = min(wLength, (u16) 1);
1195                         break;
1196
1197                 case USB_REQ_SET_INTERFACE:
1198                         if (ctrl->bRequestType != USB_RECIP_INTERFACE ||
1199                                         !dev->config)
1200                                 break;
1201
1202                         value = set_interface(dev, PRINTER_INTERFACE);
1203                         break;
1204                 case USB_REQ_GET_INTERFACE:
1205                         if (ctrl->bRequestType !=
1206                                         (USB_DIR_IN|USB_RECIP_INTERFACE)
1207                                         || !dev->config)
1208                                 break;
1209
1210                         *(u8 *)req->buf = dev->interface;
1211                         value = min(wLength, (u16) 1);
1212                         break;
1213
1214                 default:
1215                         goto unknown;
1216                 }
1217                 break;
1218
1219         case USB_TYPE_CLASS:
1220                 switch (ctrl->bRequest) {
1221                 case 0: /* Get the IEEE-1284 PNP String */
1222                         /* Only one printer interface is supported. */
1223                         if ((wIndex>>8) != PRINTER_INTERFACE)
1224                                 break;
1225
1226                         value = (pnp_string[0]<<8)|pnp_string[1];
1227                         memcpy(req->buf, pnp_string, value);
1228                         DBG(dev, "1284 PNP String: %x %s\n", value,
1229                                         &pnp_string[2]);
1230                         break;
1231
1232                 case 1: /* Get Port Status */
1233                         /* Only one printer interface is supported. */
1234                         if (wIndex != PRINTER_INTERFACE)
1235                                 break;
1236
1237                         *(u8 *)req->buf = dev->printer_status;
1238                         value = min(wLength, (u16) 1);
1239                         break;
1240
1241                 case 2: /* Soft Reset */
1242                         /* Only one printer interface is supported. */
1243                         if (wIndex != PRINTER_INTERFACE)
1244                                 break;
1245
1246                         printer_soft_reset(dev);
1247
1248                         value = 0;
1249                         break;
1250
1251                 default:
1252                         goto unknown;
1253                 }
1254                 break;
1255
1256         default:
1257 unknown:
1258                 VDBG(dev,
1259                         "unknown ctrl req%02x.%02x v%04x i%04x l%d\n",
1260                         ctrl->bRequestType, ctrl->bRequest,
1261                         wValue, wIndex, wLength);
1262                 break;
1263         }
1264
1265         /* respond with data transfer before status phase? */
1266         if (value >= 0) {
1267                 req->length = value;
1268                 req->zero = value < wLength;
1269                 value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1270                 if (value < 0) {
1271                         DBG(dev, "ep_queue --> %d\n", value);
1272                         req->status = 0;
1273                         printer_setup_complete(gadget->ep0, req);
1274                 }
1275         }
1276
1277         /* host either stalls (value < 0) or reports success */
1278         return value;
1279 }
1280
1281 static void
1282 printer_disconnect(struct usb_gadget *gadget)
1283 {
1284         struct printer_dev      *dev = get_gadget_data(gadget);
1285         unsigned long           flags;
1286
1287         DBG(dev, "%s\n", __func__);
1288
1289         spin_lock_irqsave(&dev->lock, flags);
1290
1291         printer_reset_interface(dev);
1292
1293         spin_unlock_irqrestore(&dev->lock, flags);
1294 }
1295
1296 static void
1297 printer_unbind(struct usb_gadget *gadget)
1298 {
1299         struct printer_dev      *dev = get_gadget_data(gadget);
1300         struct usb_request      *req;
1301
1302
1303         DBG(dev, "%s\n", __func__);
1304
1305         /* Remove sysfs files */
1306         device_destroy(usb_gadget_class, g_printer_devno);
1307
1308         /* Remove Character Device */
1309         cdev_del(&dev->printer_cdev);
1310
1311         /* we must already have been disconnected ... no i/o may be active */
1312         WARN_ON(!list_empty(&dev->tx_reqs_active));
1313         WARN_ON(!list_empty(&dev->rx_reqs_active));
1314
1315         /* Free all memory for this driver. */
1316         while (!list_empty(&dev->tx_reqs)) {
1317                 req = container_of(dev->tx_reqs.next, struct usb_request,
1318                                 list);
1319                 list_del(&req->list);
1320                 printer_req_free(dev->in_ep, req);
1321         }
1322
1323         if (dev->current_rx_req != NULL)
1324                 printer_req_free(dev->out_ep, dev->current_rx_req);
1325
1326         while (!list_empty(&dev->rx_reqs)) {
1327                 req = container_of(dev->rx_reqs.next,
1328                                 struct usb_request, list);
1329                 list_del(&req->list);
1330                 printer_req_free(dev->out_ep, req);
1331         }
1332
1333         while (!list_empty(&dev->rx_buffers)) {
1334                 req = container_of(dev->rx_buffers.next,
1335                                 struct usb_request, list);
1336                 list_del(&req->list);
1337                 printer_req_free(dev->out_ep, req);
1338         }
1339
1340         if (dev->req) {
1341                 printer_req_free(gadget->ep0, dev->req);
1342                 dev->req = NULL;
1343         }
1344
1345         set_gadget_data(gadget, NULL);
1346 }
1347
1348 static int __init
1349 printer_bind(struct usb_gadget *gadget)
1350 {
1351         struct printer_dev      *dev;
1352         struct usb_ep           *in_ep, *out_ep;
1353         int                     status = -ENOMEM;
1354         int                     gcnum;
1355         size_t                  len;
1356         u32                     i;
1357         struct usb_request      *req;
1358
1359         dev = &usb_printer_gadget;
1360
1361
1362         /* Setup the sysfs files for the printer gadget. */
1363         dev->pdev = device_create(usb_gadget_class, NULL, g_printer_devno,
1364                                   NULL, "g_printer");
1365         if (IS_ERR(dev->pdev)) {
1366                 ERROR(dev, "Failed to create device: g_printer\n");
1367                 goto fail;
1368         }
1369
1370         /*
1371          * Register a character device as an interface to a user mode
1372          * program that handles the printer specific functionality.
1373          */
1374         cdev_init(&dev->printer_cdev, &printer_io_operations);
1375         dev->printer_cdev.owner = THIS_MODULE;
1376         status = cdev_add(&dev->printer_cdev, g_printer_devno, 1);
1377         if (status) {
1378                 ERROR(dev, "Failed to open char device\n");
1379                 goto fail;
1380         }
1381
1382         gcnum = usb_gadget_controller_number(gadget);
1383         if (gcnum >= 0) {
1384                 device_desc.bcdDevice = cpu_to_le16(0x0200 + gcnum);
1385         } else {
1386                 dev_warn(&gadget->dev, "controller '%s' not recognized\n",
1387                         gadget->name);
1388                 /* unrecognized, but safe unless bulk is REALLY quirky */
1389                 device_desc.bcdDevice =
1390                         cpu_to_le16(0xFFFF);
1391         }
1392         snprintf(manufacturer, sizeof(manufacturer), "%s %s with %s",
1393                 init_utsname()->sysname, init_utsname()->release,
1394                 gadget->name);
1395
1396         device_desc.idVendor =
1397                 cpu_to_le16(PRINTER_VENDOR_NUM);
1398         device_desc.idProduct =
1399                 cpu_to_le16(PRINTER_PRODUCT_NUM);
1400
1401         /* support optional vendor/distro customization */
1402         if (idVendor) {
1403                 if (!idProduct) {
1404                         dev_err(&gadget->dev, "idVendor needs idProduct!\n");
1405                         return -ENODEV;
1406                 }
1407                 device_desc.idVendor = cpu_to_le16(idVendor);
1408                 device_desc.idProduct = cpu_to_le16(idProduct);
1409                 if (bcdDevice)
1410                         device_desc.bcdDevice = cpu_to_le16(bcdDevice);
1411         }
1412
1413         if (iManufacturer)
1414                 strlcpy(manufacturer, iManufacturer, sizeof manufacturer);
1415
1416         if (iProduct)
1417                 strlcpy(product_desc, iProduct, sizeof product_desc);
1418
1419         if (iSerialNum)
1420                 strlcpy(serial_num, iSerialNum, sizeof serial_num);
1421
1422         if (iPNPstring)
1423                 strlcpy(&pnp_string[2], iPNPstring, (sizeof pnp_string)-2);
1424
1425         len = strlen(pnp_string);
1426         pnp_string[0] = (len >> 8) & 0xFF;
1427         pnp_string[1] = len & 0xFF;
1428
1429         /* all we really need is bulk IN/OUT */
1430         usb_ep_autoconfig_reset(gadget);
1431         in_ep = usb_ep_autoconfig(gadget, &fs_ep_in_desc);
1432         if (!in_ep) {
1433 autoconf_fail:
1434                 dev_err(&gadget->dev, "can't autoconfigure on %s\n",
1435                         gadget->name);
1436                 return -ENODEV;
1437         }
1438         in_ep->driver_data = in_ep;     /* claim */
1439
1440         out_ep = usb_ep_autoconfig(gadget, &fs_ep_out_desc);
1441         if (!out_ep)
1442                 goto autoconf_fail;
1443         out_ep->driver_data = out_ep;   /* claim */
1444
1445 #ifdef  CONFIG_USB_GADGET_DUALSPEED
1446         /* assumes that all endpoints are dual-speed */
1447         hs_ep_in_desc.bEndpointAddress = fs_ep_in_desc.bEndpointAddress;
1448         hs_ep_out_desc.bEndpointAddress = fs_ep_out_desc.bEndpointAddress;
1449 #endif  /* DUALSPEED */
1450
1451         usb_gadget_set_selfpowered(gadget);
1452
1453         if (gadget->is_otg) {
1454                 otg_desc.bmAttributes |= USB_OTG_HNP,
1455                 config_desc.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
1456         }
1457
1458         spin_lock_init(&dev->lock);
1459         mutex_init(&dev->lock_printer_io);
1460         INIT_LIST_HEAD(&dev->tx_reqs);
1461         INIT_LIST_HEAD(&dev->tx_reqs_active);
1462         INIT_LIST_HEAD(&dev->rx_reqs);
1463         INIT_LIST_HEAD(&dev->rx_reqs_active);
1464         INIT_LIST_HEAD(&dev->rx_buffers);
1465         init_waitqueue_head(&dev->rx_wait);
1466         init_waitqueue_head(&dev->tx_wait);
1467         init_waitqueue_head(&dev->tx_flush_wait);
1468
1469         dev->config = 0;
1470         dev->interface = -1;
1471         dev->printer_cdev_open = 0;
1472         dev->printer_status = PRINTER_NOT_ERROR;
1473         dev->current_rx_req = NULL;
1474         dev->current_rx_bytes = 0;
1475         dev->current_rx_buf = NULL;
1476
1477         dev->in_ep = in_ep;
1478         dev->out_ep = out_ep;
1479
1480         /* preallocate control message data and buffer */
1481         dev->req = printer_req_alloc(gadget->ep0, USB_DESC_BUFSIZE,
1482                         GFP_KERNEL);
1483         if (!dev->req) {
1484                 status = -ENOMEM;
1485                 goto fail;
1486         }
1487
1488         for (i = 0; i < QLEN; i++) {
1489                 req = printer_req_alloc(dev->in_ep, USB_BUFSIZE, GFP_KERNEL);
1490                 if (!req) {
1491                         while (!list_empty(&dev->tx_reqs)) {
1492                                 req = container_of(dev->tx_reqs.next,
1493                                                 struct usb_request, list);
1494                                 list_del(&req->list);
1495                                 printer_req_free(dev->in_ep, req);
1496                         }
1497                         return -ENOMEM;
1498                 }
1499                 list_add(&req->list, &dev->tx_reqs);
1500         }
1501
1502         for (i = 0; i < QLEN; i++) {
1503                 req = printer_req_alloc(dev->out_ep, USB_BUFSIZE, GFP_KERNEL);
1504                 if (!req) {
1505                         while (!list_empty(&dev->rx_reqs)) {
1506                                 req = container_of(dev->rx_reqs.next,
1507                                                 struct usb_request, list);
1508                                 list_del(&req->list);
1509                                 printer_req_free(dev->out_ep, req);
1510                         }
1511                         return -ENOMEM;
1512                 }
1513                 list_add(&req->list, &dev->rx_reqs);
1514         }
1515
1516         dev->req->complete = printer_setup_complete;
1517
1518         /* finish hookup to lower layer ... */
1519         dev->gadget = gadget;
1520         set_gadget_data(gadget, dev);
1521         gadget->ep0->driver_data = dev;
1522
1523         INFO(dev, "%s, version: " DRIVER_VERSION "\n", driver_desc);
1524         INFO(dev, "using %s, OUT %s IN %s\n", gadget->name, out_ep->name,
1525                         in_ep->name);
1526
1527         return 0;
1528
1529 fail:
1530         printer_unbind(gadget);
1531         return status;
1532 }
1533
1534 /*-------------------------------------------------------------------------*/
1535
1536 static struct usb_gadget_driver printer_driver = {
1537         .max_speed      = DEVSPEED,
1538
1539         .function       = (char *) driver_desc,
1540         .unbind         = printer_unbind,
1541
1542         .setup          = printer_setup,
1543         .disconnect     = printer_disconnect,
1544
1545         .driver         = {
1546                 .name           = (char *) shortname,
1547                 .owner          = THIS_MODULE,
1548         },
1549 };
1550
1551 MODULE_DESCRIPTION(DRIVER_DESC);
1552 MODULE_AUTHOR("Craig Nadler");
1553 MODULE_LICENSE("GPL");
1554
1555 static int __init
1556 init(void)
1557 {
1558         int status;
1559
1560         usb_gadget_class = class_create(THIS_MODULE, "usb_printer_gadget");
1561         if (IS_ERR(usb_gadget_class)) {
1562                 status = PTR_ERR(usb_gadget_class);
1563                 ERROR(dev, "unable to create usb_gadget class %d\n", status);
1564                 return status;
1565         }
1566
1567         status = alloc_chrdev_region(&g_printer_devno, 0, 1,
1568                         "USB printer gadget");
1569         if (status) {
1570                 ERROR(dev, "alloc_chrdev_region %d\n", status);
1571                 class_destroy(usb_gadget_class);
1572                 return status;
1573         }
1574
1575         status = usb_gadget_probe_driver(&printer_driver, printer_bind);
1576         if (status) {
1577                 class_destroy(usb_gadget_class);
1578                 unregister_chrdev_region(g_printer_devno, 1);
1579                 DBG(dev, "usb_gadget_probe_driver %x\n", status);
1580         }
1581
1582         return status;
1583 }
1584 module_init(init);
1585
1586 static void __exit
1587 cleanup(void)
1588 {
1589         int status;
1590
1591         mutex_lock(&usb_printer_gadget.lock_printer_io);
1592         status = usb_gadget_unregister_driver(&printer_driver);
1593         if (status)
1594                 ERROR(dev, "usb_gadget_unregister_driver %x\n", status);
1595
1596         unregister_chrdev_region(g_printer_devno, 1);
1597         class_destroy(usb_gadget_class);
1598         mutex_unlock(&usb_printer_gadget.lock_printer_io);
1599 }
1600 module_exit(cleanup);