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