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