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