xref: /linux/drivers/usb/gadget/function/f_printer.c (revision e58e871becec2d3b04ed91c0c16fe8deac9c9dfa)
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 
559 	DBG(dev, "printer_write trying to send %d bytes\n", (int)len);
560 
561 	if (len == 0)
562 		return -EINVAL;
563 
564 	mutex_lock(&dev->lock_printer_io);
565 	spin_lock_irqsave(&dev->lock, flags);
566 
567 	/* Check if a printer reset happens while we have interrupts on */
568 	dev->reset_printer = 0;
569 
570 	/* Check if there is any available write buffers */
571 	if (likely(list_empty(&dev->tx_reqs))) {
572 		/* Turn interrupts back on before sleeping. */
573 		spin_unlock_irqrestore(&dev->lock, flags);
574 
575 		/*
576 		 * If write buffers are available check if this is
577 		 * a NON-Blocking call or not.
578 		 */
579 		if (fd->f_flags & (O_NONBLOCK|O_NDELAY)) {
580 			mutex_unlock(&dev->lock_printer_io);
581 			return -EAGAIN;
582 		}
583 
584 		/* Sleep until a write buffer is available */
585 		wait_event_interruptible(dev->tx_wait,
586 				(likely(!list_empty(&dev->tx_reqs))));
587 		spin_lock_irqsave(&dev->lock, flags);
588 	}
589 
590 	while (likely(!list_empty(&dev->tx_reqs)) && len) {
591 
592 		if (len > USB_BUFSIZE)
593 			size = USB_BUFSIZE;
594 		else
595 			size = len;
596 
597 		req = container_of(dev->tx_reqs.next, struct usb_request,
598 				list);
599 		list_del_init(&req->list);
600 
601 		req->complete = tx_complete;
602 		req->length = size;
603 
604 		/* Check if we need to send a zero length packet. */
605 		if (len > size)
606 			/* They will be more TX requests so no yet. */
607 			req->zero = 0;
608 		else
609 			/* If the data amount is not a multiple of the
610 			 * maxpacket size then send a zero length packet.
611 			 */
612 			req->zero = ((len % dev->in_ep->maxpacket) == 0);
613 
614 		/* Don't leave irqs off while doing memory copies */
615 		spin_unlock_irqrestore(&dev->lock, flags);
616 
617 		if (copy_from_user(req->buf, buf, size)) {
618 			list_add(&req->list, &dev->tx_reqs);
619 			mutex_unlock(&dev->lock_printer_io);
620 			return bytes_copied;
621 		}
622 
623 		bytes_copied += size;
624 		len -= size;
625 		buf += size;
626 
627 		spin_lock_irqsave(&dev->lock, flags);
628 
629 		/* We've disconnected or reset so free the req and buffer */
630 		if (dev->reset_printer) {
631 			list_add(&req->list, &dev->tx_reqs);
632 			spin_unlock_irqrestore(&dev->lock, flags);
633 			mutex_unlock(&dev->lock_printer_io);
634 			return -EAGAIN;
635 		}
636 
637 		if (usb_ep_queue(dev->in_ep, req, GFP_ATOMIC)) {
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 	}
647 
648 	spin_unlock_irqrestore(&dev->lock, flags);
649 	mutex_unlock(&dev->lock_printer_io);
650 
651 	DBG(dev, "printer_write sent %d bytes\n", (int)bytes_copied);
652 
653 	if (bytes_copied)
654 		return bytes_copied;
655 	else
656 		return -EAGAIN;
657 }
658 
659 static int
660 printer_fsync(struct file *fd, loff_t start, loff_t end, int datasync)
661 {
662 	struct printer_dev	*dev = fd->private_data;
663 	struct inode *inode = file_inode(fd);
664 	unsigned long		flags;
665 	int			tx_list_empty;
666 
667 	inode_lock(inode);
668 	spin_lock_irqsave(&dev->lock, flags);
669 	tx_list_empty = (likely(list_empty(&dev->tx_reqs)));
670 	spin_unlock_irqrestore(&dev->lock, flags);
671 
672 	if (!tx_list_empty) {
673 		/* Sleep until all data has been sent */
674 		wait_event_interruptible(dev->tx_flush_wait,
675 				(likely(list_empty(&dev->tx_reqs_active))));
676 	}
677 	inode_unlock(inode);
678 
679 	return 0;
680 }
681 
682 static unsigned int
683 printer_poll(struct file *fd, poll_table *wait)
684 {
685 	struct printer_dev	*dev = fd->private_data;
686 	unsigned long		flags;
687 	int			status = 0;
688 
689 	mutex_lock(&dev->lock_printer_io);
690 	spin_lock_irqsave(&dev->lock, flags);
691 	setup_rx_reqs(dev);
692 	spin_unlock_irqrestore(&dev->lock, flags);
693 	mutex_unlock(&dev->lock_printer_io);
694 
695 	poll_wait(fd, &dev->rx_wait, wait);
696 	poll_wait(fd, &dev->tx_wait, wait);
697 
698 	spin_lock_irqsave(&dev->lock, flags);
699 	if (likely(!list_empty(&dev->tx_reqs)))
700 		status |= POLLOUT | POLLWRNORM;
701 
702 	if (likely(dev->current_rx_bytes) ||
703 			likely(!list_empty(&dev->rx_buffers)))
704 		status |= POLLIN | POLLRDNORM;
705 
706 	spin_unlock_irqrestore(&dev->lock, flags);
707 
708 	return status;
709 }
710 
711 static long
712 printer_ioctl(struct file *fd, unsigned int code, unsigned long arg)
713 {
714 	struct printer_dev	*dev = fd->private_data;
715 	unsigned long		flags;
716 	int			status = 0;
717 
718 	DBG(dev, "printer_ioctl: cmd=0x%4.4x, arg=%lu\n", code, arg);
719 
720 	/* handle ioctls */
721 
722 	spin_lock_irqsave(&dev->lock, flags);
723 
724 	switch (code) {
725 	case GADGET_GET_PRINTER_STATUS:
726 		status = (int)dev->printer_status;
727 		break;
728 	case GADGET_SET_PRINTER_STATUS:
729 		dev->printer_status = (u8)arg;
730 		break;
731 	default:
732 		/* could not handle ioctl */
733 		DBG(dev, "printer_ioctl: ERROR cmd=0x%4.4xis not supported\n",
734 				code);
735 		status = -ENOTTY;
736 	}
737 
738 	spin_unlock_irqrestore(&dev->lock, flags);
739 
740 	return status;
741 }
742 
743 /* used after endpoint configuration */
744 static const struct file_operations printer_io_operations = {
745 	.owner =	THIS_MODULE,
746 	.open =		printer_open,
747 	.read =		printer_read,
748 	.write =	printer_write,
749 	.fsync =	printer_fsync,
750 	.poll =		printer_poll,
751 	.unlocked_ioctl = printer_ioctl,
752 	.release =	printer_close,
753 	.llseek =	noop_llseek,
754 };
755 
756 /*-------------------------------------------------------------------------*/
757 
758 static int
759 set_printer_interface(struct printer_dev *dev)
760 {
761 	int			result = 0;
762 
763 	dev->in_ep->desc = ep_desc(dev->gadget, &fs_ep_in_desc, &hs_ep_in_desc,
764 				&ss_ep_in_desc);
765 	dev->in_ep->driver_data = dev;
766 
767 	dev->out_ep->desc = ep_desc(dev->gadget, &fs_ep_out_desc,
768 				    &hs_ep_out_desc, &ss_ep_out_desc);
769 	dev->out_ep->driver_data = dev;
770 
771 	result = usb_ep_enable(dev->in_ep);
772 	if (result != 0) {
773 		DBG(dev, "enable %s --> %d\n", dev->in_ep->name, result);
774 		goto done;
775 	}
776 
777 	result = usb_ep_enable(dev->out_ep);
778 	if (result != 0) {
779 		DBG(dev, "enable %s --> %d\n", dev->in_ep->name, result);
780 		goto done;
781 	}
782 
783 done:
784 	/* on error, disable any endpoints  */
785 	if (result != 0) {
786 		(void) usb_ep_disable(dev->in_ep);
787 		(void) usb_ep_disable(dev->out_ep);
788 		dev->in_ep->desc = NULL;
789 		dev->out_ep->desc = NULL;
790 	}
791 
792 	/* caller is responsible for cleanup on error */
793 	return result;
794 }
795 
796 static void printer_reset_interface(struct printer_dev *dev)
797 {
798 	unsigned long	flags;
799 
800 	if (dev->interface < 0)
801 		return;
802 
803 	DBG(dev, "%s\n", __func__);
804 
805 	if (dev->in_ep->desc)
806 		usb_ep_disable(dev->in_ep);
807 
808 	if (dev->out_ep->desc)
809 		usb_ep_disable(dev->out_ep);
810 
811 	spin_lock_irqsave(&dev->lock, flags);
812 	dev->in_ep->desc = NULL;
813 	dev->out_ep->desc = NULL;
814 	dev->interface = -1;
815 	spin_unlock_irqrestore(&dev->lock, flags);
816 }
817 
818 /* Change our operational Interface. */
819 static int set_interface(struct printer_dev *dev, unsigned number)
820 {
821 	int			result = 0;
822 
823 	/* Free the current interface */
824 	printer_reset_interface(dev);
825 
826 	result = set_printer_interface(dev);
827 	if (result)
828 		printer_reset_interface(dev);
829 	else
830 		dev->interface = number;
831 
832 	if (!result)
833 		INFO(dev, "Using interface %x\n", number);
834 
835 	return result;
836 }
837 
838 static void printer_soft_reset(struct printer_dev *dev)
839 {
840 	struct usb_request	*req;
841 
842 	INFO(dev, "Received Printer Reset Request\n");
843 
844 	if (usb_ep_disable(dev->in_ep))
845 		DBG(dev, "Failed to disable USB in_ep\n");
846 	if (usb_ep_disable(dev->out_ep))
847 		DBG(dev, "Failed to disable USB out_ep\n");
848 
849 	if (dev->current_rx_req != NULL) {
850 		list_add(&dev->current_rx_req->list, &dev->rx_reqs);
851 		dev->current_rx_req = NULL;
852 	}
853 	dev->current_rx_bytes = 0;
854 	dev->current_rx_buf = NULL;
855 	dev->reset_printer = 1;
856 
857 	while (likely(!(list_empty(&dev->rx_buffers)))) {
858 		req = container_of(dev->rx_buffers.next, struct usb_request,
859 				list);
860 		list_del_init(&req->list);
861 		list_add(&req->list, &dev->rx_reqs);
862 	}
863 
864 	while (likely(!(list_empty(&dev->rx_reqs_active)))) {
865 		req = container_of(dev->rx_buffers.next, struct usb_request,
866 				list);
867 		list_del_init(&req->list);
868 		list_add(&req->list, &dev->rx_reqs);
869 	}
870 
871 	while (likely(!(list_empty(&dev->tx_reqs_active)))) {
872 		req = container_of(dev->tx_reqs_active.next,
873 				struct usb_request, list);
874 		list_del_init(&req->list);
875 		list_add(&req->list, &dev->tx_reqs);
876 	}
877 
878 	if (usb_ep_enable(dev->in_ep))
879 		DBG(dev, "Failed to enable USB in_ep\n");
880 	if (usb_ep_enable(dev->out_ep))
881 		DBG(dev, "Failed to enable USB out_ep\n");
882 
883 	wake_up_interruptible(&dev->rx_wait);
884 	wake_up_interruptible(&dev->tx_wait);
885 	wake_up_interruptible(&dev->tx_flush_wait);
886 }
887 
888 /*-------------------------------------------------------------------------*/
889 
890 static bool gprinter_req_match(struct usb_function *f,
891 			       const struct usb_ctrlrequest *ctrl,
892 			       bool config0)
893 {
894 	struct printer_dev	*dev = func_to_printer(f);
895 	u16			w_index = le16_to_cpu(ctrl->wIndex);
896 	u16			w_value = le16_to_cpu(ctrl->wValue);
897 	u16			w_length = le16_to_cpu(ctrl->wLength);
898 
899 	if (config0)
900 		return false;
901 
902 	if ((ctrl->bRequestType & USB_RECIP_MASK) != USB_RECIP_INTERFACE ||
903 	    (ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_CLASS)
904 		return false;
905 
906 	switch (ctrl->bRequest) {
907 	case GET_DEVICE_ID:
908 		w_index >>= 8;
909 		if (USB_DIR_IN & ctrl->bRequestType)
910 			break;
911 		return false;
912 	case GET_PORT_STATUS:
913 		if (!w_value && w_length == 1 &&
914 		    (USB_DIR_IN & ctrl->bRequestType))
915 			break;
916 		return false;
917 	case SOFT_RESET:
918 		if (!w_value && !w_length &&
919 		   !(USB_DIR_IN & ctrl->bRequestType))
920 			break;
921 		/* fall through */
922 	default:
923 		return false;
924 	}
925 	return w_index == dev->interface;
926 }
927 
928 /*
929  * The setup() callback implements all the ep0 functionality that's not
930  * handled lower down.
931  */
932 static int printer_func_setup(struct usb_function *f,
933 		const struct usb_ctrlrequest *ctrl)
934 {
935 	struct printer_dev *dev = func_to_printer(f);
936 	struct usb_composite_dev *cdev = f->config->cdev;
937 	struct usb_request	*req = cdev->req;
938 	u8			*buf = req->buf;
939 	int			value = -EOPNOTSUPP;
940 	u16			wIndex = le16_to_cpu(ctrl->wIndex);
941 	u16			wValue = le16_to_cpu(ctrl->wValue);
942 	u16			wLength = le16_to_cpu(ctrl->wLength);
943 
944 	DBG(dev, "ctrl req%02x.%02x v%04x i%04x l%d\n",
945 		ctrl->bRequestType, ctrl->bRequest, wValue, wIndex, wLength);
946 
947 	switch (ctrl->bRequestType&USB_TYPE_MASK) {
948 	case USB_TYPE_CLASS:
949 		switch (ctrl->bRequest) {
950 		case GET_DEVICE_ID: /* Get the IEEE-1284 PNP String */
951 			/* Only one printer interface is supported. */
952 			if ((wIndex>>8) != dev->interface)
953 				break;
954 
955 			if (!dev->pnp_string) {
956 				value = 0;
957 				break;
958 			}
959 			value = strlen(dev->pnp_string);
960 			buf[0] = (value >> 8) & 0xFF;
961 			buf[1] = value & 0xFF;
962 			memcpy(buf + 2, dev->pnp_string, value);
963 			DBG(dev, "1284 PNP String: %x %s\n", value,
964 			    dev->pnp_string);
965 			break;
966 
967 		case GET_PORT_STATUS: /* Get Port Status */
968 			/* Only one printer interface is supported. */
969 			if (wIndex != dev->interface)
970 				break;
971 
972 			buf[0] = dev->printer_status;
973 			value = min_t(u16, wLength, 1);
974 			break;
975 
976 		case SOFT_RESET: /* Soft Reset */
977 			/* Only one printer interface is supported. */
978 			if (wIndex != dev->interface)
979 				break;
980 
981 			printer_soft_reset(dev);
982 
983 			value = 0;
984 			break;
985 
986 		default:
987 			goto unknown;
988 		}
989 		break;
990 
991 	default:
992 unknown:
993 		VDBG(dev,
994 			"unknown ctrl req%02x.%02x v%04x i%04x l%d\n",
995 			ctrl->bRequestType, ctrl->bRequest,
996 			wValue, wIndex, wLength);
997 		break;
998 	}
999 	/* host either stalls (value < 0) or reports success */
1000 	if (value >= 0) {
1001 		req->length = value;
1002 		req->zero = value < wLength;
1003 		value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1004 		if (value < 0) {
1005 			ERROR(dev, "%s:%d Error!\n", __func__, __LINE__);
1006 			req->status = 0;
1007 		}
1008 	}
1009 	return value;
1010 }
1011 
1012 static int printer_func_bind(struct usb_configuration *c,
1013 		struct usb_function *f)
1014 {
1015 	struct usb_gadget *gadget = c->cdev->gadget;
1016 	struct printer_dev *dev = func_to_printer(f);
1017 	struct device *pdev;
1018 	struct usb_composite_dev *cdev = c->cdev;
1019 	struct usb_ep *in_ep;
1020 	struct usb_ep *out_ep = NULL;
1021 	struct usb_request *req;
1022 	dev_t devt;
1023 	int id;
1024 	int ret;
1025 	u32 i;
1026 
1027 	id = usb_interface_id(c, f);
1028 	if (id < 0)
1029 		return id;
1030 	intf_desc.bInterfaceNumber = id;
1031 
1032 	/* finish hookup to lower layer ... */
1033 	dev->gadget = gadget;
1034 
1035 	/* all we really need is bulk IN/OUT */
1036 	in_ep = usb_ep_autoconfig(cdev->gadget, &fs_ep_in_desc);
1037 	if (!in_ep) {
1038 autoconf_fail:
1039 		dev_err(&cdev->gadget->dev, "can't autoconfigure on %s\n",
1040 			cdev->gadget->name);
1041 		return -ENODEV;
1042 	}
1043 
1044 	out_ep = usb_ep_autoconfig(cdev->gadget, &fs_ep_out_desc);
1045 	if (!out_ep)
1046 		goto autoconf_fail;
1047 
1048 	/* assumes that all endpoints are dual-speed */
1049 	hs_ep_in_desc.bEndpointAddress = fs_ep_in_desc.bEndpointAddress;
1050 	hs_ep_out_desc.bEndpointAddress = fs_ep_out_desc.bEndpointAddress;
1051 	ss_ep_in_desc.bEndpointAddress = fs_ep_in_desc.bEndpointAddress;
1052 	ss_ep_out_desc.bEndpointAddress = fs_ep_out_desc.bEndpointAddress;
1053 
1054 	ret = usb_assign_descriptors(f, fs_printer_function,
1055 			hs_printer_function, ss_printer_function, NULL);
1056 	if (ret)
1057 		return ret;
1058 
1059 	dev->in_ep = in_ep;
1060 	dev->out_ep = out_ep;
1061 
1062 	ret = -ENOMEM;
1063 	for (i = 0; i < dev->q_len; i++) {
1064 		req = printer_req_alloc(dev->in_ep, USB_BUFSIZE, GFP_KERNEL);
1065 		if (!req)
1066 			goto fail_tx_reqs;
1067 		list_add(&req->list, &dev->tx_reqs);
1068 	}
1069 
1070 	for (i = 0; i < dev->q_len; i++) {
1071 		req = printer_req_alloc(dev->out_ep, USB_BUFSIZE, GFP_KERNEL);
1072 		if (!req)
1073 			goto fail_rx_reqs;
1074 		list_add(&req->list, &dev->rx_reqs);
1075 	}
1076 
1077 	/* Setup the sysfs files for the printer gadget. */
1078 	devt = MKDEV(major, dev->minor);
1079 	pdev = device_create(usb_gadget_class, NULL, devt,
1080 				  NULL, "g_printer%d", dev->minor);
1081 	if (IS_ERR(pdev)) {
1082 		ERROR(dev, "Failed to create device: g_printer\n");
1083 		ret = PTR_ERR(pdev);
1084 		goto fail_rx_reqs;
1085 	}
1086 
1087 	/*
1088 	 * Register a character device as an interface to a user mode
1089 	 * program that handles the printer specific functionality.
1090 	 */
1091 	cdev_init(&dev->printer_cdev, &printer_io_operations);
1092 	dev->printer_cdev.owner = THIS_MODULE;
1093 	ret = cdev_add(&dev->printer_cdev, devt, 1);
1094 	if (ret) {
1095 		ERROR(dev, "Failed to open char device\n");
1096 		goto fail_cdev_add;
1097 	}
1098 
1099 	return 0;
1100 
1101 fail_cdev_add:
1102 	device_destroy(usb_gadget_class, devt);
1103 
1104 fail_rx_reqs:
1105 	while (!list_empty(&dev->rx_reqs)) {
1106 		req = container_of(dev->rx_reqs.next, struct usb_request, list);
1107 		list_del(&req->list);
1108 		printer_req_free(dev->out_ep, req);
1109 	}
1110 
1111 fail_tx_reqs:
1112 	while (!list_empty(&dev->tx_reqs)) {
1113 		req = container_of(dev->tx_reqs.next, struct usb_request, list);
1114 		list_del(&req->list);
1115 		printer_req_free(dev->in_ep, req);
1116 	}
1117 
1118 	return ret;
1119 
1120 }
1121 
1122 static int printer_func_set_alt(struct usb_function *f,
1123 		unsigned intf, unsigned alt)
1124 {
1125 	struct printer_dev *dev = func_to_printer(f);
1126 	int ret = -ENOTSUPP;
1127 
1128 	if (!alt)
1129 		ret = set_interface(dev, intf);
1130 
1131 	return ret;
1132 }
1133 
1134 static void printer_func_disable(struct usb_function *f)
1135 {
1136 	struct printer_dev *dev = func_to_printer(f);
1137 
1138 	DBG(dev, "%s\n", __func__);
1139 
1140 	printer_reset_interface(dev);
1141 }
1142 
1143 static inline struct f_printer_opts
1144 *to_f_printer_opts(struct config_item *item)
1145 {
1146 	return container_of(to_config_group(item), struct f_printer_opts,
1147 			    func_inst.group);
1148 }
1149 
1150 static void printer_attr_release(struct config_item *item)
1151 {
1152 	struct f_printer_opts *opts = to_f_printer_opts(item);
1153 
1154 	usb_put_function_instance(&opts->func_inst);
1155 }
1156 
1157 static struct configfs_item_operations printer_item_ops = {
1158 	.release	= printer_attr_release,
1159 };
1160 
1161 static ssize_t f_printer_opts_pnp_string_show(struct config_item *item,
1162 					      char *page)
1163 {
1164 	struct f_printer_opts *opts = to_f_printer_opts(item);
1165 	int result = 0;
1166 
1167 	mutex_lock(&opts->lock);
1168 	if (!opts->pnp_string)
1169 		goto unlock;
1170 
1171 	result = strlcpy(page, opts->pnp_string, PAGE_SIZE);
1172 	if (result >= PAGE_SIZE) {
1173 		result = PAGE_SIZE;
1174 	} else if (page[result - 1] != '\n' && result + 1 < PAGE_SIZE) {
1175 		page[result++] = '\n';
1176 		page[result] = '\0';
1177 	}
1178 
1179 unlock:
1180 	mutex_unlock(&opts->lock);
1181 
1182 	return result;
1183 }
1184 
1185 static ssize_t f_printer_opts_pnp_string_store(struct config_item *item,
1186 					       const char *page, size_t len)
1187 {
1188 	struct f_printer_opts *opts = to_f_printer_opts(item);
1189 	char *new_pnp;
1190 	int result;
1191 
1192 	mutex_lock(&opts->lock);
1193 
1194 	new_pnp = kstrndup(page, len, GFP_KERNEL);
1195 	if (!new_pnp) {
1196 		result = -ENOMEM;
1197 		goto unlock;
1198 	}
1199 
1200 	if (opts->pnp_string_allocated)
1201 		kfree(opts->pnp_string);
1202 
1203 	opts->pnp_string_allocated = true;
1204 	opts->pnp_string = new_pnp;
1205 	result = len;
1206 unlock:
1207 	mutex_unlock(&opts->lock);
1208 
1209 	return result;
1210 }
1211 
1212 CONFIGFS_ATTR(f_printer_opts_, pnp_string);
1213 
1214 static ssize_t f_printer_opts_q_len_show(struct config_item *item,
1215 					 char *page)
1216 {
1217 	struct f_printer_opts *opts = to_f_printer_opts(item);
1218 	int result;
1219 
1220 	mutex_lock(&opts->lock);
1221 	result = sprintf(page, "%d\n", opts->q_len);
1222 	mutex_unlock(&opts->lock);
1223 
1224 	return result;
1225 }
1226 
1227 static ssize_t f_printer_opts_q_len_store(struct config_item *item,
1228 					  const char *page, size_t len)
1229 {
1230 	struct f_printer_opts *opts = to_f_printer_opts(item);
1231 	int ret;
1232 	u16 num;
1233 
1234 	mutex_lock(&opts->lock);
1235 	if (opts->refcnt) {
1236 		ret = -EBUSY;
1237 		goto end;
1238 	}
1239 
1240 	ret = kstrtou16(page, 0, &num);
1241 	if (ret)
1242 		goto end;
1243 
1244 	opts->q_len = (unsigned)num;
1245 	ret = len;
1246 end:
1247 	mutex_unlock(&opts->lock);
1248 	return ret;
1249 }
1250 
1251 CONFIGFS_ATTR(f_printer_opts_, q_len);
1252 
1253 static struct configfs_attribute *printer_attrs[] = {
1254 	&f_printer_opts_attr_pnp_string,
1255 	&f_printer_opts_attr_q_len,
1256 	NULL,
1257 };
1258 
1259 static struct config_item_type printer_func_type = {
1260 	.ct_item_ops	= &printer_item_ops,
1261 	.ct_attrs	= printer_attrs,
1262 	.ct_owner	= THIS_MODULE,
1263 };
1264 
1265 static inline int gprinter_get_minor(void)
1266 {
1267 	int ret;
1268 
1269 	ret = ida_simple_get(&printer_ida, 0, 0, GFP_KERNEL);
1270 	if (ret >= PRINTER_MINORS) {
1271 		ida_simple_remove(&printer_ida, ret);
1272 		ret = -ENODEV;
1273 	}
1274 
1275 	return ret;
1276 }
1277 
1278 static inline void gprinter_put_minor(int minor)
1279 {
1280 	ida_simple_remove(&printer_ida, minor);
1281 }
1282 
1283 static int gprinter_setup(int);
1284 static void gprinter_cleanup(void);
1285 
1286 static void gprinter_free_inst(struct usb_function_instance *f)
1287 {
1288 	struct f_printer_opts *opts;
1289 
1290 	opts = container_of(f, struct f_printer_opts, func_inst);
1291 
1292 	mutex_lock(&printer_ida_lock);
1293 
1294 	gprinter_put_minor(opts->minor);
1295 	if (ida_is_empty(&printer_ida))
1296 		gprinter_cleanup();
1297 
1298 	mutex_unlock(&printer_ida_lock);
1299 
1300 	if (opts->pnp_string_allocated)
1301 		kfree(opts->pnp_string);
1302 	kfree(opts);
1303 }
1304 
1305 static struct usb_function_instance *gprinter_alloc_inst(void)
1306 {
1307 	struct f_printer_opts *opts;
1308 	struct usb_function_instance *ret;
1309 	int status = 0;
1310 
1311 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1312 	if (!opts)
1313 		return ERR_PTR(-ENOMEM);
1314 
1315 	mutex_init(&opts->lock);
1316 	opts->func_inst.free_func_inst = gprinter_free_inst;
1317 	ret = &opts->func_inst;
1318 
1319 	mutex_lock(&printer_ida_lock);
1320 
1321 	if (ida_is_empty(&printer_ida)) {
1322 		status = gprinter_setup(PRINTER_MINORS);
1323 		if (status) {
1324 			ret = ERR_PTR(status);
1325 			kfree(opts);
1326 			goto unlock;
1327 		}
1328 	}
1329 
1330 	opts->minor = gprinter_get_minor();
1331 	if (opts->minor < 0) {
1332 		ret = ERR_PTR(opts->minor);
1333 		kfree(opts);
1334 		if (ida_is_empty(&printer_ida))
1335 			gprinter_cleanup();
1336 		goto unlock;
1337 	}
1338 	config_group_init_type_name(&opts->func_inst.group, "",
1339 				    &printer_func_type);
1340 
1341 unlock:
1342 	mutex_unlock(&printer_ida_lock);
1343 	return ret;
1344 }
1345 
1346 static void gprinter_free(struct usb_function *f)
1347 {
1348 	struct printer_dev *dev = func_to_printer(f);
1349 	struct f_printer_opts *opts;
1350 
1351 	opts = container_of(f->fi, struct f_printer_opts, func_inst);
1352 	kfree(dev);
1353 	mutex_lock(&opts->lock);
1354 	--opts->refcnt;
1355 	mutex_unlock(&opts->lock);
1356 }
1357 
1358 static void printer_func_unbind(struct usb_configuration *c,
1359 		struct usb_function *f)
1360 {
1361 	struct printer_dev	*dev;
1362 	struct usb_request	*req;
1363 
1364 	dev = func_to_printer(f);
1365 
1366 	device_destroy(usb_gadget_class, MKDEV(major, dev->minor));
1367 
1368 	/* Remove Character Device */
1369 	cdev_del(&dev->printer_cdev);
1370 
1371 	/* we must already have been disconnected ... no i/o may be active */
1372 	WARN_ON(!list_empty(&dev->tx_reqs_active));
1373 	WARN_ON(!list_empty(&dev->rx_reqs_active));
1374 
1375 	/* Free all memory for this driver. */
1376 	while (!list_empty(&dev->tx_reqs)) {
1377 		req = container_of(dev->tx_reqs.next, struct usb_request,
1378 				list);
1379 		list_del(&req->list);
1380 		printer_req_free(dev->in_ep, req);
1381 	}
1382 
1383 	if (dev->current_rx_req != NULL)
1384 		printer_req_free(dev->out_ep, dev->current_rx_req);
1385 
1386 	while (!list_empty(&dev->rx_reqs)) {
1387 		req = container_of(dev->rx_reqs.next,
1388 				struct usb_request, list);
1389 		list_del(&req->list);
1390 		printer_req_free(dev->out_ep, req);
1391 	}
1392 
1393 	while (!list_empty(&dev->rx_buffers)) {
1394 		req = container_of(dev->rx_buffers.next,
1395 				struct usb_request, list);
1396 		list_del(&req->list);
1397 		printer_req_free(dev->out_ep, req);
1398 	}
1399 	usb_free_all_descriptors(f);
1400 }
1401 
1402 static struct usb_function *gprinter_alloc(struct usb_function_instance *fi)
1403 {
1404 	struct printer_dev	*dev;
1405 	struct f_printer_opts	*opts;
1406 
1407 	opts = container_of(fi, struct f_printer_opts, func_inst);
1408 
1409 	mutex_lock(&opts->lock);
1410 	if (opts->minor >= minors) {
1411 		mutex_unlock(&opts->lock);
1412 		return ERR_PTR(-ENOENT);
1413 	}
1414 
1415 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1416 	if (!dev) {
1417 		mutex_unlock(&opts->lock);
1418 		return ERR_PTR(-ENOMEM);
1419 	}
1420 
1421 	++opts->refcnt;
1422 	dev->minor = opts->minor;
1423 	dev->pnp_string = opts->pnp_string;
1424 	dev->q_len = opts->q_len;
1425 	mutex_unlock(&opts->lock);
1426 
1427 	dev->function.name = "printer";
1428 	dev->function.bind = printer_func_bind;
1429 	dev->function.setup = printer_func_setup;
1430 	dev->function.unbind = printer_func_unbind;
1431 	dev->function.set_alt = printer_func_set_alt;
1432 	dev->function.disable = printer_func_disable;
1433 	dev->function.req_match = gprinter_req_match;
1434 	dev->function.free_func = gprinter_free;
1435 
1436 	INIT_LIST_HEAD(&dev->tx_reqs);
1437 	INIT_LIST_HEAD(&dev->rx_reqs);
1438 	INIT_LIST_HEAD(&dev->rx_buffers);
1439 	INIT_LIST_HEAD(&dev->tx_reqs_active);
1440 	INIT_LIST_HEAD(&dev->rx_reqs_active);
1441 
1442 	spin_lock_init(&dev->lock);
1443 	mutex_init(&dev->lock_printer_io);
1444 	init_waitqueue_head(&dev->rx_wait);
1445 	init_waitqueue_head(&dev->tx_wait);
1446 	init_waitqueue_head(&dev->tx_flush_wait);
1447 
1448 	dev->interface = -1;
1449 	dev->printer_cdev_open = 0;
1450 	dev->printer_status = PRINTER_NOT_ERROR;
1451 	dev->current_rx_req = NULL;
1452 	dev->current_rx_bytes = 0;
1453 	dev->current_rx_buf = NULL;
1454 
1455 	return &dev->function;
1456 }
1457 
1458 DECLARE_USB_FUNCTION_INIT(printer, gprinter_alloc_inst, gprinter_alloc);
1459 MODULE_LICENSE("GPL");
1460 MODULE_AUTHOR("Craig Nadler");
1461 
1462 static int gprinter_setup(int count)
1463 {
1464 	int status;
1465 	dev_t devt;
1466 
1467 	usb_gadget_class = class_create(THIS_MODULE, "usb_printer_gadget");
1468 	if (IS_ERR(usb_gadget_class)) {
1469 		status = PTR_ERR(usb_gadget_class);
1470 		usb_gadget_class = NULL;
1471 		pr_err("unable to create usb_gadget class %d\n", status);
1472 		return status;
1473 	}
1474 
1475 	status = alloc_chrdev_region(&devt, 0, count, "USB printer gadget");
1476 	if (status) {
1477 		pr_err("alloc_chrdev_region %d\n", status);
1478 		class_destroy(usb_gadget_class);
1479 		usb_gadget_class = NULL;
1480 		return status;
1481 	}
1482 
1483 	major = MAJOR(devt);
1484 	minors = count;
1485 
1486 	return status;
1487 }
1488 
1489 static void gprinter_cleanup(void)
1490 {
1491 	if (major) {
1492 		unregister_chrdev_region(MKDEV(major, 0), minors);
1493 		major = minors = 0;
1494 	}
1495 	class_destroy(usb_gadget_class);
1496 	usb_gadget_class = NULL;
1497 }
1498