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