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