1 /*
2  * printer.c -- Printer gadget driver
3  *
4  * Copyright (C) 2003-2005 David Brownell
5  * Copyright (C) 2006 Craig W. Nadler
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  */
12 
13 #include <linux/module.h>
14 #include <linux/kernel.h>
15 #include <linux/delay.h>
16 #include <linux/ioport.h>
17 #include <linux/sched.h>
18 #include <linux/slab.h>
19 #include <linux/mutex.h>
20 #include <linux/errno.h>
21 #include <linux/init.h>
22 #include <linux/timer.h>
23 #include <linux/list.h>
24 #include <linux/interrupt.h>
25 #include <linux/device.h>
26 #include <linux/moduleparam.h>
27 #include <linux/fs.h>
28 #include <linux/poll.h>
29 #include <linux/types.h>
30 #include <linux/ctype.h>
31 #include <linux/cdev.h>
32 
33 #include <asm/byteorder.h>
34 #include <linux/io.h>
35 #include <linux/irq.h>
36 #include <linux/uaccess.h>
37 #include <asm/unaligned.h>
38 
39 #include <linux/usb/ch9.h>
40 #include <linux/usb/composite.h>
41 #include <linux/usb/gadget.h>
42 #include <linux/usb/g_printer.h>
43 
44 #include "gadget_chips.h"
45 
46 USB_GADGET_COMPOSITE_OPTIONS();
47 
48 #define DRIVER_DESC		"Printer Gadget"
49 #define DRIVER_VERSION		"2007 OCT 06"
50 
51 static DEFINE_MUTEX(printer_mutex);
52 static const char shortname [] = "printer";
53 static const char driver_desc [] = DRIVER_DESC;
54 
55 static dev_t g_printer_devno;
56 
57 static struct class *usb_gadget_class;
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 
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 	struct cdev		printer_cdev;
86 	struct device		*pdev;
87 	u8			printer_cdev_open;
88 	wait_queue_head_t	wait;
89 	struct usb_function	function;
90 };
91 
92 static struct printer_dev usb_printer_gadget;
93 
94 /*-------------------------------------------------------------------------*/
95 
96 /* DO NOT REUSE THESE IDs with a protocol-incompatible driver!!  Ever!!
97  * Instead:  allocate your own, using normal USB-IF procedures.
98  */
99 
100 /* Thanks to NetChip Technologies for donating this product ID.
101  */
102 #define PRINTER_VENDOR_NUM	0x0525		/* NetChip */
103 #define PRINTER_PRODUCT_NUM	0xa4a8		/* Linux-USB Printer Gadget */
104 
105 /* Some systems will want different product identifiers published in the
106  * device descriptor, either numbers or strings or both.  These string
107  * parameters are in UTF-8 (superset of ASCII's 7 bit characters).
108  */
109 
110 module_param_named(iSerialNum, coverwrite.serial_number, charp, S_IRUGO);
111 MODULE_PARM_DESC(iSerialNum, "1");
112 
113 static char *iPNPstring;
114 module_param(iPNPstring, charp, S_IRUGO);
115 MODULE_PARM_DESC(iPNPstring, "MFG:linux;MDL:g_printer;CLS:PRINTER;SN:1;");
116 
117 /* Number of requests to allocate per endpoint, not used for ep0. */
118 static unsigned qlen = 10;
119 module_param(qlen, uint, S_IRUGO|S_IWUSR);
120 
121 #define QLEN	qlen
122 
123 /*-------------------------------------------------------------------------*/
124 
125 /*
126  * DESCRIPTORS ... most are static, but strings and (full) configuration
127  * descriptors are built on demand.
128  */
129 
130 /* holds our biggest descriptor */
131 #define USB_DESC_BUFSIZE		256
132 #define USB_BUFSIZE			8192
133 
134 static struct usb_device_descriptor device_desc = {
135 	.bLength =		sizeof device_desc,
136 	.bDescriptorType =	USB_DT_DEVICE,
137 	.bcdUSB =		cpu_to_le16(0x0200),
138 	.bDeviceClass =		USB_CLASS_PER_INTERFACE,
139 	.bDeviceSubClass =	0,
140 	.bDeviceProtocol =	0,
141 	.idVendor =		cpu_to_le16(PRINTER_VENDOR_NUM),
142 	.idProduct =		cpu_to_le16(PRINTER_PRODUCT_NUM),
143 	.bNumConfigurations =	1
144 };
145 
146 static struct usb_interface_descriptor intf_desc = {
147 	.bLength =		sizeof intf_desc,
148 	.bDescriptorType =	USB_DT_INTERFACE,
149 	.bNumEndpoints =	2,
150 	.bInterfaceClass =	USB_CLASS_PRINTER,
151 	.bInterfaceSubClass =	1,	/* Printer Sub-Class */
152 	.bInterfaceProtocol =	2,	/* Bi-Directional */
153 	.iInterface =		0
154 };
155 
156 static struct usb_endpoint_descriptor fs_ep_in_desc = {
157 	.bLength =		USB_DT_ENDPOINT_SIZE,
158 	.bDescriptorType =	USB_DT_ENDPOINT,
159 	.bEndpointAddress =	USB_DIR_IN,
160 	.bmAttributes =		USB_ENDPOINT_XFER_BULK
161 };
162 
163 static struct usb_endpoint_descriptor fs_ep_out_desc = {
164 	.bLength =		USB_DT_ENDPOINT_SIZE,
165 	.bDescriptorType =	USB_DT_ENDPOINT,
166 	.bEndpointAddress =	USB_DIR_OUT,
167 	.bmAttributes =		USB_ENDPOINT_XFER_BULK
168 };
169 
170 static struct usb_descriptor_header *fs_printer_function[] = {
171 	(struct usb_descriptor_header *) &intf_desc,
172 	(struct usb_descriptor_header *) &fs_ep_in_desc,
173 	(struct usb_descriptor_header *) &fs_ep_out_desc,
174 	NULL
175 };
176 
177 /*
178  * usb 2.0 devices need to expose both high speed and full speed
179  * descriptors, unless they only run at full speed.
180  */
181 
182 static struct usb_endpoint_descriptor hs_ep_in_desc = {
183 	.bLength =		USB_DT_ENDPOINT_SIZE,
184 	.bDescriptorType =	USB_DT_ENDPOINT,
185 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
186 	.wMaxPacketSize =	cpu_to_le16(512)
187 };
188 
189 static struct usb_endpoint_descriptor hs_ep_out_desc = {
190 	.bLength =		USB_DT_ENDPOINT_SIZE,
191 	.bDescriptorType =	USB_DT_ENDPOINT,
192 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
193 	.wMaxPacketSize =	cpu_to_le16(512)
194 };
195 
196 static struct usb_qualifier_descriptor dev_qualifier = {
197 	.bLength =		sizeof dev_qualifier,
198 	.bDescriptorType =	USB_DT_DEVICE_QUALIFIER,
199 	.bcdUSB =		cpu_to_le16(0x0200),
200 	.bDeviceClass =		USB_CLASS_PRINTER,
201 	.bNumConfigurations =	1
202 };
203 
204 static struct usb_descriptor_header *hs_printer_function[] = {
205 	(struct usb_descriptor_header *) &intf_desc,
206 	(struct usb_descriptor_header *) &hs_ep_in_desc,
207 	(struct usb_descriptor_header *) &hs_ep_out_desc,
208 	NULL
209 };
210 
211 static struct usb_otg_descriptor otg_descriptor = {
212 	.bLength =              sizeof otg_descriptor,
213 	.bDescriptorType =      USB_DT_OTG,
214 	.bmAttributes =         USB_OTG_SRP,
215 };
216 
217 static const struct usb_descriptor_header *otg_desc[] = {
218 	(struct usb_descriptor_header *) &otg_descriptor,
219 	NULL,
220 };
221 
222 /* maxpacket and other transfer characteristics vary by speed. */
223 #define ep_desc(g, hs, fs) (((g)->speed == USB_SPEED_HIGH)?(hs):(fs))
224 
225 /*-------------------------------------------------------------------------*/
226 
227 /* descriptors that are built on-demand */
228 
229 static char				product_desc [40] = DRIVER_DESC;
230 static char				serial_num [40] = "1";
231 static char				pnp_string [1024] =
232 	"XXMFG:linux;MDL:g_printer;CLS:PRINTER;SN:1;";
233 
234 /* static strings, in UTF-8 */
235 static struct usb_string		strings [] = {
236 	[USB_GADGET_MANUFACTURER_IDX].s = "",
237 	[USB_GADGET_PRODUCT_IDX].s = product_desc,
238 	[USB_GADGET_SERIAL_IDX].s =	serial_num,
239 	{  }		/* end of list */
240 };
241 
242 static struct usb_gadget_strings	stringtab_dev = {
243 	.language	= 0x0409,	/* en-us */
244 	.strings	= strings,
245 };
246 
247 static struct usb_gadget_strings *dev_strings[] = {
248 	&stringtab_dev,
249 	NULL,
250 };
251 
252 /*-------------------------------------------------------------------------*/
253 
254 static struct usb_request *
255 printer_req_alloc(struct usb_ep *ep, unsigned len, gfp_t gfp_flags)
256 {
257 	struct usb_request	*req;
258 
259 	req = usb_ep_alloc_request(ep, gfp_flags);
260 
261 	if (req != NULL) {
262 		req->length = len;
263 		req->buf = kmalloc(len, gfp_flags);
264 		if (req->buf == NULL) {
265 			usb_ep_free_request(ep, req);
266 			return NULL;
267 		}
268 	}
269 
270 	return req;
271 }
272 
273 static void
274 printer_req_free(struct usb_ep *ep, struct usb_request *req)
275 {
276 	if (ep != NULL && req != NULL) {
277 		kfree(req->buf);
278 		usb_ep_free_request(ep, req);
279 	}
280 }
281 
282 /*-------------------------------------------------------------------------*/
283 
284 static void rx_complete(struct usb_ep *ep, struct usb_request *req)
285 {
286 	struct printer_dev	*dev = ep->driver_data;
287 	int			status = req->status;
288 	unsigned long		flags;
289 
290 	spin_lock_irqsave(&dev->lock, flags);
291 
292 	list_del_init(&req->list);	/* Remode from Active List */
293 
294 	switch (status) {
295 
296 	/* normal completion */
297 	case 0:
298 		if (req->actual > 0) {
299 			list_add_tail(&req->list, &dev->rx_buffers);
300 			DBG(dev, "G_Printer : rx length %d\n", req->actual);
301 		} else {
302 			list_add(&req->list, &dev->rx_reqs);
303 		}
304 		break;
305 
306 	/* software-driven interface shutdown */
307 	case -ECONNRESET:		/* unlink */
308 	case -ESHUTDOWN:		/* disconnect etc */
309 		VDBG(dev, "rx shutdown, code %d\n", status);
310 		list_add(&req->list, &dev->rx_reqs);
311 		break;
312 
313 	/* for hardware automagic (such as pxa) */
314 	case -ECONNABORTED:		/* endpoint reset */
315 		DBG(dev, "rx %s reset\n", ep->name);
316 		list_add(&req->list, &dev->rx_reqs);
317 		break;
318 
319 	/* data overrun */
320 	case -EOVERFLOW:
321 		/* FALLTHROUGH */
322 
323 	default:
324 		DBG(dev, "rx status %d\n", status);
325 		list_add(&req->list, &dev->rx_reqs);
326 		break;
327 	}
328 
329 	wake_up_interruptible(&dev->rx_wait);
330 	spin_unlock_irqrestore(&dev->lock, flags);
331 }
332 
333 static void tx_complete(struct usb_ep *ep, struct usb_request *req)
334 {
335 	struct printer_dev	*dev = ep->driver_data;
336 
337 	switch (req->status) {
338 	default:
339 		VDBG(dev, "tx err %d\n", req->status);
340 		/* FALLTHROUGH */
341 	case -ECONNRESET:		/* unlink */
342 	case -ESHUTDOWN:		/* disconnect etc */
343 		break;
344 	case 0:
345 		break;
346 	}
347 
348 	spin_lock(&dev->lock);
349 	/* Take the request struct off the active list and put it on the
350 	 * free list.
351 	 */
352 	list_del_init(&req->list);
353 	list_add(&req->list, &dev->tx_reqs);
354 	wake_up_interruptible(&dev->tx_wait);
355 	if (likely(list_empty(&dev->tx_reqs_active)))
356 		wake_up_interruptible(&dev->tx_flush_wait);
357 
358 	spin_unlock(&dev->lock);
359 }
360 
361 /*-------------------------------------------------------------------------*/
362 
363 static int
364 printer_open(struct inode *inode, struct file *fd)
365 {
366 	struct printer_dev	*dev;
367 	unsigned long		flags;
368 	int			ret = -EBUSY;
369 
370 	mutex_lock(&printer_mutex);
371 	dev = container_of(inode->i_cdev, struct printer_dev, printer_cdev);
372 
373 	spin_lock_irqsave(&dev->lock, flags);
374 
375 	if (!dev->printer_cdev_open) {
376 		dev->printer_cdev_open = 1;
377 		fd->private_data = dev;
378 		ret = 0;
379 		/* Change the printer status to show that it's on-line. */
380 		dev->printer_status |= PRINTER_SELECTED;
381 	}
382 
383 	spin_unlock_irqrestore(&dev->lock, flags);
384 
385 	DBG(dev, "printer_open returned %x\n", ret);
386 	mutex_unlock(&printer_mutex);
387 	return ret;
388 }
389 
390 static int
391 printer_close(struct inode *inode, struct file *fd)
392 {
393 	struct printer_dev	*dev = fd->private_data;
394 	unsigned long		flags;
395 
396 	spin_lock_irqsave(&dev->lock, flags);
397 	dev->printer_cdev_open = 0;
398 	fd->private_data = NULL;
399 	/* Change printer status to show that the printer is off-line. */
400 	dev->printer_status &= ~PRINTER_SELECTED;
401 	spin_unlock_irqrestore(&dev->lock, flags);
402 
403 	DBG(dev, "printer_close\n");
404 
405 	return 0;
406 }
407 
408 /* This function must be called with interrupts turned off. */
409 static void
410 setup_rx_reqs(struct printer_dev *dev)
411 {
412 	struct usb_request              *req;
413 
414 	while (likely(!list_empty(&dev->rx_reqs))) {
415 		int error;
416 
417 		req = container_of(dev->rx_reqs.next,
418 				struct usb_request, list);
419 		list_del_init(&req->list);
420 
421 		/* The USB Host sends us whatever amount of data it wants to
422 		 * so we always set the length field to the full USB_BUFSIZE.
423 		 * If the amount of data is more than the read() caller asked
424 		 * for it will be stored in the request buffer until it is
425 		 * asked for by read().
426 		 */
427 		req->length = USB_BUFSIZE;
428 		req->complete = rx_complete;
429 
430 		/* here, we unlock, and only unlock, to avoid deadlock. */
431 		spin_unlock(&dev->lock);
432 		error = usb_ep_queue(dev->out_ep, req, GFP_ATOMIC);
433 		spin_lock(&dev->lock);
434 		if (error) {
435 			DBG(dev, "rx submit --> %d\n", error);
436 			list_add(&req->list, &dev->rx_reqs);
437 			break;
438 		}
439 		/* if the req is empty, then add it into dev->rx_reqs_active. */
440 		else if (list_empty(&req->list)) {
441 			list_add(&req->list, &dev->rx_reqs_active);
442 		}
443 	}
444 }
445 
446 static ssize_t
447 printer_read(struct file *fd, char __user *buf, size_t len, loff_t *ptr)
448 {
449 	struct printer_dev		*dev = fd->private_data;
450 	unsigned long			flags;
451 	size_t				size;
452 	size_t				bytes_copied;
453 	struct usb_request		*req;
454 	/* This is a pointer to the current USB rx request. */
455 	struct usb_request		*current_rx_req;
456 	/* This is the number of bytes in the current rx buffer. */
457 	size_t				current_rx_bytes;
458 	/* This is a pointer to the current rx buffer. */
459 	u8				*current_rx_buf;
460 
461 	if (len == 0)
462 		return -EINVAL;
463 
464 	DBG(dev, "printer_read trying to read %d bytes\n", (int)len);
465 
466 	mutex_lock(&dev->lock_printer_io);
467 	spin_lock_irqsave(&dev->lock, flags);
468 
469 	/* We will use this flag later to check if a printer reset happened
470 	 * after we turn interrupts back on.
471 	 */
472 	dev->reset_printer = 0;
473 
474 	setup_rx_reqs(dev);
475 
476 	bytes_copied = 0;
477 	current_rx_req = dev->current_rx_req;
478 	current_rx_bytes = dev->current_rx_bytes;
479 	current_rx_buf = dev->current_rx_buf;
480 	dev->current_rx_req = NULL;
481 	dev->current_rx_bytes = 0;
482 	dev->current_rx_buf = NULL;
483 
484 	/* Check if there is any data in the read buffers. Please note that
485 	 * current_rx_bytes is the number of bytes in the current rx buffer.
486 	 * If it is zero then check if there are any other rx_buffers that
487 	 * are on the completed list. We are only out of data if all rx
488 	 * buffers are empty.
489 	 */
490 	if ((current_rx_bytes == 0) &&
491 			(likely(list_empty(&dev->rx_buffers)))) {
492 		/* Turn interrupts back on before sleeping. */
493 		spin_unlock_irqrestore(&dev->lock, flags);
494 
495 		/*
496 		 * If no data is available check if this is a NON-Blocking
497 		 * call or not.
498 		 */
499 		if (fd->f_flags & (O_NONBLOCK|O_NDELAY)) {
500 			mutex_unlock(&dev->lock_printer_io);
501 			return -EAGAIN;
502 		}
503 
504 		/* Sleep until data is available */
505 		wait_event_interruptible(dev->rx_wait,
506 				(likely(!list_empty(&dev->rx_buffers))));
507 		spin_lock_irqsave(&dev->lock, flags);
508 	}
509 
510 	/* We have data to return then copy it to the caller's buffer.*/
511 	while ((current_rx_bytes || likely(!list_empty(&dev->rx_buffers)))
512 			&& len) {
513 		if (current_rx_bytes == 0) {
514 			req = container_of(dev->rx_buffers.next,
515 					struct usb_request, list);
516 			list_del_init(&req->list);
517 
518 			if (req->actual && req->buf) {
519 				current_rx_req = req;
520 				current_rx_bytes = req->actual;
521 				current_rx_buf = req->buf;
522 			} else {
523 				list_add(&req->list, &dev->rx_reqs);
524 				continue;
525 			}
526 		}
527 
528 		/* Don't leave irqs off while doing memory copies */
529 		spin_unlock_irqrestore(&dev->lock, flags);
530 
531 		if (len > current_rx_bytes)
532 			size = current_rx_bytes;
533 		else
534 			size = len;
535 
536 		size -= copy_to_user(buf, current_rx_buf, size);
537 		bytes_copied += size;
538 		len -= size;
539 		buf += size;
540 
541 		spin_lock_irqsave(&dev->lock, flags);
542 
543 		/* We've disconnected or reset so return. */
544 		if (dev->reset_printer) {
545 			list_add(&current_rx_req->list, &dev->rx_reqs);
546 			spin_unlock_irqrestore(&dev->lock, flags);
547 			mutex_unlock(&dev->lock_printer_io);
548 			return -EAGAIN;
549 		}
550 
551 		/* If we not returning all the data left in this RX request
552 		 * buffer then adjust the amount of data left in the buffer.
553 		 * Othewise if we are done with this RX request buffer then
554 		 * requeue it to get any incoming data from the USB host.
555 		 */
556 		if (size < current_rx_bytes) {
557 			current_rx_bytes -= size;
558 			current_rx_buf += size;
559 		} else {
560 			list_add(&current_rx_req->list, &dev->rx_reqs);
561 			current_rx_bytes = 0;
562 			current_rx_buf = NULL;
563 			current_rx_req = NULL;
564 		}
565 	}
566 
567 	dev->current_rx_req = current_rx_req;
568 	dev->current_rx_bytes = current_rx_bytes;
569 	dev->current_rx_buf = current_rx_buf;
570 
571 	spin_unlock_irqrestore(&dev->lock, flags);
572 	mutex_unlock(&dev->lock_printer_io);
573 
574 	DBG(dev, "printer_read returned %d bytes\n", (int)bytes_copied);
575 
576 	if (bytes_copied)
577 		return bytes_copied;
578 	else
579 		return -EAGAIN;
580 }
581 
582 static ssize_t
583 printer_write(struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
584 {
585 	struct printer_dev	*dev = fd->private_data;
586 	unsigned long		flags;
587 	size_t			size;	/* Amount of data in a TX request. */
588 	size_t			bytes_copied = 0;
589 	struct usb_request	*req;
590 
591 	DBG(dev, "printer_write trying to send %d bytes\n", (int)len);
592 
593 	if (len == 0)
594 		return -EINVAL;
595 
596 	mutex_lock(&dev->lock_printer_io);
597 	spin_lock_irqsave(&dev->lock, flags);
598 
599 	/* Check if a printer reset happens while we have interrupts on */
600 	dev->reset_printer = 0;
601 
602 	/* Check if there is any available write buffers */
603 	if (likely(list_empty(&dev->tx_reqs))) {
604 		/* Turn interrupts back on before sleeping. */
605 		spin_unlock_irqrestore(&dev->lock, flags);
606 
607 		/*
608 		 * If write buffers are available check if this is
609 		 * a NON-Blocking call or not.
610 		 */
611 		if (fd->f_flags & (O_NONBLOCK|O_NDELAY)) {
612 			mutex_unlock(&dev->lock_printer_io);
613 			return -EAGAIN;
614 		}
615 
616 		/* Sleep until a write buffer is available */
617 		wait_event_interruptible(dev->tx_wait,
618 				(likely(!list_empty(&dev->tx_reqs))));
619 		spin_lock_irqsave(&dev->lock, flags);
620 	}
621 
622 	while (likely(!list_empty(&dev->tx_reqs)) && len) {
623 
624 		if (len > USB_BUFSIZE)
625 			size = USB_BUFSIZE;
626 		else
627 			size = len;
628 
629 		req = container_of(dev->tx_reqs.next, struct usb_request,
630 				list);
631 		list_del_init(&req->list);
632 
633 		req->complete = tx_complete;
634 		req->length = size;
635 
636 		/* Check if we need to send a zero length packet. */
637 		if (len > size)
638 			/* They will be more TX requests so no yet. */
639 			req->zero = 0;
640 		else
641 			/* If the data amount is not a multple of the
642 			 * maxpacket size then send a zero length packet.
643 			 */
644 			req->zero = ((len % dev->in_ep->maxpacket) == 0);
645 
646 		/* Don't leave irqs off while doing memory copies */
647 		spin_unlock_irqrestore(&dev->lock, flags);
648 
649 		if (copy_from_user(req->buf, buf, size)) {
650 			list_add(&req->list, &dev->tx_reqs);
651 			mutex_unlock(&dev->lock_printer_io);
652 			return bytes_copied;
653 		}
654 
655 		bytes_copied += size;
656 		len -= size;
657 		buf += size;
658 
659 		spin_lock_irqsave(&dev->lock, flags);
660 
661 		/* We've disconnected or reset so free the req and buffer */
662 		if (dev->reset_printer) {
663 			list_add(&req->list, &dev->tx_reqs);
664 			spin_unlock_irqrestore(&dev->lock, flags);
665 			mutex_unlock(&dev->lock_printer_io);
666 			return -EAGAIN;
667 		}
668 
669 		if (usb_ep_queue(dev->in_ep, req, GFP_ATOMIC)) {
670 			list_add(&req->list, &dev->tx_reqs);
671 			spin_unlock_irqrestore(&dev->lock, flags);
672 			mutex_unlock(&dev->lock_printer_io);
673 			return -EAGAIN;
674 		}
675 
676 		list_add(&req->list, &dev->tx_reqs_active);
677 
678 	}
679 
680 	spin_unlock_irqrestore(&dev->lock, flags);
681 	mutex_unlock(&dev->lock_printer_io);
682 
683 	DBG(dev, "printer_write sent %d bytes\n", (int)bytes_copied);
684 
685 	if (bytes_copied) {
686 		return bytes_copied;
687 	} else {
688 		return -EAGAIN;
689 	}
690 }
691 
692 static int
693 printer_fsync(struct file *fd, loff_t start, loff_t end, int datasync)
694 {
695 	struct printer_dev	*dev = fd->private_data;
696 	struct inode *inode = file_inode(fd);
697 	unsigned long		flags;
698 	int			tx_list_empty;
699 
700 	mutex_lock(&inode->i_mutex);
701 	spin_lock_irqsave(&dev->lock, flags);
702 	tx_list_empty = (likely(list_empty(&dev->tx_reqs)));
703 	spin_unlock_irqrestore(&dev->lock, flags);
704 
705 	if (!tx_list_empty) {
706 		/* Sleep until all data has been sent */
707 		wait_event_interruptible(dev->tx_flush_wait,
708 				(likely(list_empty(&dev->tx_reqs_active))));
709 	}
710 	mutex_unlock(&inode->i_mutex);
711 
712 	return 0;
713 }
714 
715 static unsigned int
716 printer_poll(struct file *fd, poll_table *wait)
717 {
718 	struct printer_dev	*dev = fd->private_data;
719 	unsigned long		flags;
720 	int			status = 0;
721 
722 	mutex_lock(&dev->lock_printer_io);
723 	spin_lock_irqsave(&dev->lock, flags);
724 	setup_rx_reqs(dev);
725 	spin_unlock_irqrestore(&dev->lock, flags);
726 	mutex_unlock(&dev->lock_printer_io);
727 
728 	poll_wait(fd, &dev->rx_wait, wait);
729 	poll_wait(fd, &dev->tx_wait, wait);
730 
731 	spin_lock_irqsave(&dev->lock, flags);
732 	if (likely(!list_empty(&dev->tx_reqs)))
733 		status |= POLLOUT | POLLWRNORM;
734 
735 	if (likely(dev->current_rx_bytes) ||
736 			likely(!list_empty(&dev->rx_buffers)))
737 		status |= POLLIN | POLLRDNORM;
738 
739 	spin_unlock_irqrestore(&dev->lock, flags);
740 
741 	return status;
742 }
743 
744 static long
745 printer_ioctl(struct file *fd, unsigned int code, unsigned long arg)
746 {
747 	struct printer_dev	*dev = fd->private_data;
748 	unsigned long		flags;
749 	int			status = 0;
750 
751 	DBG(dev, "printer_ioctl: cmd=0x%4.4x, arg=%lu\n", code, arg);
752 
753 	/* handle ioctls */
754 
755 	spin_lock_irqsave(&dev->lock, flags);
756 
757 	switch (code) {
758 	case GADGET_GET_PRINTER_STATUS:
759 		status = (int)dev->printer_status;
760 		break;
761 	case GADGET_SET_PRINTER_STATUS:
762 		dev->printer_status = (u8)arg;
763 		break;
764 	default:
765 		/* could not handle ioctl */
766 		DBG(dev, "printer_ioctl: ERROR cmd=0x%4.4xis not supported\n",
767 				code);
768 		status = -ENOTTY;
769 	}
770 
771 	spin_unlock_irqrestore(&dev->lock, flags);
772 
773 	return status;
774 }
775 
776 /* used after endpoint configuration */
777 static const struct file_operations printer_io_operations = {
778 	.owner =	THIS_MODULE,
779 	.open =		printer_open,
780 	.read =		printer_read,
781 	.write =	printer_write,
782 	.fsync =	printer_fsync,
783 	.poll =		printer_poll,
784 	.unlocked_ioctl = printer_ioctl,
785 	.release =	printer_close,
786 	.llseek =	noop_llseek,
787 };
788 
789 /*-------------------------------------------------------------------------*/
790 
791 static int
792 set_printer_interface(struct printer_dev *dev)
793 {
794 	int			result = 0;
795 
796 	dev->in_ep->desc = ep_desc(dev->gadget, &hs_ep_in_desc, &fs_ep_in_desc);
797 	dev->in_ep->driver_data = dev;
798 
799 	dev->out_ep->desc = ep_desc(dev->gadget, &hs_ep_out_desc,
800 				    &fs_ep_out_desc);
801 	dev->out_ep->driver_data = dev;
802 
803 	result = usb_ep_enable(dev->in_ep);
804 	if (result != 0) {
805 		DBG(dev, "enable %s --> %d\n", dev->in_ep->name, result);
806 		goto done;
807 	}
808 
809 	result = usb_ep_enable(dev->out_ep);
810 	if (result != 0) {
811 		DBG(dev, "enable %s --> %d\n", dev->in_ep->name, result);
812 		goto done;
813 	}
814 
815 done:
816 	/* on error, disable any endpoints  */
817 	if (result != 0) {
818 		(void) usb_ep_disable(dev->in_ep);
819 		(void) usb_ep_disable(dev->out_ep);
820 		dev->in_ep->desc = NULL;
821 		dev->out_ep->desc = NULL;
822 	}
823 
824 	/* caller is responsible for cleanup on error */
825 	return result;
826 }
827 
828 static void printer_reset_interface(struct printer_dev *dev)
829 {
830 	if (dev->interface < 0)
831 		return;
832 
833 	DBG(dev, "%s\n", __func__);
834 
835 	if (dev->in_ep->desc)
836 		usb_ep_disable(dev->in_ep);
837 
838 	if (dev->out_ep->desc)
839 		usb_ep_disable(dev->out_ep);
840 
841 	dev->in_ep->desc = NULL;
842 	dev->out_ep->desc = NULL;
843 	dev->interface = -1;
844 }
845 
846 /* Change our operational Interface. */
847 static int set_interface(struct printer_dev *dev, unsigned number)
848 {
849 	int			result = 0;
850 
851 	/* Free the current interface */
852 	printer_reset_interface(dev);
853 
854 	result = set_printer_interface(dev);
855 	if (result)
856 		printer_reset_interface(dev);
857 	else
858 		dev->interface = number;
859 
860 	if (!result)
861 		INFO(dev, "Using interface %x\n", number);
862 
863 	return result;
864 }
865 
866 static void printer_soft_reset(struct printer_dev *dev)
867 {
868 	struct usb_request	*req;
869 
870 	INFO(dev, "Received Printer Reset Request\n");
871 
872 	if (usb_ep_disable(dev->in_ep))
873 		DBG(dev, "Failed to disable USB in_ep\n");
874 	if (usb_ep_disable(dev->out_ep))
875 		DBG(dev, "Failed to disable USB out_ep\n");
876 
877 	if (dev->current_rx_req != NULL) {
878 		list_add(&dev->current_rx_req->list, &dev->rx_reqs);
879 		dev->current_rx_req = NULL;
880 	}
881 	dev->current_rx_bytes = 0;
882 	dev->current_rx_buf = NULL;
883 	dev->reset_printer = 1;
884 
885 	while (likely(!(list_empty(&dev->rx_buffers)))) {
886 		req = container_of(dev->rx_buffers.next, struct usb_request,
887 				list);
888 		list_del_init(&req->list);
889 		list_add(&req->list, &dev->rx_reqs);
890 	}
891 
892 	while (likely(!(list_empty(&dev->rx_reqs_active)))) {
893 		req = container_of(dev->rx_buffers.next, struct usb_request,
894 				list);
895 		list_del_init(&req->list);
896 		list_add(&req->list, &dev->rx_reqs);
897 	}
898 
899 	while (likely(!(list_empty(&dev->tx_reqs_active)))) {
900 		req = container_of(dev->tx_reqs_active.next,
901 				struct usb_request, list);
902 		list_del_init(&req->list);
903 		list_add(&req->list, &dev->tx_reqs);
904 	}
905 
906 	if (usb_ep_enable(dev->in_ep))
907 		DBG(dev, "Failed to enable USB in_ep\n");
908 	if (usb_ep_enable(dev->out_ep))
909 		DBG(dev, "Failed to enable USB out_ep\n");
910 
911 	wake_up_interruptible(&dev->rx_wait);
912 	wake_up_interruptible(&dev->tx_wait);
913 	wake_up_interruptible(&dev->tx_flush_wait);
914 }
915 
916 /*-------------------------------------------------------------------------*/
917 
918 /*
919  * The setup() callback implements all the ep0 functionality that's not
920  * handled lower down.
921  */
922 static int printer_func_setup(struct usb_function *f,
923 		const struct usb_ctrlrequest *ctrl)
924 {
925 	struct printer_dev *dev = container_of(f, struct printer_dev, function);
926 	struct usb_composite_dev *cdev = f->config->cdev;
927 	struct usb_request	*req = cdev->req;
928 	int			value = -EOPNOTSUPP;
929 	u16			wIndex = le16_to_cpu(ctrl->wIndex);
930 	u16			wValue = le16_to_cpu(ctrl->wValue);
931 	u16			wLength = le16_to_cpu(ctrl->wLength);
932 
933 	DBG(dev, "ctrl req%02x.%02x v%04x i%04x l%d\n",
934 		ctrl->bRequestType, ctrl->bRequest, wValue, wIndex, wLength);
935 
936 	switch (ctrl->bRequestType&USB_TYPE_MASK) {
937 	case USB_TYPE_CLASS:
938 		switch (ctrl->bRequest) {
939 		case 0: /* Get the IEEE-1284 PNP String */
940 			/* Only one printer interface is supported. */
941 			if ((wIndex>>8) != dev->interface)
942 				break;
943 
944 			value = (pnp_string[0]<<8)|pnp_string[1];
945 			memcpy(req->buf, pnp_string, value);
946 			DBG(dev, "1284 PNP String: %x %s\n", value,
947 					&pnp_string[2]);
948 			break;
949 
950 		case 1: /* Get Port Status */
951 			/* Only one printer interface is supported. */
952 			if (wIndex != dev->interface)
953 				break;
954 
955 			*(u8 *)req->buf = dev->printer_status;
956 			value = min(wLength, (u16) 1);
957 			break;
958 
959 		case 2: /* Soft Reset */
960 			/* Only one printer interface is supported. */
961 			if (wIndex != dev->interface)
962 				break;
963 
964 			printer_soft_reset(dev);
965 
966 			value = 0;
967 			break;
968 
969 		default:
970 			goto unknown;
971 		}
972 		break;
973 
974 	default:
975 unknown:
976 		VDBG(dev,
977 			"unknown ctrl req%02x.%02x v%04x i%04x l%d\n",
978 			ctrl->bRequestType, ctrl->bRequest,
979 			wValue, wIndex, wLength);
980 		break;
981 	}
982 	/* host either stalls (value < 0) or reports success */
983 	return value;
984 }
985 
986 static int __init printer_func_bind(struct usb_configuration *c,
987 		struct usb_function *f)
988 {
989 	struct printer_dev *dev = container_of(f, struct printer_dev, function);
990 	struct usb_composite_dev *cdev = c->cdev;
991 	struct usb_ep *in_ep;
992 	struct usb_ep *out_ep = NULL;
993 	int id;
994 	int ret;
995 
996 	id = usb_interface_id(c, f);
997 	if (id < 0)
998 		return id;
999 	intf_desc.bInterfaceNumber = id;
1000 
1001 	/* all we really need is bulk IN/OUT */
1002 	in_ep = usb_ep_autoconfig(cdev->gadget, &fs_ep_in_desc);
1003 	if (!in_ep) {
1004 autoconf_fail:
1005 		dev_err(&cdev->gadget->dev, "can't autoconfigure on %s\n",
1006 			cdev->gadget->name);
1007 		return -ENODEV;
1008 	}
1009 	in_ep->driver_data = in_ep;	/* claim */
1010 
1011 	out_ep = usb_ep_autoconfig(cdev->gadget, &fs_ep_out_desc);
1012 	if (!out_ep)
1013 		goto autoconf_fail;
1014 	out_ep->driver_data = out_ep;	/* claim */
1015 
1016 	/* assumes that all endpoints are dual-speed */
1017 	hs_ep_in_desc.bEndpointAddress = fs_ep_in_desc.bEndpointAddress;
1018 	hs_ep_out_desc.bEndpointAddress = fs_ep_out_desc.bEndpointAddress;
1019 
1020 	ret = usb_assign_descriptors(f, fs_printer_function,
1021 			hs_printer_function, NULL);
1022 	if (ret)
1023 		return ret;
1024 
1025 	dev->in_ep = in_ep;
1026 	dev->out_ep = out_ep;
1027 	return 0;
1028 }
1029 
1030 static void printer_func_unbind(struct usb_configuration *c,
1031 		struct usb_function *f)
1032 {
1033 	usb_free_all_descriptors(f);
1034 }
1035 
1036 static int printer_func_set_alt(struct usb_function *f,
1037 		unsigned intf, unsigned alt)
1038 {
1039 	struct printer_dev *dev = container_of(f, struct printer_dev, function);
1040 	int ret = -ENOTSUPP;
1041 
1042 	if (!alt)
1043 		ret = set_interface(dev, intf);
1044 
1045 	return ret;
1046 }
1047 
1048 static void printer_func_disable(struct usb_function *f)
1049 {
1050 	struct printer_dev *dev = container_of(f, struct printer_dev, function);
1051 	unsigned long		flags;
1052 
1053 	DBG(dev, "%s\n", __func__);
1054 
1055 	spin_lock_irqsave(&dev->lock, flags);
1056 	printer_reset_interface(dev);
1057 	spin_unlock_irqrestore(&dev->lock, flags);
1058 }
1059 
1060 static void printer_cfg_unbind(struct usb_configuration *c)
1061 {
1062 	struct printer_dev	*dev;
1063 	struct usb_request	*req;
1064 
1065 	dev = &usb_printer_gadget;
1066 
1067 	DBG(dev, "%s\n", __func__);
1068 
1069 	/* Remove sysfs files */
1070 	device_destroy(usb_gadget_class, g_printer_devno);
1071 
1072 	/* Remove Character Device */
1073 	cdev_del(&dev->printer_cdev);
1074 
1075 	/* we must already have been disconnected ... no i/o may be active */
1076 	WARN_ON(!list_empty(&dev->tx_reqs_active));
1077 	WARN_ON(!list_empty(&dev->rx_reqs_active));
1078 
1079 	/* Free all memory for this driver. */
1080 	while (!list_empty(&dev->tx_reqs)) {
1081 		req = container_of(dev->tx_reqs.next, struct usb_request,
1082 				list);
1083 		list_del(&req->list);
1084 		printer_req_free(dev->in_ep, req);
1085 	}
1086 
1087 	if (dev->current_rx_req != NULL)
1088 		printer_req_free(dev->out_ep, dev->current_rx_req);
1089 
1090 	while (!list_empty(&dev->rx_reqs)) {
1091 		req = container_of(dev->rx_reqs.next,
1092 				struct usb_request, list);
1093 		list_del(&req->list);
1094 		printer_req_free(dev->out_ep, req);
1095 	}
1096 
1097 	while (!list_empty(&dev->rx_buffers)) {
1098 		req = container_of(dev->rx_buffers.next,
1099 				struct usb_request, list);
1100 		list_del(&req->list);
1101 		printer_req_free(dev->out_ep, req);
1102 	}
1103 }
1104 
1105 static struct usb_configuration printer_cfg_driver = {
1106 	.label			= "printer",
1107 	.unbind			= printer_cfg_unbind,
1108 	.bConfigurationValue	= 1,
1109 	.bmAttributes		= USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
1110 };
1111 
1112 static int __init printer_bind_config(struct usb_configuration *c)
1113 {
1114 	struct usb_gadget	*gadget = c->cdev->gadget;
1115 	struct printer_dev	*dev;
1116 	int			status = -ENOMEM;
1117 	size_t			len;
1118 	u32			i;
1119 	struct usb_request	*req;
1120 
1121 	usb_ep_autoconfig_reset(gadget);
1122 
1123 	dev = &usb_printer_gadget;
1124 
1125 	dev->function.name = shortname;
1126 	dev->function.bind = printer_func_bind;
1127 	dev->function.setup = printer_func_setup;
1128 	dev->function.unbind = printer_func_unbind;
1129 	dev->function.set_alt = printer_func_set_alt;
1130 	dev->function.disable = printer_func_disable;
1131 
1132 	status = usb_add_function(c, &dev->function);
1133 	if (status)
1134 		return status;
1135 
1136 	/* Setup the sysfs files for the printer gadget. */
1137 	dev->pdev = device_create(usb_gadget_class, NULL, g_printer_devno,
1138 				  NULL, "g_printer");
1139 	if (IS_ERR(dev->pdev)) {
1140 		ERROR(dev, "Failed to create device: g_printer\n");
1141 		status = PTR_ERR(dev->pdev);
1142 		goto fail;
1143 	}
1144 
1145 	/*
1146 	 * Register a character device as an interface to a user mode
1147 	 * program that handles the printer specific functionality.
1148 	 */
1149 	cdev_init(&dev->printer_cdev, &printer_io_operations);
1150 	dev->printer_cdev.owner = THIS_MODULE;
1151 	status = cdev_add(&dev->printer_cdev, g_printer_devno, 1);
1152 	if (status) {
1153 		ERROR(dev, "Failed to open char device\n");
1154 		goto fail;
1155 	}
1156 
1157 	if (iPNPstring)
1158 		strlcpy(&pnp_string[2], iPNPstring, (sizeof pnp_string)-2);
1159 
1160 	len = strlen(pnp_string);
1161 	pnp_string[0] = (len >> 8) & 0xFF;
1162 	pnp_string[1] = len & 0xFF;
1163 
1164 	usb_gadget_set_selfpowered(gadget);
1165 
1166 	if (gadget_is_otg(gadget)) {
1167 		otg_descriptor.bmAttributes |= USB_OTG_HNP;
1168 		printer_cfg_driver.descriptors = otg_desc;
1169 		printer_cfg_driver.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
1170 	}
1171 
1172 	spin_lock_init(&dev->lock);
1173 	mutex_init(&dev->lock_printer_io);
1174 	INIT_LIST_HEAD(&dev->tx_reqs);
1175 	INIT_LIST_HEAD(&dev->tx_reqs_active);
1176 	INIT_LIST_HEAD(&dev->rx_reqs);
1177 	INIT_LIST_HEAD(&dev->rx_reqs_active);
1178 	INIT_LIST_HEAD(&dev->rx_buffers);
1179 	init_waitqueue_head(&dev->rx_wait);
1180 	init_waitqueue_head(&dev->tx_wait);
1181 	init_waitqueue_head(&dev->tx_flush_wait);
1182 
1183 	dev->interface = -1;
1184 	dev->printer_cdev_open = 0;
1185 	dev->printer_status = PRINTER_NOT_ERROR;
1186 	dev->current_rx_req = NULL;
1187 	dev->current_rx_bytes = 0;
1188 	dev->current_rx_buf = NULL;
1189 
1190 	for (i = 0; i < QLEN; i++) {
1191 		req = printer_req_alloc(dev->in_ep, USB_BUFSIZE, GFP_KERNEL);
1192 		if (!req) {
1193 			while (!list_empty(&dev->tx_reqs)) {
1194 				req = container_of(dev->tx_reqs.next,
1195 						struct usb_request, list);
1196 				list_del(&req->list);
1197 				printer_req_free(dev->in_ep, req);
1198 			}
1199 			return -ENOMEM;
1200 		}
1201 		list_add(&req->list, &dev->tx_reqs);
1202 	}
1203 
1204 	for (i = 0; i < QLEN; i++) {
1205 		req = printer_req_alloc(dev->out_ep, USB_BUFSIZE, GFP_KERNEL);
1206 		if (!req) {
1207 			while (!list_empty(&dev->rx_reqs)) {
1208 				req = container_of(dev->rx_reqs.next,
1209 						struct usb_request, list);
1210 				list_del(&req->list);
1211 				printer_req_free(dev->out_ep, req);
1212 			}
1213 			return -ENOMEM;
1214 		}
1215 		list_add(&req->list, &dev->rx_reqs);
1216 	}
1217 
1218 	/* finish hookup to lower layer ... */
1219 	dev->gadget = gadget;
1220 
1221 	INFO(dev, "%s, version: " DRIVER_VERSION "\n", driver_desc);
1222 	return 0;
1223 
1224 fail:
1225 	printer_cfg_unbind(c);
1226 	return status;
1227 }
1228 
1229 static int printer_unbind(struct usb_composite_dev *cdev)
1230 {
1231 	return 0;
1232 }
1233 
1234 static int __init printer_bind(struct usb_composite_dev *cdev)
1235 {
1236 	int ret;
1237 
1238 	ret = usb_string_ids_tab(cdev, strings);
1239 	if (ret < 0)
1240 		return ret;
1241 	device_desc.iManufacturer = strings[USB_GADGET_MANUFACTURER_IDX].id;
1242 	device_desc.iProduct = strings[USB_GADGET_PRODUCT_IDX].id;
1243 	device_desc.iSerialNumber = strings[USB_GADGET_SERIAL_IDX].id;
1244 
1245 	ret = usb_add_config(cdev, &printer_cfg_driver, printer_bind_config);
1246 	if (ret)
1247 		return ret;
1248 	usb_composite_overwrite_options(cdev, &coverwrite);
1249 	return ret;
1250 }
1251 
1252 static __refdata struct usb_composite_driver printer_driver = {
1253 	.name           = shortname,
1254 	.dev            = &device_desc,
1255 	.strings        = dev_strings,
1256 	.max_speed      = USB_SPEED_HIGH,
1257 	.bind		= printer_bind,
1258 	.unbind		= printer_unbind,
1259 };
1260 
1261 static int __init
1262 init(void)
1263 {
1264 	int status;
1265 
1266 	usb_gadget_class = class_create(THIS_MODULE, "usb_printer_gadget");
1267 	if (IS_ERR(usb_gadget_class)) {
1268 		status = PTR_ERR(usb_gadget_class);
1269 		pr_err("unable to create usb_gadget class %d\n", status);
1270 		return status;
1271 	}
1272 
1273 	status = alloc_chrdev_region(&g_printer_devno, 0, 1,
1274 			"USB printer gadget");
1275 	if (status) {
1276 		pr_err("alloc_chrdev_region %d\n", status);
1277 		class_destroy(usb_gadget_class);
1278 		return status;
1279 	}
1280 
1281 	status = usb_composite_probe(&printer_driver);
1282 	if (status) {
1283 		class_destroy(usb_gadget_class);
1284 		unregister_chrdev_region(g_printer_devno, 1);
1285 		pr_err("usb_gadget_probe_driver %x\n", status);
1286 	}
1287 
1288 	return status;
1289 }
1290 module_init(init);
1291 
1292 static void __exit
1293 cleanup(void)
1294 {
1295 	mutex_lock(&usb_printer_gadget.lock_printer_io);
1296 	usb_composite_unregister(&printer_driver);
1297 	unregister_chrdev_region(g_printer_devno, 1);
1298 	class_destroy(usb_gadget_class);
1299 	mutex_unlock(&usb_printer_gadget.lock_printer_io);
1300 }
1301 module_exit(cleanup);
1302 
1303 MODULE_DESCRIPTION(DRIVER_DESC);
1304 MODULE_AUTHOR("Craig Nadler");
1305 MODULE_LICENSE("GPL");
1306