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