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