1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * u_serial.c - utilities for USB gadget "serial port"/TTY support
4  *
5  * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
6  * Copyright (C) 2008 David Brownell
7  * Copyright (C) 2008 by Nokia Corporation
8  *
9  * This code also borrows from usbserial.c, which is
10  * Copyright (C) 1999 - 2002 Greg Kroah-Hartman (greg@kroah.com)
11  * Copyright (C) 2000 Peter Berger (pberger@brimson.com)
12  * Copyright (C) 2000 Al Borchers (alborchers@steinerpoint.com)
13  */
14 
15 /* #define VERBOSE_DEBUG */
16 
17 #include <linux/kernel.h>
18 #include <linux/sched.h>
19 #include <linux/interrupt.h>
20 #include <linux/device.h>
21 #include <linux/delay.h>
22 #include <linux/tty.h>
23 #include <linux/tty_flip.h>
24 #include <linux/slab.h>
25 #include <linux/export.h>
26 #include <linux/module.h>
27 #include <linux/console.h>
28 #include <linux/kthread.h>
29 
30 #include "u_serial.h"
31 
32 
33 /*
34  * This component encapsulates the TTY layer glue needed to provide basic
35  * "serial port" functionality through the USB gadget stack.  Each such
36  * port is exposed through a /dev/ttyGS* node.
37  *
38  * After this module has been loaded, the individual TTY port can be requested
39  * (gserial_alloc_line()) and it will stay available until they are removed
40  * (gserial_free_line()). Each one may be connected to a USB function
41  * (gserial_connect), or disconnected (with gserial_disconnect) when the USB
42  * host issues a config change event. Data can only flow when the port is
43  * connected to the host.
44  *
45  * A given TTY port can be made available in multiple configurations.
46  * For example, each one might expose a ttyGS0 node which provides a
47  * login application.  In one case that might use CDC ACM interface 0,
48  * while another configuration might use interface 3 for that.  The
49  * work to handle that (including descriptor management) is not part
50  * of this component.
51  *
52  * Configurations may expose more than one TTY port.  For example, if
53  * ttyGS0 provides login service, then ttyGS1 might provide dialer access
54  * for a telephone or fax link.  And ttyGS2 might be something that just
55  * needs a simple byte stream interface for some messaging protocol that
56  * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
57  *
58  *
59  * gserial is the lifecycle interface, used by USB functions
60  * gs_port is the I/O nexus, used by the tty driver
61  * tty_struct links to the tty/filesystem framework
62  *
63  * gserial <---> gs_port ... links will be null when the USB link is
64  * inactive; managed by gserial_{connect,disconnect}().  each gserial
65  * instance can wrap its own USB control protocol.
66  *	gserial->ioport == usb_ep->driver_data ... gs_port
67  *	gs_port->port_usb ... gserial
68  *
69  * gs_port <---> tty_struct ... links will be null when the TTY file
70  * isn't opened; managed by gs_open()/gs_close()
71  *	gserial->port_tty ... tty_struct
72  *	tty_struct->driver_data ... gserial
73  */
74 
75 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
76  * next layer of buffering.  For TX that's a circular buffer; for RX
77  * consider it a NOP.  A third layer is provided by the TTY code.
78  */
79 #define QUEUE_SIZE		16
80 #define WRITE_BUF_SIZE		8192		/* TX only */
81 #define GS_CONSOLE_BUF_SIZE	8192
82 
83 /* circular buffer */
84 struct gs_buf {
85 	unsigned		buf_size;
86 	char			*buf_buf;
87 	char			*buf_get;
88 	char			*buf_put;
89 };
90 
91 /* console info */
92 struct gscons_info {
93 	struct gs_port		*port;
94 	struct task_struct	*console_thread;
95 	struct gs_buf		con_buf;
96 	/* protect the buf and busy flag */
97 	spinlock_t		con_lock;
98 	int			req_busy;
99 	struct usb_request	*console_req;
100 };
101 
102 /*
103  * The port structure holds info for each port, one for each minor number
104  * (and thus for each /dev/ node).
105  */
106 struct gs_port {
107 	struct tty_port		port;
108 	spinlock_t		port_lock;	/* guard port_* access */
109 
110 	struct gserial		*port_usb;
111 
112 	bool			openclose;	/* open/close in progress */
113 	u8			port_num;
114 
115 	struct list_head	read_pool;
116 	int read_started;
117 	int read_allocated;
118 	struct list_head	read_queue;
119 	unsigned		n_read;
120 	struct tasklet_struct	push;
121 
122 	struct list_head	write_pool;
123 	int write_started;
124 	int write_allocated;
125 	struct gs_buf		port_write_buf;
126 	wait_queue_head_t	drain_wait;	/* wait while writes drain */
127 	bool                    write_busy;
128 	wait_queue_head_t	close_wait;
129 
130 	/* REVISIT this state ... */
131 	struct usb_cdc_line_coding port_line_coding;	/* 8-N-1 etc */
132 };
133 
134 static struct portmaster {
135 	struct mutex	lock;			/* protect open/close */
136 	struct gs_port	*port;
137 } ports[MAX_U_SERIAL_PORTS];
138 
139 #define GS_CLOSE_TIMEOUT		15		/* seconds */
140 
141 
142 
143 #ifdef VERBOSE_DEBUG
144 #ifndef pr_vdebug
145 #define pr_vdebug(fmt, arg...) \
146 	pr_debug(fmt, ##arg)
147 #endif /* pr_vdebug */
148 #else
149 #ifndef pr_vdebug
150 #define pr_vdebug(fmt, arg...) \
151 	({ if (0) pr_debug(fmt, ##arg); })
152 #endif /* pr_vdebug */
153 #endif
154 
155 /*-------------------------------------------------------------------------*/
156 
157 /* Circular Buffer */
158 
159 /*
160  * gs_buf_alloc
161  *
162  * Allocate a circular buffer and all associated memory.
163  */
164 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
165 {
166 	gb->buf_buf = kmalloc(size, GFP_KERNEL);
167 	if (gb->buf_buf == NULL)
168 		return -ENOMEM;
169 
170 	gb->buf_size = size;
171 	gb->buf_put = gb->buf_buf;
172 	gb->buf_get = gb->buf_buf;
173 
174 	return 0;
175 }
176 
177 /*
178  * gs_buf_free
179  *
180  * Free the buffer and all associated memory.
181  */
182 static void gs_buf_free(struct gs_buf *gb)
183 {
184 	kfree(gb->buf_buf);
185 	gb->buf_buf = NULL;
186 }
187 
188 /*
189  * gs_buf_clear
190  *
191  * Clear out all data in the circular buffer.
192  */
193 static void gs_buf_clear(struct gs_buf *gb)
194 {
195 	gb->buf_get = gb->buf_put;
196 	/* equivalent to a get of all data available */
197 }
198 
199 /*
200  * gs_buf_data_avail
201  *
202  * Return the number of bytes of data written into the circular
203  * buffer.
204  */
205 static unsigned gs_buf_data_avail(struct gs_buf *gb)
206 {
207 	return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
208 }
209 
210 /*
211  * gs_buf_space_avail
212  *
213  * Return the number of bytes of space available in the circular
214  * buffer.
215  */
216 static unsigned gs_buf_space_avail(struct gs_buf *gb)
217 {
218 	return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
219 }
220 
221 /*
222  * gs_buf_put
223  *
224  * Copy data data from a user buffer and put it into the circular buffer.
225  * Restrict to the amount of space available.
226  *
227  * Return the number of bytes copied.
228  */
229 static unsigned
230 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
231 {
232 	unsigned len;
233 
234 	len  = gs_buf_space_avail(gb);
235 	if (count > len)
236 		count = len;
237 
238 	if (count == 0)
239 		return 0;
240 
241 	len = gb->buf_buf + gb->buf_size - gb->buf_put;
242 	if (count > len) {
243 		memcpy(gb->buf_put, buf, len);
244 		memcpy(gb->buf_buf, buf+len, count - len);
245 		gb->buf_put = gb->buf_buf + count - len;
246 	} else {
247 		memcpy(gb->buf_put, buf, count);
248 		if (count < len)
249 			gb->buf_put += count;
250 		else /* count == len */
251 			gb->buf_put = gb->buf_buf;
252 	}
253 
254 	return count;
255 }
256 
257 /*
258  * gs_buf_get
259  *
260  * Get data from the circular buffer and copy to the given buffer.
261  * Restrict to the amount of data available.
262  *
263  * Return the number of bytes copied.
264  */
265 static unsigned
266 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
267 {
268 	unsigned len;
269 
270 	len = gs_buf_data_avail(gb);
271 	if (count > len)
272 		count = len;
273 
274 	if (count == 0)
275 		return 0;
276 
277 	len = gb->buf_buf + gb->buf_size - gb->buf_get;
278 	if (count > len) {
279 		memcpy(buf, gb->buf_get, len);
280 		memcpy(buf+len, gb->buf_buf, count - len);
281 		gb->buf_get = gb->buf_buf + count - len;
282 	} else {
283 		memcpy(buf, gb->buf_get, count);
284 		if (count < len)
285 			gb->buf_get += count;
286 		else /* count == len */
287 			gb->buf_get = gb->buf_buf;
288 	}
289 
290 	return count;
291 }
292 
293 /*-------------------------------------------------------------------------*/
294 
295 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
296 
297 /*
298  * gs_alloc_req
299  *
300  * Allocate a usb_request and its buffer.  Returns a pointer to the
301  * usb_request or NULL if there is an error.
302  */
303 struct usb_request *
304 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
305 {
306 	struct usb_request *req;
307 
308 	req = usb_ep_alloc_request(ep, kmalloc_flags);
309 
310 	if (req != NULL) {
311 		req->length = len;
312 		req->buf = kmalloc(len, kmalloc_flags);
313 		if (req->buf == NULL) {
314 			usb_ep_free_request(ep, req);
315 			return NULL;
316 		}
317 	}
318 
319 	return req;
320 }
321 EXPORT_SYMBOL_GPL(gs_alloc_req);
322 
323 /*
324  * gs_free_req
325  *
326  * Free a usb_request and its buffer.
327  */
328 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
329 {
330 	kfree(req->buf);
331 	usb_ep_free_request(ep, req);
332 }
333 EXPORT_SYMBOL_GPL(gs_free_req);
334 
335 /*
336  * gs_send_packet
337  *
338  * If there is data to send, a packet is built in the given
339  * buffer and the size is returned.  If there is no data to
340  * send, 0 is returned.
341  *
342  * Called with port_lock held.
343  */
344 static unsigned
345 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
346 {
347 	unsigned len;
348 
349 	len = gs_buf_data_avail(&port->port_write_buf);
350 	if (len < size)
351 		size = len;
352 	if (size != 0)
353 		size = gs_buf_get(&port->port_write_buf, packet, size);
354 	return size;
355 }
356 
357 /*
358  * gs_start_tx
359  *
360  * This function finds available write requests, calls
361  * gs_send_packet to fill these packets with data, and
362  * continues until either there are no more write requests
363  * available or no more data to send.  This function is
364  * run whenever data arrives or write requests are available.
365  *
366  * Context: caller owns port_lock; port_usb is non-null.
367  */
368 static int gs_start_tx(struct gs_port *port)
369 /*
370 __releases(&port->port_lock)
371 __acquires(&port->port_lock)
372 */
373 {
374 	struct list_head	*pool = &port->write_pool;
375 	struct usb_ep		*in;
376 	int			status = 0;
377 	bool			do_tty_wake = false;
378 
379 	if (!port->port_usb)
380 		return status;
381 
382 	in = port->port_usb->in;
383 
384 	while (!port->write_busy && !list_empty(pool)) {
385 		struct usb_request	*req;
386 		int			len;
387 
388 		if (port->write_started >= QUEUE_SIZE)
389 			break;
390 
391 		req = list_entry(pool->next, struct usb_request, list);
392 		len = gs_send_packet(port, req->buf, in->maxpacket);
393 		if (len == 0) {
394 			wake_up_interruptible(&port->drain_wait);
395 			break;
396 		}
397 		do_tty_wake = true;
398 
399 		req->length = len;
400 		list_del(&req->list);
401 		req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
402 
403 		pr_vdebug("ttyGS%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
404 			  port->port_num, len, *((u8 *)req->buf),
405 			  *((u8 *)req->buf+1), *((u8 *)req->buf+2));
406 
407 		/* Drop lock while we call out of driver; completions
408 		 * could be issued while we do so.  Disconnection may
409 		 * happen too; maybe immediately before we queue this!
410 		 *
411 		 * NOTE that we may keep sending data for a while after
412 		 * the TTY closed (dev->ioport->port_tty is NULL).
413 		 */
414 		port->write_busy = true;
415 		spin_unlock(&port->port_lock);
416 		status = usb_ep_queue(in, req, GFP_ATOMIC);
417 		spin_lock(&port->port_lock);
418 		port->write_busy = false;
419 
420 		if (status) {
421 			pr_debug("%s: %s %s err %d\n",
422 					__func__, "queue", in->name, status);
423 			list_add(&req->list, pool);
424 			break;
425 		}
426 
427 		port->write_started++;
428 
429 		/* abort immediately after disconnect */
430 		if (!port->port_usb)
431 			break;
432 	}
433 
434 	if (do_tty_wake && port->port.tty)
435 		tty_wakeup(port->port.tty);
436 	return status;
437 }
438 
439 /*
440  * Context: caller owns port_lock, and port_usb is set
441  */
442 static unsigned gs_start_rx(struct gs_port *port)
443 /*
444 __releases(&port->port_lock)
445 __acquires(&port->port_lock)
446 */
447 {
448 	struct list_head	*pool = &port->read_pool;
449 	struct usb_ep		*out = port->port_usb->out;
450 
451 	while (!list_empty(pool)) {
452 		struct usb_request	*req;
453 		int			status;
454 		struct tty_struct	*tty;
455 
456 		/* no more rx if closed */
457 		tty = port->port.tty;
458 		if (!tty)
459 			break;
460 
461 		if (port->read_started >= QUEUE_SIZE)
462 			break;
463 
464 		req = list_entry(pool->next, struct usb_request, list);
465 		list_del(&req->list);
466 		req->length = out->maxpacket;
467 
468 		/* drop lock while we call out; the controller driver
469 		 * may need to call us back (e.g. for disconnect)
470 		 */
471 		spin_unlock(&port->port_lock);
472 		status = usb_ep_queue(out, req, GFP_ATOMIC);
473 		spin_lock(&port->port_lock);
474 
475 		if (status) {
476 			pr_debug("%s: %s %s err %d\n",
477 					__func__, "queue", out->name, status);
478 			list_add(&req->list, pool);
479 			break;
480 		}
481 		port->read_started++;
482 
483 		/* abort immediately after disconnect */
484 		if (!port->port_usb)
485 			break;
486 	}
487 	return port->read_started;
488 }
489 
490 /*
491  * RX tasklet takes data out of the RX queue and hands it up to the TTY
492  * layer until it refuses to take any more data (or is throttled back).
493  * Then it issues reads for any further data.
494  *
495  * If the RX queue becomes full enough that no usb_request is queued,
496  * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
497  * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
498  * can be buffered before the TTY layer's buffers (currently 64 KB).
499  */
500 static void gs_rx_push(unsigned long _port)
501 {
502 	struct gs_port		*port = (void *)_port;
503 	struct tty_struct	*tty;
504 	struct list_head	*queue = &port->read_queue;
505 	bool			disconnect = false;
506 	bool			do_push = false;
507 
508 	/* hand any queued data to the tty */
509 	spin_lock_irq(&port->port_lock);
510 	tty = port->port.tty;
511 	while (!list_empty(queue)) {
512 		struct usb_request	*req;
513 
514 		req = list_first_entry(queue, struct usb_request, list);
515 
516 		/* leave data queued if tty was rx throttled */
517 		if (tty && tty_throttled(tty))
518 			break;
519 
520 		switch (req->status) {
521 		case -ESHUTDOWN:
522 			disconnect = true;
523 			pr_vdebug("ttyGS%d: shutdown\n", port->port_num);
524 			break;
525 
526 		default:
527 			/* presumably a transient fault */
528 			pr_warn("ttyGS%d: unexpected RX status %d\n",
529 				port->port_num, req->status);
530 			/* FALLTHROUGH */
531 		case 0:
532 			/* normal completion */
533 			break;
534 		}
535 
536 		/* push data to (open) tty */
537 		if (req->actual && tty) {
538 			char		*packet = req->buf;
539 			unsigned	size = req->actual;
540 			unsigned	n;
541 			int		count;
542 
543 			/* we may have pushed part of this packet already... */
544 			n = port->n_read;
545 			if (n) {
546 				packet += n;
547 				size -= n;
548 			}
549 
550 			count = tty_insert_flip_string(&port->port, packet,
551 					size);
552 			if (count)
553 				do_push = true;
554 			if (count != size) {
555 				/* stop pushing; TTY layer can't handle more */
556 				port->n_read += count;
557 				pr_vdebug("ttyGS%d: rx block %d/%d\n",
558 					  port->port_num, count, req->actual);
559 				break;
560 			}
561 			port->n_read = 0;
562 		}
563 
564 		list_move(&req->list, &port->read_pool);
565 		port->read_started--;
566 	}
567 
568 	/* Push from tty to ldisc; this is handled by a workqueue,
569 	 * so we won't get callbacks and can hold port_lock
570 	 */
571 	if (do_push)
572 		tty_flip_buffer_push(&port->port);
573 
574 
575 	/* We want our data queue to become empty ASAP, keeping data
576 	 * in the tty and ldisc (not here).  If we couldn't push any
577 	 * this time around, there may be trouble unless there's an
578 	 * implicit tty_unthrottle() call on its way...
579 	 *
580 	 * REVISIT we should probably add a timer to keep the tasklet
581 	 * from starving ... but it's not clear that case ever happens.
582 	 */
583 	if (!list_empty(queue) && tty) {
584 		if (!tty_throttled(tty)) {
585 			if (do_push)
586 				tasklet_schedule(&port->push);
587 			else
588 				pr_warn("ttyGS%d: RX not scheduled?\n",
589 					port->port_num);
590 		}
591 	}
592 
593 	/* If we're still connected, refill the USB RX queue. */
594 	if (!disconnect && port->port_usb)
595 		gs_start_rx(port);
596 
597 	spin_unlock_irq(&port->port_lock);
598 }
599 
600 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
601 {
602 	struct gs_port	*port = ep->driver_data;
603 
604 	/* Queue all received data until the tty layer is ready for it. */
605 	spin_lock(&port->port_lock);
606 	list_add_tail(&req->list, &port->read_queue);
607 	tasklet_schedule(&port->push);
608 	spin_unlock(&port->port_lock);
609 }
610 
611 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
612 {
613 	struct gs_port	*port = ep->driver_data;
614 
615 	spin_lock(&port->port_lock);
616 	list_add(&req->list, &port->write_pool);
617 	port->write_started--;
618 
619 	switch (req->status) {
620 	default:
621 		/* presumably a transient fault */
622 		pr_warn("%s: unexpected %s status %d\n",
623 			__func__, ep->name, req->status);
624 		/* FALL THROUGH */
625 	case 0:
626 		/* normal completion */
627 		gs_start_tx(port);
628 		break;
629 
630 	case -ESHUTDOWN:
631 		/* disconnect */
632 		pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
633 		break;
634 	}
635 
636 	spin_unlock(&port->port_lock);
637 }
638 
639 static void gs_free_requests(struct usb_ep *ep, struct list_head *head,
640 							 int *allocated)
641 {
642 	struct usb_request	*req;
643 
644 	while (!list_empty(head)) {
645 		req = list_entry(head->next, struct usb_request, list);
646 		list_del(&req->list);
647 		gs_free_req(ep, req);
648 		if (allocated)
649 			(*allocated)--;
650 	}
651 }
652 
653 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
654 		void (*fn)(struct usb_ep *, struct usb_request *),
655 		int *allocated)
656 {
657 	int			i;
658 	struct usb_request	*req;
659 	int n = allocated ? QUEUE_SIZE - *allocated : QUEUE_SIZE;
660 
661 	/* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
662 	 * do quite that many this time, don't fail ... we just won't
663 	 * be as speedy as we might otherwise be.
664 	 */
665 	for (i = 0; i < n; i++) {
666 		req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
667 		if (!req)
668 			return list_empty(head) ? -ENOMEM : 0;
669 		req->complete = fn;
670 		list_add_tail(&req->list, head);
671 		if (allocated)
672 			(*allocated)++;
673 	}
674 	return 0;
675 }
676 
677 /**
678  * gs_start_io - start USB I/O streams
679  * @dev: encapsulates endpoints to use
680  * Context: holding port_lock; port_tty and port_usb are non-null
681  *
682  * We only start I/O when something is connected to both sides of
683  * this port.  If nothing is listening on the host side, we may
684  * be pointlessly filling up our TX buffers and FIFO.
685  */
686 static int gs_start_io(struct gs_port *port)
687 {
688 	struct list_head	*head = &port->read_pool;
689 	struct usb_ep		*ep = port->port_usb->out;
690 	int			status;
691 	unsigned		started;
692 
693 	/* Allocate RX and TX I/O buffers.  We can't easily do this much
694 	 * earlier (with GFP_KERNEL) because the requests are coupled to
695 	 * endpoints, as are the packet sizes we'll be using.  Different
696 	 * configurations may use different endpoints with a given port;
697 	 * and high speed vs full speed changes packet sizes too.
698 	 */
699 	status = gs_alloc_requests(ep, head, gs_read_complete,
700 		&port->read_allocated);
701 	if (status)
702 		return status;
703 
704 	status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
705 			gs_write_complete, &port->write_allocated);
706 	if (status) {
707 		gs_free_requests(ep, head, &port->read_allocated);
708 		return status;
709 	}
710 
711 	/* queue read requests */
712 	port->n_read = 0;
713 	started = gs_start_rx(port);
714 
715 	/* unblock any pending writes into our circular buffer */
716 	if (started) {
717 		tty_wakeup(port->port.tty);
718 	} else {
719 		gs_free_requests(ep, head, &port->read_allocated);
720 		gs_free_requests(port->port_usb->in, &port->write_pool,
721 			&port->write_allocated);
722 		status = -EIO;
723 	}
724 
725 	return status;
726 }
727 
728 /*-------------------------------------------------------------------------*/
729 
730 /* TTY Driver */
731 
732 /*
733  * gs_open sets up the link between a gs_port and its associated TTY.
734  * That link is broken *only* by TTY close(), and all driver methods
735  * know that.
736  */
737 static int gs_open(struct tty_struct *tty, struct file *file)
738 {
739 	int		port_num = tty->index;
740 	struct gs_port	*port;
741 	int		status;
742 
743 	do {
744 		mutex_lock(&ports[port_num].lock);
745 		port = ports[port_num].port;
746 		if (!port)
747 			status = -ENODEV;
748 		else {
749 			spin_lock_irq(&port->port_lock);
750 
751 			/* already open?  Great. */
752 			if (port->port.count) {
753 				status = 0;
754 				port->port.count++;
755 
756 			/* currently opening/closing? wait ... */
757 			} else if (port->openclose) {
758 				status = -EBUSY;
759 
760 			/* ... else we do the work */
761 			} else {
762 				status = -EAGAIN;
763 				port->openclose = true;
764 			}
765 			spin_unlock_irq(&port->port_lock);
766 		}
767 		mutex_unlock(&ports[port_num].lock);
768 
769 		switch (status) {
770 		default:
771 			/* fully handled */
772 			return status;
773 		case -EAGAIN:
774 			/* must do the work */
775 			break;
776 		case -EBUSY:
777 			/* wait for EAGAIN task to finish */
778 			msleep(1);
779 			/* REVISIT could have a waitchannel here, if
780 			 * concurrent open performance is important
781 			 */
782 			break;
783 		}
784 	} while (status != -EAGAIN);
785 
786 	/* Do the "real open" */
787 	spin_lock_irq(&port->port_lock);
788 
789 	/* allocate circular buffer on first open */
790 	if (port->port_write_buf.buf_buf == NULL) {
791 
792 		spin_unlock_irq(&port->port_lock);
793 		status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
794 		spin_lock_irq(&port->port_lock);
795 
796 		if (status) {
797 			pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
798 				port->port_num, tty, file);
799 			port->openclose = false;
800 			goto exit_unlock_port;
801 		}
802 	}
803 
804 	/* REVISIT if REMOVED (ports[].port NULL), abort the open
805 	 * to let rmmod work faster (but this way isn't wrong).
806 	 */
807 
808 	/* REVISIT maybe wait for "carrier detect" */
809 
810 	tty->driver_data = port;
811 	port->port.tty = tty;
812 
813 	port->port.count = 1;
814 	port->openclose = false;
815 
816 	/* if connected, start the I/O stream */
817 	if (port->port_usb) {
818 		struct gserial	*gser = port->port_usb;
819 
820 		pr_debug("gs_open: start ttyGS%d\n", port->port_num);
821 		gs_start_io(port);
822 
823 		if (gser->connect)
824 			gser->connect(gser);
825 	}
826 
827 	pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
828 
829 	status = 0;
830 
831 exit_unlock_port:
832 	spin_unlock_irq(&port->port_lock);
833 	return status;
834 }
835 
836 static int gs_writes_finished(struct gs_port *p)
837 {
838 	int cond;
839 
840 	/* return true on disconnect or empty buffer */
841 	spin_lock_irq(&p->port_lock);
842 	cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
843 	spin_unlock_irq(&p->port_lock);
844 
845 	return cond;
846 }
847 
848 static void gs_close(struct tty_struct *tty, struct file *file)
849 {
850 	struct gs_port *port = tty->driver_data;
851 	struct gserial	*gser;
852 
853 	spin_lock_irq(&port->port_lock);
854 
855 	if (port->port.count != 1) {
856 		if (port->port.count == 0)
857 			WARN_ON(1);
858 		else
859 			--port->port.count;
860 		goto exit;
861 	}
862 
863 	pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
864 
865 	/* mark port as closing but in use; we can drop port lock
866 	 * and sleep if necessary
867 	 */
868 	port->openclose = true;
869 	port->port.count = 0;
870 
871 	gser = port->port_usb;
872 	if (gser && gser->disconnect)
873 		gser->disconnect(gser);
874 
875 	/* wait for circular write buffer to drain, disconnect, or at
876 	 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
877 	 */
878 	if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
879 		spin_unlock_irq(&port->port_lock);
880 		wait_event_interruptible_timeout(port->drain_wait,
881 					gs_writes_finished(port),
882 					GS_CLOSE_TIMEOUT * HZ);
883 		spin_lock_irq(&port->port_lock);
884 		gser = port->port_usb;
885 	}
886 
887 	/* Iff we're disconnected, there can be no I/O in flight so it's
888 	 * ok to free the circular buffer; else just scrub it.  And don't
889 	 * let the push tasklet fire again until we're re-opened.
890 	 */
891 	if (gser == NULL)
892 		gs_buf_free(&port->port_write_buf);
893 	else
894 		gs_buf_clear(&port->port_write_buf);
895 
896 	port->port.tty = NULL;
897 
898 	port->openclose = false;
899 
900 	pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
901 			port->port_num, tty, file);
902 
903 	wake_up(&port->close_wait);
904 exit:
905 	spin_unlock_irq(&port->port_lock);
906 }
907 
908 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
909 {
910 	struct gs_port	*port = tty->driver_data;
911 	unsigned long	flags;
912 
913 	pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
914 			port->port_num, tty, count);
915 
916 	spin_lock_irqsave(&port->port_lock, flags);
917 	if (count)
918 		count = gs_buf_put(&port->port_write_buf, buf, count);
919 	/* treat count == 0 as flush_chars() */
920 	if (port->port_usb)
921 		gs_start_tx(port);
922 	spin_unlock_irqrestore(&port->port_lock, flags);
923 
924 	return count;
925 }
926 
927 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
928 {
929 	struct gs_port	*port = tty->driver_data;
930 	unsigned long	flags;
931 	int		status;
932 
933 	pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %ps\n",
934 		port->port_num, tty, ch, __builtin_return_address(0));
935 
936 	spin_lock_irqsave(&port->port_lock, flags);
937 	status = gs_buf_put(&port->port_write_buf, &ch, 1);
938 	spin_unlock_irqrestore(&port->port_lock, flags);
939 
940 	return status;
941 }
942 
943 static void gs_flush_chars(struct tty_struct *tty)
944 {
945 	struct gs_port	*port = tty->driver_data;
946 	unsigned long	flags;
947 
948 	pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
949 
950 	spin_lock_irqsave(&port->port_lock, flags);
951 	if (port->port_usb)
952 		gs_start_tx(port);
953 	spin_unlock_irqrestore(&port->port_lock, flags);
954 }
955 
956 static int gs_write_room(struct tty_struct *tty)
957 {
958 	struct gs_port	*port = tty->driver_data;
959 	unsigned long	flags;
960 	int		room = 0;
961 
962 	spin_lock_irqsave(&port->port_lock, flags);
963 	if (port->port_usb)
964 		room = gs_buf_space_avail(&port->port_write_buf);
965 	spin_unlock_irqrestore(&port->port_lock, flags);
966 
967 	pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
968 		port->port_num, tty, room);
969 
970 	return room;
971 }
972 
973 static int gs_chars_in_buffer(struct tty_struct *tty)
974 {
975 	struct gs_port	*port = tty->driver_data;
976 	unsigned long	flags;
977 	int		chars = 0;
978 
979 	spin_lock_irqsave(&port->port_lock, flags);
980 	chars = gs_buf_data_avail(&port->port_write_buf);
981 	spin_unlock_irqrestore(&port->port_lock, flags);
982 
983 	pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
984 		port->port_num, tty, chars);
985 
986 	return chars;
987 }
988 
989 /* undo side effects of setting TTY_THROTTLED */
990 static void gs_unthrottle(struct tty_struct *tty)
991 {
992 	struct gs_port		*port = tty->driver_data;
993 	unsigned long		flags;
994 
995 	spin_lock_irqsave(&port->port_lock, flags);
996 	if (port->port_usb) {
997 		/* Kickstart read queue processing.  We don't do xon/xoff,
998 		 * rts/cts, or other handshaking with the host, but if the
999 		 * read queue backs up enough we'll be NAKing OUT packets.
1000 		 */
1001 		tasklet_schedule(&port->push);
1002 		pr_vdebug("ttyGS%d: unthrottle\n", port->port_num);
1003 	}
1004 	spin_unlock_irqrestore(&port->port_lock, flags);
1005 }
1006 
1007 static int gs_break_ctl(struct tty_struct *tty, int duration)
1008 {
1009 	struct gs_port	*port = tty->driver_data;
1010 	int		status = 0;
1011 	struct gserial	*gser;
1012 
1013 	pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
1014 			port->port_num, duration);
1015 
1016 	spin_lock_irq(&port->port_lock);
1017 	gser = port->port_usb;
1018 	if (gser && gser->send_break)
1019 		status = gser->send_break(gser, duration);
1020 	spin_unlock_irq(&port->port_lock);
1021 
1022 	return status;
1023 }
1024 
1025 static const struct tty_operations gs_tty_ops = {
1026 	.open =			gs_open,
1027 	.close =		gs_close,
1028 	.write =		gs_write,
1029 	.put_char =		gs_put_char,
1030 	.flush_chars =		gs_flush_chars,
1031 	.write_room =		gs_write_room,
1032 	.chars_in_buffer =	gs_chars_in_buffer,
1033 	.unthrottle =		gs_unthrottle,
1034 	.break_ctl =		gs_break_ctl,
1035 };
1036 
1037 /*-------------------------------------------------------------------------*/
1038 
1039 static struct tty_driver *gs_tty_driver;
1040 
1041 #ifdef CONFIG_U_SERIAL_CONSOLE
1042 
1043 static struct gscons_info gscons_info;
1044 static struct console gserial_cons;
1045 
1046 static struct usb_request *gs_request_new(struct usb_ep *ep)
1047 {
1048 	struct usb_request *req = usb_ep_alloc_request(ep, GFP_ATOMIC);
1049 	if (!req)
1050 		return NULL;
1051 
1052 	req->buf = kmalloc(ep->maxpacket, GFP_ATOMIC);
1053 	if (!req->buf) {
1054 		usb_ep_free_request(ep, req);
1055 		return NULL;
1056 	}
1057 
1058 	return req;
1059 }
1060 
1061 static void gs_request_free(struct usb_request *req, struct usb_ep *ep)
1062 {
1063 	if (!req)
1064 		return;
1065 
1066 	kfree(req->buf);
1067 	usb_ep_free_request(ep, req);
1068 }
1069 
1070 static void gs_complete_out(struct usb_ep *ep, struct usb_request *req)
1071 {
1072 	struct gscons_info *info = &gscons_info;
1073 
1074 	switch (req->status) {
1075 	default:
1076 		pr_warn("%s: unexpected %s status %d\n",
1077 			__func__, ep->name, req->status);
1078 		/* fall through */
1079 	case 0:
1080 		/* normal completion */
1081 		spin_lock(&info->con_lock);
1082 		info->req_busy = 0;
1083 		spin_unlock(&info->con_lock);
1084 
1085 		wake_up_process(info->console_thread);
1086 		break;
1087 	case -ESHUTDOWN:
1088 		/* disconnect */
1089 		pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
1090 		break;
1091 	}
1092 }
1093 
1094 static int gs_console_connect(int port_num)
1095 {
1096 	struct gscons_info *info = &gscons_info;
1097 	struct gs_port *port;
1098 	struct usb_ep *ep;
1099 
1100 	if (port_num != gserial_cons.index) {
1101 		pr_err("%s: port num [%d] is not support console\n",
1102 		       __func__, port_num);
1103 		return -ENXIO;
1104 	}
1105 
1106 	port = ports[port_num].port;
1107 	ep = port->port_usb->in;
1108 	if (!info->console_req) {
1109 		info->console_req = gs_request_new(ep);
1110 		if (!info->console_req)
1111 			return -ENOMEM;
1112 		info->console_req->complete = gs_complete_out;
1113 	}
1114 
1115 	info->port = port;
1116 	spin_lock(&info->con_lock);
1117 	info->req_busy = 0;
1118 	spin_unlock(&info->con_lock);
1119 	pr_vdebug("port[%d] console connect!\n", port_num);
1120 	return 0;
1121 }
1122 
1123 static void gs_console_disconnect(struct usb_ep *ep)
1124 {
1125 	struct gscons_info *info = &gscons_info;
1126 	struct usb_request *req = info->console_req;
1127 
1128 	gs_request_free(req, ep);
1129 	info->console_req = NULL;
1130 }
1131 
1132 static int gs_console_thread(void *data)
1133 {
1134 	struct gscons_info *info = &gscons_info;
1135 	struct gs_port *port;
1136 	struct usb_request *req;
1137 	struct usb_ep *ep;
1138 	int xfer, ret, count, size;
1139 
1140 	do {
1141 		port = info->port;
1142 		set_current_state(TASK_INTERRUPTIBLE);
1143 		if (!port || !port->port_usb
1144 		    || !port->port_usb->in || !info->console_req)
1145 			goto sched;
1146 
1147 		req = info->console_req;
1148 		ep = port->port_usb->in;
1149 
1150 		spin_lock_irq(&info->con_lock);
1151 		count = gs_buf_data_avail(&info->con_buf);
1152 		size = ep->maxpacket;
1153 
1154 		if (count > 0 && !info->req_busy) {
1155 			set_current_state(TASK_RUNNING);
1156 			if (count < size)
1157 				size = count;
1158 
1159 			xfer = gs_buf_get(&info->con_buf, req->buf, size);
1160 			req->length = xfer;
1161 
1162 			spin_unlock(&info->con_lock);
1163 			ret = usb_ep_queue(ep, req, GFP_ATOMIC);
1164 			spin_lock(&info->con_lock);
1165 			if (ret < 0)
1166 				info->req_busy = 0;
1167 			else
1168 				info->req_busy = 1;
1169 
1170 			spin_unlock_irq(&info->con_lock);
1171 		} else {
1172 			spin_unlock_irq(&info->con_lock);
1173 sched:
1174 			if (kthread_should_stop()) {
1175 				set_current_state(TASK_RUNNING);
1176 				break;
1177 			}
1178 			schedule();
1179 		}
1180 	} while (1);
1181 
1182 	return 0;
1183 }
1184 
1185 static int gs_console_setup(struct console *co, char *options)
1186 {
1187 	struct gscons_info *info = &gscons_info;
1188 	int status;
1189 
1190 	info->port = NULL;
1191 	info->console_req = NULL;
1192 	info->req_busy = 0;
1193 	spin_lock_init(&info->con_lock);
1194 
1195 	status = gs_buf_alloc(&info->con_buf, GS_CONSOLE_BUF_SIZE);
1196 	if (status) {
1197 		pr_err("%s: allocate console buffer failed\n", __func__);
1198 		return status;
1199 	}
1200 
1201 	info->console_thread = kthread_create(gs_console_thread,
1202 					      co, "gs_console");
1203 	if (IS_ERR(info->console_thread)) {
1204 		pr_err("%s: cannot create console thread\n", __func__);
1205 		gs_buf_free(&info->con_buf);
1206 		return PTR_ERR(info->console_thread);
1207 	}
1208 	wake_up_process(info->console_thread);
1209 
1210 	return 0;
1211 }
1212 
1213 static void gs_console_write(struct console *co,
1214 			     const char *buf, unsigned count)
1215 {
1216 	struct gscons_info *info = &gscons_info;
1217 	unsigned long flags;
1218 
1219 	spin_lock_irqsave(&info->con_lock, flags);
1220 	gs_buf_put(&info->con_buf, buf, count);
1221 	spin_unlock_irqrestore(&info->con_lock, flags);
1222 
1223 	wake_up_process(info->console_thread);
1224 }
1225 
1226 static struct tty_driver *gs_console_device(struct console *co, int *index)
1227 {
1228 	struct tty_driver **p = (struct tty_driver **)co->data;
1229 
1230 	if (!*p)
1231 		return NULL;
1232 
1233 	*index = co->index;
1234 	return *p;
1235 }
1236 
1237 static struct console gserial_cons = {
1238 	.name =		"ttyGS",
1239 	.write =	gs_console_write,
1240 	.device =	gs_console_device,
1241 	.setup =	gs_console_setup,
1242 	.flags =	CON_PRINTBUFFER,
1243 	.index =	-1,
1244 	.data =		&gs_tty_driver,
1245 };
1246 
1247 static void gserial_console_init(void)
1248 {
1249 	register_console(&gserial_cons);
1250 }
1251 
1252 static void gserial_console_exit(void)
1253 {
1254 	struct gscons_info *info = &gscons_info;
1255 
1256 	unregister_console(&gserial_cons);
1257 	if (!IS_ERR_OR_NULL(info->console_thread))
1258 		kthread_stop(info->console_thread);
1259 	gs_buf_free(&info->con_buf);
1260 }
1261 
1262 #else
1263 
1264 static int gs_console_connect(int port_num)
1265 {
1266 	return 0;
1267 }
1268 
1269 static void gs_console_disconnect(struct usb_ep *ep)
1270 {
1271 }
1272 
1273 static void gserial_console_init(void)
1274 {
1275 }
1276 
1277 static void gserial_console_exit(void)
1278 {
1279 }
1280 
1281 #endif
1282 
1283 static int
1284 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1285 {
1286 	struct gs_port	*port;
1287 	int		ret = 0;
1288 
1289 	mutex_lock(&ports[port_num].lock);
1290 	if (ports[port_num].port) {
1291 		ret = -EBUSY;
1292 		goto out;
1293 	}
1294 
1295 	port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1296 	if (port == NULL) {
1297 		ret = -ENOMEM;
1298 		goto out;
1299 	}
1300 
1301 	tty_port_init(&port->port);
1302 	spin_lock_init(&port->port_lock);
1303 	init_waitqueue_head(&port->drain_wait);
1304 	init_waitqueue_head(&port->close_wait);
1305 
1306 	tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1307 
1308 	INIT_LIST_HEAD(&port->read_pool);
1309 	INIT_LIST_HEAD(&port->read_queue);
1310 	INIT_LIST_HEAD(&port->write_pool);
1311 
1312 	port->port_num = port_num;
1313 	port->port_line_coding = *coding;
1314 
1315 	ports[port_num].port = port;
1316 out:
1317 	mutex_unlock(&ports[port_num].lock);
1318 	return ret;
1319 }
1320 
1321 static int gs_closed(struct gs_port *port)
1322 {
1323 	int cond;
1324 
1325 	spin_lock_irq(&port->port_lock);
1326 	cond = (port->port.count == 0) && !port->openclose;
1327 	spin_unlock_irq(&port->port_lock);
1328 	return cond;
1329 }
1330 
1331 static void gserial_free_port(struct gs_port *port)
1332 {
1333 	tasklet_kill(&port->push);
1334 	/* wait for old opens to finish */
1335 	wait_event(port->close_wait, gs_closed(port));
1336 	WARN_ON(port->port_usb != NULL);
1337 	tty_port_destroy(&port->port);
1338 	kfree(port);
1339 }
1340 
1341 void gserial_free_line(unsigned char port_num)
1342 {
1343 	struct gs_port	*port;
1344 
1345 	mutex_lock(&ports[port_num].lock);
1346 	if (WARN_ON(!ports[port_num].port)) {
1347 		mutex_unlock(&ports[port_num].lock);
1348 		return;
1349 	}
1350 	port = ports[port_num].port;
1351 	ports[port_num].port = NULL;
1352 	mutex_unlock(&ports[port_num].lock);
1353 
1354 	gserial_free_port(port);
1355 	tty_unregister_device(gs_tty_driver, port_num);
1356 	gserial_console_exit();
1357 }
1358 EXPORT_SYMBOL_GPL(gserial_free_line);
1359 
1360 int gserial_alloc_line(unsigned char *line_num)
1361 {
1362 	struct usb_cdc_line_coding	coding;
1363 	struct device			*tty_dev;
1364 	int				ret;
1365 	int				port_num;
1366 
1367 	coding.dwDTERate = cpu_to_le32(9600);
1368 	coding.bCharFormat = 8;
1369 	coding.bParityType = USB_CDC_NO_PARITY;
1370 	coding.bDataBits = USB_CDC_1_STOP_BITS;
1371 
1372 	for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) {
1373 		ret = gs_port_alloc(port_num, &coding);
1374 		if (ret == -EBUSY)
1375 			continue;
1376 		if (ret)
1377 			return ret;
1378 		break;
1379 	}
1380 	if (ret)
1381 		return ret;
1382 
1383 	/* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1384 
1385 	tty_dev = tty_port_register_device(&ports[port_num].port->port,
1386 			gs_tty_driver, port_num, NULL);
1387 	if (IS_ERR(tty_dev)) {
1388 		struct gs_port	*port;
1389 		pr_err("%s: failed to register tty for port %d, err %ld\n",
1390 				__func__, port_num, PTR_ERR(tty_dev));
1391 
1392 		ret = PTR_ERR(tty_dev);
1393 		port = ports[port_num].port;
1394 		ports[port_num].port = NULL;
1395 		gserial_free_port(port);
1396 		goto err;
1397 	}
1398 	*line_num = port_num;
1399 	gserial_console_init();
1400 err:
1401 	return ret;
1402 }
1403 EXPORT_SYMBOL_GPL(gserial_alloc_line);
1404 
1405 /**
1406  * gserial_connect - notify TTY I/O glue that USB link is active
1407  * @gser: the function, set up with endpoints and descriptors
1408  * @port_num: which port is active
1409  * Context: any (usually from irq)
1410  *
1411  * This is called activate endpoints and let the TTY layer know that
1412  * the connection is active ... not unlike "carrier detect".  It won't
1413  * necessarily start I/O queues; unless the TTY is held open by any
1414  * task, there would be no point.  However, the endpoints will be
1415  * activated so the USB host can perform I/O, subject to basic USB
1416  * hardware flow control.
1417  *
1418  * Caller needs to have set up the endpoints and USB function in @dev
1419  * before calling this, as well as the appropriate (speed-specific)
1420  * endpoint descriptors, and also have allocate @port_num by calling
1421  * @gserial_alloc_line().
1422  *
1423  * Returns negative errno or zero.
1424  * On success, ep->driver_data will be overwritten.
1425  */
1426 int gserial_connect(struct gserial *gser, u8 port_num)
1427 {
1428 	struct gs_port	*port;
1429 	unsigned long	flags;
1430 	int		status;
1431 
1432 	if (port_num >= MAX_U_SERIAL_PORTS)
1433 		return -ENXIO;
1434 
1435 	port = ports[port_num].port;
1436 	if (!port) {
1437 		pr_err("serial line %d not allocated.\n", port_num);
1438 		return -EINVAL;
1439 	}
1440 	if (port->port_usb) {
1441 		pr_err("serial line %d is in use.\n", port_num);
1442 		return -EBUSY;
1443 	}
1444 
1445 	/* activate the endpoints */
1446 	status = usb_ep_enable(gser->in);
1447 	if (status < 0)
1448 		return status;
1449 	gser->in->driver_data = port;
1450 
1451 	status = usb_ep_enable(gser->out);
1452 	if (status < 0)
1453 		goto fail_out;
1454 	gser->out->driver_data = port;
1455 
1456 	/* then tell the tty glue that I/O can work */
1457 	spin_lock_irqsave(&port->port_lock, flags);
1458 	gser->ioport = port;
1459 	port->port_usb = gser;
1460 
1461 	/* REVISIT unclear how best to handle this state...
1462 	 * we don't really couple it with the Linux TTY.
1463 	 */
1464 	gser->port_line_coding = port->port_line_coding;
1465 
1466 	/* REVISIT if waiting on "carrier detect", signal. */
1467 
1468 	/* if it's already open, start I/O ... and notify the serial
1469 	 * protocol about open/close status (connect/disconnect).
1470 	 */
1471 	if (port->port.count) {
1472 		pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1473 		gs_start_io(port);
1474 		if (gser->connect)
1475 			gser->connect(gser);
1476 	} else {
1477 		if (gser->disconnect)
1478 			gser->disconnect(gser);
1479 	}
1480 
1481 	status = gs_console_connect(port_num);
1482 	spin_unlock_irqrestore(&port->port_lock, flags);
1483 
1484 	return status;
1485 
1486 fail_out:
1487 	usb_ep_disable(gser->in);
1488 	return status;
1489 }
1490 EXPORT_SYMBOL_GPL(gserial_connect);
1491 /**
1492  * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1493  * @gser: the function, on which gserial_connect() was called
1494  * Context: any (usually from irq)
1495  *
1496  * This is called to deactivate endpoints and let the TTY layer know
1497  * that the connection went inactive ... not unlike "hangup".
1498  *
1499  * On return, the state is as if gserial_connect() had never been called;
1500  * there is no active USB I/O on these endpoints.
1501  */
1502 void gserial_disconnect(struct gserial *gser)
1503 {
1504 	struct gs_port	*port = gser->ioport;
1505 	unsigned long	flags;
1506 
1507 	if (!port)
1508 		return;
1509 
1510 	/* tell the TTY glue not to do I/O here any more */
1511 	spin_lock_irqsave(&port->port_lock, flags);
1512 
1513 	/* REVISIT as above: how best to track this? */
1514 	port->port_line_coding = gser->port_line_coding;
1515 
1516 	port->port_usb = NULL;
1517 	gser->ioport = NULL;
1518 	if (port->port.count > 0 || port->openclose) {
1519 		wake_up_interruptible(&port->drain_wait);
1520 		if (port->port.tty)
1521 			tty_hangup(port->port.tty);
1522 	}
1523 	spin_unlock_irqrestore(&port->port_lock, flags);
1524 
1525 	/* disable endpoints, aborting down any active I/O */
1526 	usb_ep_disable(gser->out);
1527 	usb_ep_disable(gser->in);
1528 
1529 	/* finally, free any unused/unusable I/O buffers */
1530 	spin_lock_irqsave(&port->port_lock, flags);
1531 	if (port->port.count == 0 && !port->openclose)
1532 		gs_buf_free(&port->port_write_buf);
1533 	gs_free_requests(gser->out, &port->read_pool, NULL);
1534 	gs_free_requests(gser->out, &port->read_queue, NULL);
1535 	gs_free_requests(gser->in, &port->write_pool, NULL);
1536 
1537 	port->read_allocated = port->read_started =
1538 		port->write_allocated = port->write_started = 0;
1539 
1540 	gs_console_disconnect(gser->in);
1541 	spin_unlock_irqrestore(&port->port_lock, flags);
1542 }
1543 EXPORT_SYMBOL_GPL(gserial_disconnect);
1544 
1545 static int userial_init(void)
1546 {
1547 	unsigned			i;
1548 	int				status;
1549 
1550 	gs_tty_driver = alloc_tty_driver(MAX_U_SERIAL_PORTS);
1551 	if (!gs_tty_driver)
1552 		return -ENOMEM;
1553 
1554 	gs_tty_driver->driver_name = "g_serial";
1555 	gs_tty_driver->name = "ttyGS";
1556 	/* uses dynamically assigned dev_t values */
1557 
1558 	gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1559 	gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1560 	gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1561 	gs_tty_driver->init_termios = tty_std_termios;
1562 
1563 	/* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1564 	 * MS-Windows.  Otherwise, most of these flags shouldn't affect
1565 	 * anything unless we were to actually hook up to a serial line.
1566 	 */
1567 	gs_tty_driver->init_termios.c_cflag =
1568 			B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1569 	gs_tty_driver->init_termios.c_ispeed = 9600;
1570 	gs_tty_driver->init_termios.c_ospeed = 9600;
1571 
1572 	tty_set_operations(gs_tty_driver, &gs_tty_ops);
1573 	for (i = 0; i < MAX_U_SERIAL_PORTS; i++)
1574 		mutex_init(&ports[i].lock);
1575 
1576 	/* export the driver ... */
1577 	status = tty_register_driver(gs_tty_driver);
1578 	if (status) {
1579 		pr_err("%s: cannot register, err %d\n",
1580 				__func__, status);
1581 		goto fail;
1582 	}
1583 
1584 	pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1585 			MAX_U_SERIAL_PORTS,
1586 			(MAX_U_SERIAL_PORTS == 1) ? "" : "s");
1587 
1588 	return status;
1589 fail:
1590 	put_tty_driver(gs_tty_driver);
1591 	gs_tty_driver = NULL;
1592 	return status;
1593 }
1594 module_init(userial_init);
1595 
1596 static void userial_cleanup(void)
1597 {
1598 	tty_unregister_driver(gs_tty_driver);
1599 	put_tty_driver(gs_tty_driver);
1600 	gs_tty_driver = NULL;
1601 }
1602 module_exit(userial_cleanup);
1603 
1604 MODULE_LICENSE("GPL");
1605