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