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