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