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