u_serial.c 38.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * u_serial.c - utilities for USB gadget "serial port"/TTY support
 *
 * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
 * Copyright (C) 2008 David Brownell
 * Copyright (C) 2008 by Nokia Corporation
 *
 * This code also borrows from usbserial.c, which is
 * Copyright (C) 1999 - 2002 Greg Kroah-Hartman (greg@kroah.com)
 * Copyright (C) 2000 Peter Berger (pberger@brimson.com)
 * Copyright (C) 2000 Al Borchers (alborchers@steinerpoint.com)
 *
 * This software is distributed under the terms of the GNU General
 * Public License ("GPL") as published by the Free Software Foundation,
 * either version 2 of that License or (at your option) any later version.
 */

/* #define VERBOSE_DEBUG */

#include <linux/kernel.h>
21
#include <linux/sched.h>
22 23 24 25 26
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
27
#include <linux/slab.h>
28
#include <linux/export.h>
29
#include <linux/module.h>
30 31
#include <linux/console.h>
#include <linux/kthread.h>
32 33 34 35 36 37 38 39 40

#include "u_serial.h"


/*
 * This component encapsulates the TTY layer glue needed to provide basic
 * "serial port" functionality through the USB gadget stack.  Each such
 * port is exposed through a /dev/ttyGS* node.
 *
41 42 43 44 45 46
 * After this module has been loaded, the individual TTY port can be requested
 * (gserial_alloc_line()) and it will stay available until they are removed
 * (gserial_free_line()). Each one may be connected to a USB function
 * (gserial_connect), or disconnected (with gserial_disconnect) when the USB
 * host issues a config change event. Data can only flow when the port is
 * connected to the host.
47 48 49 50 51 52 53 54 55 56 57 58 59
 *
 * A given TTY port can be made available in multiple configurations.
 * For example, each one might expose a ttyGS0 node which provides a
 * login application.  In one case that might use CDC ACM interface 0,
 * while another configuration might use interface 3 for that.  The
 * work to handle that (including descriptor management) is not part
 * of this component.
 *
 * Configurations may expose more than one TTY port.  For example, if
 * ttyGS0 provides login service, then ttyGS1 might provide dialer access
 * for a telephone or fax link.  And ttyGS2 might be something that just
 * needs a simple byte stream interface for some messaging protocol that
 * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
60 61
 *
 *
62 63 64 65 66
 * gserial is the lifecycle interface, used by USB functions
 * gs_port is the I/O nexus, used by the tty driver
 * tty_struct links to the tty/filesystem framework
 *
 * gserial <---> gs_port ... links will be null when the USB link is
67 68
 * inactive; managed by gserial_{connect,disconnect}().  each gserial
 * instance can wrap its own USB control protocol.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 *	gserial->ioport == usb_ep->driver_data ... gs_port
 *	gs_port->port_usb ... gserial
 *
 * gs_port <---> tty_struct ... links will be null when the TTY file
 * isn't opened; managed by gs_open()/gs_close()
 *	gserial->port_tty ... tty_struct
 *	tty_struct->driver_data ... gserial
 */

/* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
 * next layer of buffering.  For TX that's a circular buffer; for RX
 * consider it a NOP.  A third layer is provided by the TTY code.
 */
#define QUEUE_SIZE		16
#define WRITE_BUF_SIZE		8192		/* TX only */
84
#define GS_CONSOLE_BUF_SIZE	8192
85 86 87 88 89 90 91 92 93

/* circular buffer */
struct gs_buf {
	unsigned		buf_size;
	char			*buf_buf;
	char			*buf_get;
	char			*buf_put;
};

94 95 96 97 98 99 100 101 102 103 104
/* console info */
struct gscons_info {
	struct gs_port		*port;
	struct task_struct	*console_thread;
	struct gs_buf		con_buf;
	/* protect the buf and busy flag */
	spinlock_t		con_lock;
	int			req_busy;
	struct usb_request	*console_req;
};

105 106 107 108 109
/*
 * The port structure holds info for each port, one for each minor number
 * (and thus for each /dev/ node).
 */
struct gs_port {
J
Jiri Slaby 已提交
110
	struct tty_port		port;
111 112 113 114 115 116 117 118
	spinlock_t		port_lock;	/* guard port_* access */

	struct gserial		*port_usb;

	bool			openclose;	/* open/close in progress */
	u8			port_num;

	struct list_head	read_pool;
119 120
	int read_started;
	int read_allocated;
121 122
	struct list_head	read_queue;
	unsigned		n_read;
123 124 125
	struct tasklet_struct	push;

	struct list_head	write_pool;
126 127
	int write_started;
	int write_allocated;
128 129
	struct gs_buf		port_write_buf;
	wait_queue_head_t	drain_wait;	/* wait while writes drain */
130
	bool                    write_busy;
131
	wait_queue_head_t	close_wait;
132 133 134 135 136 137 138 139

	/* REVISIT this state ... */
	struct usb_cdc_line_coding port_line_coding;	/* 8-N-1 etc */
};

static struct portmaster {
	struct mutex	lock;			/* protect open/close */
	struct gs_port	*port;
140
} ports[MAX_U_SERIAL_PORTS];
141 142 143 144 145 146

#define GS_CLOSE_TIMEOUT		15		/* seconds */



#ifdef VERBOSE_DEBUG
147
#ifndef pr_vdebug
148 149
#define pr_vdebug(fmt, arg...) \
	pr_debug(fmt, ##arg)
150
#endif /* pr_vdebug */
151
#else
152
#ifndef pr_vdebug
153 154
#define pr_vdebug(fmt, arg...) \
	({ if (0) pr_debug(fmt, ##arg); })
155
#endif /* pr_vdebug */
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
#endif

/*-------------------------------------------------------------------------*/

/* Circular Buffer */

/*
 * gs_buf_alloc
 *
 * Allocate a circular buffer and all associated memory.
 */
static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
{
	gb->buf_buf = kmalloc(size, GFP_KERNEL);
	if (gb->buf_buf == NULL)
		return -ENOMEM;

	gb->buf_size = size;
	gb->buf_put = gb->buf_buf;
	gb->buf_get = gb->buf_buf;

	return 0;
}

/*
 * gs_buf_free
 *
 * Free the buffer and all associated memory.
 */
static void gs_buf_free(struct gs_buf *gb)
{
	kfree(gb->buf_buf);
	gb->buf_buf = NULL;
}

/*
 * gs_buf_clear
 *
 * Clear out all data in the circular buffer.
 */
static void gs_buf_clear(struct gs_buf *gb)
{
	gb->buf_get = gb->buf_put;
	/* equivalent to a get of all data available */
}

/*
 * gs_buf_data_avail
 *
205
 * Return the number of bytes of data written into the circular
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
 * buffer.
 */
static unsigned gs_buf_data_avail(struct gs_buf *gb)
{
	return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
}

/*
 * gs_buf_space_avail
 *
 * Return the number of bytes of space available in the circular
 * buffer.
 */
static unsigned gs_buf_space_avail(struct gs_buf *gb)
{
	return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
}

/*
 * gs_buf_put
 *
 * Copy data data from a user buffer and put it into the circular buffer.
 * Restrict to the amount of space available.
 *
 * Return the number of bytes copied.
 */
static unsigned
gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
{
	unsigned len;

	len  = gs_buf_space_avail(gb);
	if (count > len)
		count = len;

	if (count == 0)
		return 0;

	len = gb->buf_buf + gb->buf_size - gb->buf_put;
	if (count > len) {
		memcpy(gb->buf_put, buf, len);
		memcpy(gb->buf_buf, buf+len, count - len);
		gb->buf_put = gb->buf_buf + count - len;
	} else {
		memcpy(gb->buf_put, buf, count);
		if (count < len)
			gb->buf_put += count;
		else /* count == len */
			gb->buf_put = gb->buf_buf;
	}

	return count;
}

/*
 * gs_buf_get
 *
 * Get data from the circular buffer and copy to the given buffer.
 * Restrict to the amount of data available.
 *
 * Return the number of bytes copied.
 */
static unsigned
gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
{
	unsigned len;

	len = gs_buf_data_avail(gb);
	if (count > len)
		count = len;

	if (count == 0)
		return 0;

	len = gb->buf_buf + gb->buf_size - gb->buf_get;
	if (count > len) {
		memcpy(buf, gb->buf_get, len);
		memcpy(buf+len, gb->buf_buf, count - len);
		gb->buf_get = gb->buf_buf + count - len;
	} else {
		memcpy(buf, gb->buf_get, count);
		if (count < len)
			gb->buf_get += count;
		else /* count == len */
			gb->buf_get = gb->buf_buf;
	}

	return count;
}

/*-------------------------------------------------------------------------*/

/* I/O glue between TTY (upper) and USB function (lower) driver layers */

/*
 * gs_alloc_req
 *
 * Allocate a usb_request and its buffer.  Returns a pointer to the
 * usb_request or NULL if there is an error.
 */
306
struct usb_request *
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
{
	struct usb_request *req;

	req = usb_ep_alloc_request(ep, kmalloc_flags);

	if (req != NULL) {
		req->length = len;
		req->buf = kmalloc(len, kmalloc_flags);
		if (req->buf == NULL) {
			usb_ep_free_request(ep, req);
			return NULL;
		}
	}

	return req;
}
324
EXPORT_SYMBOL_GPL(gs_alloc_req);
325 326 327 328 329 330

/*
 * gs_free_req
 *
 * Free a usb_request and its buffer.
 */
331
void gs_free_req(struct usb_ep *ep, struct usb_request *req)
332 333 334 335
{
	kfree(req->buf);
	usb_ep_free_request(ep, req);
}
336
EXPORT_SYMBOL_GPL(gs_free_req);
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

/*
 * gs_send_packet
 *
 * If there is data to send, a packet is built in the given
 * buffer and the size is returned.  If there is no data to
 * send, 0 is returned.
 *
 * Called with port_lock held.
 */
static unsigned
gs_send_packet(struct gs_port *port, char *packet, unsigned size)
{
	unsigned len;

	len = gs_buf_data_avail(&port->port_write_buf);
	if (len < size)
		size = len;
	if (size != 0)
		size = gs_buf_get(&port->port_write_buf, packet, size);
	return size;
}

/*
 * gs_start_tx
 *
 * This function finds available write requests, calls
 * gs_send_packet to fill these packets with data, and
 * continues until either there are no more write requests
 * available or no more data to send.  This function is
 * run whenever data arrives or write requests are available.
 *
 * Context: caller owns port_lock; port_usb is non-null.
 */
static int gs_start_tx(struct gs_port *port)
/*
__releases(&port->port_lock)
__acquires(&port->port_lock)
*/
{
	struct list_head	*pool = &port->write_pool;
378
	struct usb_ep		*in;
379 380 381
	int			status = 0;
	bool			do_tty_wake = false;

382 383 384 385 386
	if (!port->port_usb)
		return status;

	in = port->port_usb->in;

387
	while (!port->write_busy && !list_empty(pool)) {
388 389 390
		struct usb_request	*req;
		int			len;

391 392 393
		if (port->write_started >= QUEUE_SIZE)
			break;

394 395 396 397 398 399 400 401 402 403
		req = list_entry(pool->next, struct usb_request, list);
		len = gs_send_packet(port, req->buf, in->maxpacket);
		if (len == 0) {
			wake_up_interruptible(&port->drain_wait);
			break;
		}
		do_tty_wake = true;

		req->length = len;
		list_del(&req->list);
404
		req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
405

406 407 408
		pr_vdebug("ttyGS%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
			  port->port_num, len, *((u8 *)req->buf),
			  *((u8 *)req->buf+1), *((u8 *)req->buf+2));
409 410 411 412 413 414 415 416

		/* Drop lock while we call out of driver; completions
		 * could be issued while we do so.  Disconnection may
		 * happen too; maybe immediately before we queue this!
		 *
		 * NOTE that we may keep sending data for a while after
		 * the TTY closed (dev->ioport->port_tty is NULL).
		 */
417
		port->write_busy = true;
418 419 420
		spin_unlock(&port->port_lock);
		status = usb_ep_queue(in, req, GFP_ATOMIC);
		spin_lock(&port->port_lock);
421
		port->write_busy = false;
422 423 424 425 426 427 428 429

		if (status) {
			pr_debug("%s: %s %s err %d\n",
					__func__, "queue", in->name, status);
			list_add(&req->list, pool);
			break;
		}

430 431
		port->write_started++;

432 433 434 435 436
		/* abort immediately after disconnect */
		if (!port->port_usb)
			break;
	}

437 438
	if (do_tty_wake && port->port.tty)
		tty_wakeup(port->port.tty);
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	return status;
}

/*
 * Context: caller owns port_lock, and port_usb is set
 */
static unsigned gs_start_rx(struct gs_port *port)
/*
__releases(&port->port_lock)
__acquires(&port->port_lock)
*/
{
	struct list_head	*pool = &port->read_pool;
	struct usb_ep		*out = port->port_usb->out;

	while (!list_empty(pool)) {
		struct usb_request	*req;
		int			status;
		struct tty_struct	*tty;

459
		/* no more rx if closed */
460
		tty = port->port.tty;
461
		if (!tty)
462 463
			break;

464 465 466
		if (port->read_started >= QUEUE_SIZE)
			break;

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
		req = list_entry(pool->next, struct usb_request, list);
		list_del(&req->list);
		req->length = out->maxpacket;

		/* drop lock while we call out; the controller driver
		 * may need to call us back (e.g. for disconnect)
		 */
		spin_unlock(&port->port_lock);
		status = usb_ep_queue(out, req, GFP_ATOMIC);
		spin_lock(&port->port_lock);

		if (status) {
			pr_debug("%s: %s %s err %d\n",
					__func__, "queue", out->name, status);
			list_add(&req->list, pool);
			break;
		}
484
		port->read_started++;
485 486 487 488 489

		/* abort immediately after disconnect */
		if (!port->port_usb)
			break;
	}
490
	return port->read_started;
491 492
}

493 494 495 496 497 498 499 500 501 502 503
/*
 * RX tasklet takes data out of the RX queue and hands it up to the TTY
 * layer until it refuses to take any more data (or is throttled back).
 * Then it issues reads for any further data.
 *
 * If the RX queue becomes full enough that no usb_request is queued,
 * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
 * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
 * can be buffered before the TTY layer's buffers (currently 64 KB).
 */
static void gs_rx_push(unsigned long _port)
504
{
505 506 507 508 509
	struct gs_port		*port = (void *)_port;
	struct tty_struct	*tty;
	struct list_head	*queue = &port->read_queue;
	bool			disconnect = false;
	bool			do_push = false;
510

511 512
	/* hand any queued data to the tty */
	spin_lock_irq(&port->port_lock);
513
	tty = port->port.tty;
514 515
	while (!list_empty(queue)) {
		struct usb_request	*req;
516

517
		req = list_first_entry(queue, struct usb_request, list);
518

519
		/* leave data queued if tty was rx throttled */
520
		if (tty && tty_throttled(tty))
521 522 523 524 525
			break;

		switch (req->status) {
		case -ESHUTDOWN:
			disconnect = true;
526
			pr_vdebug("ttyGS%d: shutdown\n", port->port_num);
527 528 529 530
			break;

		default:
			/* presumably a transient fault */
531 532
			pr_warn("ttyGS%d: unexpected RX status %d\n",
				port->port_num, req->status);
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
			/* FALLTHROUGH */
		case 0:
			/* normal completion */
			break;
		}

		/* push data to (open) tty */
		if (req->actual) {
			char		*packet = req->buf;
			unsigned	size = req->actual;
			unsigned	n;
			int		count;

			/* we may have pushed part of this packet already... */
			n = port->n_read;
			if (n) {
				packet += n;
				size -= n;
			}

J
Jiri Slaby 已提交
553 554
			count = tty_insert_flip_string(&port->port, packet,
					size);
555 556 557 558 559
			if (count)
				do_push = true;
			if (count != size) {
				/* stop pushing; TTY layer can't handle more */
				port->n_read += count;
560 561
				pr_vdebug("ttyGS%d: rx block %d/%d\n",
					  port->port_num, count, req->actual);
562 563 564 565
				break;
			}
			port->n_read = 0;
		}
J
Jiri Slaby 已提交
566

567
		list_move(&req->list, &port->read_pool);
568
		port->read_started--;
569 570
	}

P
Peter Hurley 已提交
571 572
	/* Push from tty to ldisc; this is handled by a workqueue,
	 * so we won't get callbacks and can hold port_lock
573
	 */
J
Jiri Slaby 已提交
574 575
	if (do_push)
		tty_flip_buffer_push(&port->port);
576 577 578 579 580 581 582 583 584 585 586


	/* We want our data queue to become empty ASAP, keeping data
	 * in the tty and ldisc (not here).  If we couldn't push any
	 * this time around, there may be trouble unless there's an
	 * implicit tty_unthrottle() call on its way...
	 *
	 * REVISIT we should probably add a timer to keep the tasklet
	 * from starving ... but it's not clear that case ever happens.
	 */
	if (!list_empty(queue) && tty) {
587
		if (!tty_throttled(tty)) {
588 589 590
			if (do_push)
				tasklet_schedule(&port->push);
			else
591
				pr_warn("ttyGS%d: RX not scheduled?\n",
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
					port->port_num);
		}
	}

	/* If we're still connected, refill the USB RX queue. */
	if (!disconnect && port->port_usb)
		gs_start_rx(port);

	spin_unlock_irq(&port->port_lock);
}

static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct gs_port	*port = ep->driver_data;

	/* Queue all received data until the tty layer is ready for it. */
	spin_lock(&port->port_lock);
	list_add_tail(&req->list, &port->read_queue);
	tasklet_schedule(&port->push);
611 612 613 614 615 616 617 618 619
	spin_unlock(&port->port_lock);
}

static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct gs_port	*port = ep->driver_data;

	spin_lock(&port->port_lock);
	list_add(&req->list, &port->write_pool);
620
	port->write_started--;
621 622 623 624

	switch (req->status) {
	default:
		/* presumably a transient fault */
J
Joe Perches 已提交
625 626
		pr_warn("%s: unexpected %s status %d\n",
			__func__, ep->name, req->status);
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
		/* FALL THROUGH */
	case 0:
		/* normal completion */
		gs_start_tx(port);
		break;

	case -ESHUTDOWN:
		/* disconnect */
		pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
		break;
	}

	spin_unlock(&port->port_lock);
}

642 643
static void gs_free_requests(struct usb_ep *ep, struct list_head *head,
							 int *allocated)
644 645 646 647 648 649 650
{
	struct usb_request	*req;

	while (!list_empty(head)) {
		req = list_entry(head->next, struct usb_request, list);
		list_del(&req->list);
		gs_free_req(ep, req);
651 652
		if (allocated)
			(*allocated)--;
653 654 655 656
	}
}

static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
657 658
		void (*fn)(struct usb_ep *, struct usb_request *),
		int *allocated)
659 660 661
{
	int			i;
	struct usb_request	*req;
662
	int n = allocated ? QUEUE_SIZE - *allocated : QUEUE_SIZE;
663 664 665 666 667

	/* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
	 * do quite that many this time, don't fail ... we just won't
	 * be as speedy as we might otherwise be.
	 */
668
	for (i = 0; i < n; i++) {
669 670 671 672 673
		req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
		if (!req)
			return list_empty(head) ? -ENOMEM : 0;
		req->complete = fn;
		list_add_tail(&req->list, head);
674 675
		if (allocated)
			(*allocated)++;
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
	}
	return 0;
}

/**
 * gs_start_io - start USB I/O streams
 * @dev: encapsulates endpoints to use
 * Context: holding port_lock; port_tty and port_usb are non-null
 *
 * We only start I/O when something is connected to both sides of
 * this port.  If nothing is listening on the host side, we may
 * be pointlessly filling up our TX buffers and FIFO.
 */
static int gs_start_io(struct gs_port *port)
{
	struct list_head	*head = &port->read_pool;
	struct usb_ep		*ep = port->port_usb->out;
	int			status;
	unsigned		started;

	/* Allocate RX and TX I/O buffers.  We can't easily do this much
	 * earlier (with GFP_KERNEL) because the requests are coupled to
	 * endpoints, as are the packet sizes we'll be using.  Different
	 * configurations may use different endpoints with a given port;
	 * and high speed vs full speed changes packet sizes too.
	 */
702 703
	status = gs_alloc_requests(ep, head, gs_read_complete,
		&port->read_allocated);
704 705 706 707
	if (status)
		return status;

	status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
708
			gs_write_complete, &port->write_allocated);
709
	if (status) {
710
		gs_free_requests(ep, head, &port->read_allocated);
711 712 713 714
		return status;
	}

	/* queue read requests */
715
	port->n_read = 0;
716 717 718 719
	started = gs_start_rx(port);

	/* unblock any pending writes into our circular buffer */
	if (started) {
720
		tty_wakeup(port->port.tty);
721
	} else {
722 723 724
		gs_free_requests(ep, head, &port->read_allocated);
		gs_free_requests(port->port_usb->in, &port->write_pool,
			&port->write_allocated);
725
		status = -EIO;
726 727
	}

728
	return status;
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
}

/*-------------------------------------------------------------------------*/

/* TTY Driver */

/*
 * gs_open sets up the link between a gs_port and its associated TTY.
 * That link is broken *only* by TTY close(), and all driver methods
 * know that.
 */
static int gs_open(struct tty_struct *tty, struct file *file)
{
	int		port_num = tty->index;
	struct gs_port	*port;
	int		status;

	do {
		mutex_lock(&ports[port_num].lock);
		port = ports[port_num].port;
		if (!port)
			status = -ENODEV;
		else {
			spin_lock_irq(&port->port_lock);

			/* already open?  Great. */
J
Jiri Slaby 已提交
755
			if (port->port.count) {
756
				status = 0;
J
Jiri Slaby 已提交
757
				port->port.count++;
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813

			/* currently opening/closing? wait ... */
			} else if (port->openclose) {
				status = -EBUSY;

			/* ... else we do the work */
			} else {
				status = -EAGAIN;
				port->openclose = true;
			}
			spin_unlock_irq(&port->port_lock);
		}
		mutex_unlock(&ports[port_num].lock);

		switch (status) {
		default:
			/* fully handled */
			return status;
		case -EAGAIN:
			/* must do the work */
			break;
		case -EBUSY:
			/* wait for EAGAIN task to finish */
			msleep(1);
			/* REVISIT could have a waitchannel here, if
			 * concurrent open performance is important
			 */
			break;
		}
	} while (status != -EAGAIN);

	/* Do the "real open" */
	spin_lock_irq(&port->port_lock);

	/* allocate circular buffer on first open */
	if (port->port_write_buf.buf_buf == NULL) {

		spin_unlock_irq(&port->port_lock);
		status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
		spin_lock_irq(&port->port_lock);

		if (status) {
			pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
				port->port_num, tty, file);
			port->openclose = false;
			goto exit_unlock_port;
		}
	}

	/* REVISIT if REMOVED (ports[].port NULL), abort the open
	 * to let rmmod work faster (but this way isn't wrong).
	 */

	/* REVISIT maybe wait for "carrier detect" */

	tty->driver_data = port;
814
	port->port.tty = tty;
815

J
Jiri Slaby 已提交
816
	port->port.count = 1;
817 818 819 820
	port->openclose = false;

	/* if connected, start the I/O stream */
	if (port->port_usb) {
821 822
		struct gserial	*gser = port->port_usb;

823 824 825
		pr_debug("gs_open: start ttyGS%d\n", port->port_num);
		gs_start_io(port);

826 827
		if (gser->connect)
			gser->connect(gser);
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
	}

	pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);

	status = 0;

exit_unlock_port:
	spin_unlock_irq(&port->port_lock);
	return status;
}

static int gs_writes_finished(struct gs_port *p)
{
	int cond;

	/* return true on disconnect or empty buffer */
	spin_lock_irq(&p->port_lock);
	cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
	spin_unlock_irq(&p->port_lock);

	return cond;
}

static void gs_close(struct tty_struct *tty, struct file *file)
{
	struct gs_port *port = tty->driver_data;
854
	struct gserial	*gser;
855 856 857

	spin_lock_irq(&port->port_lock);

J
Jiri Slaby 已提交
858 859
	if (port->port.count != 1) {
		if (port->port.count == 0)
860 861
			WARN_ON(1);
		else
J
Jiri Slaby 已提交
862
			--port->port.count;
863 864 865 866 867 868 869 870 871
		goto exit;
	}

	pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);

	/* mark port as closing but in use; we can drop port lock
	 * and sleep if necessary
	 */
	port->openclose = true;
J
Jiri Slaby 已提交
872
	port->port.count = 0;
873

874 875 876
	gser = port->port_usb;
	if (gser && gser->disconnect)
		gser->disconnect(gser);
877 878 879 880

	/* wait for circular write buffer to drain, disconnect, or at
	 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
	 */
881
	if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
882 883 884 885 886
		spin_unlock_irq(&port->port_lock);
		wait_event_interruptible_timeout(port->drain_wait,
					gs_writes_finished(port),
					GS_CLOSE_TIMEOUT * HZ);
		spin_lock_irq(&port->port_lock);
887
		gser = port->port_usb;
888 889 890 891 892 893
	}

	/* Iff we're disconnected, there can be no I/O in flight so it's
	 * ok to free the circular buffer; else just scrub it.  And don't
	 * let the push tasklet fire again until we're re-opened.
	 */
894
	if (gser == NULL)
895 896 897 898
		gs_buf_free(&port->port_write_buf);
	else
		gs_buf_clear(&port->port_write_buf);

899
	port->port.tty = NULL;
900 901 902 903 904 905

	port->openclose = false;

	pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
			port->port_num, tty, file);

906
	wake_up(&port->close_wait);
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
exit:
	spin_unlock_irq(&port->port_lock);
}

static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
{
	struct gs_port	*port = tty->driver_data;
	unsigned long	flags;

	pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
			port->port_num, tty, count);

	spin_lock_irqsave(&port->port_lock, flags);
	if (count)
		count = gs_buf_put(&port->port_write_buf, buf, count);
	/* treat count == 0 as flush_chars() */
	if (port->port_usb)
924
		gs_start_tx(port);
925 926 927 928 929 930 931 932 933 934 935
	spin_unlock_irqrestore(&port->port_lock, flags);

	return count;
}

static int gs_put_char(struct tty_struct *tty, unsigned char ch)
{
	struct gs_port	*port = tty->driver_data;
	unsigned long	flags;
	int		status;

936
	pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %ps\n",
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
		port->port_num, tty, ch, __builtin_return_address(0));

	spin_lock_irqsave(&port->port_lock, flags);
	status = gs_buf_put(&port->port_write_buf, &ch, 1);
	spin_unlock_irqrestore(&port->port_lock, flags);

	return status;
}

static void gs_flush_chars(struct tty_struct *tty)
{
	struct gs_port	*port = tty->driver_data;
	unsigned long	flags;

	pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);

	spin_lock_irqsave(&port->port_lock, flags);
	if (port->port_usb)
		gs_start_tx(port);
	spin_unlock_irqrestore(&port->port_lock, flags);
}

static int gs_write_room(struct tty_struct *tty)
{
	struct gs_port	*port = tty->driver_data;
	unsigned long	flags;
	int		room = 0;

	spin_lock_irqsave(&port->port_lock, flags);
	if (port->port_usb)
		room = gs_buf_space_avail(&port->port_write_buf);
	spin_unlock_irqrestore(&port->port_lock, flags);

	pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
		port->port_num, tty, room);

	return room;
}

static int gs_chars_in_buffer(struct tty_struct *tty)
{
	struct gs_port	*port = tty->driver_data;
	unsigned long	flags;
	int		chars = 0;

	spin_lock_irqsave(&port->port_lock, flags);
	chars = gs_buf_data_avail(&port->port_write_buf);
	spin_unlock_irqrestore(&port->port_lock, flags);

	pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
		port->port_num, tty, chars);

	return chars;
}

/* undo side effects of setting TTY_THROTTLED */
static void gs_unthrottle(struct tty_struct *tty)
{
	struct gs_port		*port = tty->driver_data;
	unsigned long		flags;

	spin_lock_irqsave(&port->port_lock, flags);
999 1000 1001 1002 1003 1004
	if (port->port_usb) {
		/* Kickstart read queue processing.  We don't do xon/xoff,
		 * rts/cts, or other handshaking with the host, but if the
		 * read queue backs up enough we'll be NAKing OUT packets.
		 */
		tasklet_schedule(&port->push);
1005
		pr_vdebug("ttyGS%d: unthrottle\n", port->port_num);
1006
	}
1007 1008 1009
	spin_unlock_irqrestore(&port->port_lock, flags);
}

1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
static int gs_break_ctl(struct tty_struct *tty, int duration)
{
	struct gs_port	*port = tty->driver_data;
	int		status = 0;
	struct gserial	*gser;

	pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
			port->port_num, duration);

	spin_lock_irq(&port->port_lock);
	gser = port->port_usb;
	if (gser && gser->send_break)
		status = gser->send_break(gser, duration);
	spin_unlock_irq(&port->port_lock);

	return status;
}

1028 1029 1030 1031 1032 1033 1034 1035 1036
static const struct tty_operations gs_tty_ops = {
	.open =			gs_open,
	.close =		gs_close,
	.write =		gs_write,
	.put_char =		gs_put_char,
	.flush_chars =		gs_flush_chars,
	.write_room =		gs_write_room,
	.chars_in_buffer =	gs_chars_in_buffer,
	.unthrottle =		gs_unthrottle,
1037
	.break_ctl =		gs_break_ctl,
1038 1039 1040 1041 1042 1043
};

/*-------------------------------------------------------------------------*/

static struct tty_driver *gs_tty_driver;

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
#ifdef CONFIG_U_SERIAL_CONSOLE

static struct gscons_info gscons_info;
static struct console gserial_cons;

static struct usb_request *gs_request_new(struct usb_ep *ep)
{
	struct usb_request *req = usb_ep_alloc_request(ep, GFP_ATOMIC);
	if (!req)
		return NULL;

	req->buf = kmalloc(ep->maxpacket, GFP_ATOMIC);
	if (!req->buf) {
		usb_ep_free_request(ep, req);
		return NULL;
	}

	return req;
}

static void gs_request_free(struct usb_request *req, struct usb_ep *ep)
{
	if (!req)
		return;

	kfree(req->buf);
	usb_ep_free_request(ep, req);
}

static void gs_complete_out(struct usb_ep *ep, struct usb_request *req)
{
	struct gscons_info *info = &gscons_info;

	switch (req->status) {
	default:
		pr_warn("%s: unexpected %s status %d\n",
			__func__, ep->name, req->status);
	case 0:
		/* normal completion */
		spin_lock(&info->con_lock);
		info->req_busy = 0;
		spin_unlock(&info->con_lock);

		wake_up_process(info->console_thread);
		break;
	case -ESHUTDOWN:
		/* disconnect */
		pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
		break;
	}
}

static int gs_console_connect(int port_num)
{
	struct gscons_info *info = &gscons_info;
	struct gs_port *port;
	struct usb_ep *ep;

	if (port_num != gserial_cons.index) {
		pr_err("%s: port num [%d] is not support console\n",
		       __func__, port_num);
		return -ENXIO;
	}

	port = ports[port_num].port;
	ep = port->port_usb->in;
	if (!info->console_req) {
		info->console_req = gs_request_new(ep);
		if (!info->console_req)
			return -ENOMEM;
		info->console_req->complete = gs_complete_out;
	}

	info->port = port;
	spin_lock(&info->con_lock);
	info->req_busy = 0;
	spin_unlock(&info->con_lock);
	pr_vdebug("port[%d] console connect!\n", port_num);
	return 0;
}

static void gs_console_disconnect(struct usb_ep *ep)
{
	struct gscons_info *info = &gscons_info;
	struct usb_request *req = info->console_req;

	gs_request_free(req, ep);
	info->console_req = NULL;
}

static int gs_console_thread(void *data)
{
	struct gscons_info *info = &gscons_info;
	struct gs_port *port;
	struct usb_request *req;
	struct usb_ep *ep;
	int xfer, ret, count, size;

	do {
		port = info->port;
		set_current_state(TASK_INTERRUPTIBLE);
		if (!port || !port->port_usb
		    || !port->port_usb->in || !info->console_req)
			goto sched;

		req = info->console_req;
		ep = port->port_usb->in;

		spin_lock_irq(&info->con_lock);
		count = gs_buf_data_avail(&info->con_buf);
		size = ep->maxpacket;

		if (count > 0 && !info->req_busy) {
			set_current_state(TASK_RUNNING);
			if (count < size)
				size = count;

			xfer = gs_buf_get(&info->con_buf, req->buf, size);
			req->length = xfer;

			spin_unlock(&info->con_lock);
			ret = usb_ep_queue(ep, req, GFP_ATOMIC);
			spin_lock(&info->con_lock);
			if (ret < 0)
				info->req_busy = 0;
			else
				info->req_busy = 1;

			spin_unlock_irq(&info->con_lock);
		} else {
			spin_unlock_irq(&info->con_lock);
sched:
			if (kthread_should_stop()) {
				set_current_state(TASK_RUNNING);
				break;
			}
			schedule();
		}
	} while (1);

	return 0;
}

static int gs_console_setup(struct console *co, char *options)
{
	struct gscons_info *info = &gscons_info;
	int status;

	info->port = NULL;
	info->console_req = NULL;
	info->req_busy = 0;
	spin_lock_init(&info->con_lock);

	status = gs_buf_alloc(&info->con_buf, GS_CONSOLE_BUF_SIZE);
	if (status) {
		pr_err("%s: allocate console buffer failed\n", __func__);
		return status;
	}

	info->console_thread = kthread_create(gs_console_thread,
					      co, "gs_console");
	if (IS_ERR(info->console_thread)) {
		pr_err("%s: cannot create console thread\n", __func__);
		gs_buf_free(&info->con_buf);
		return PTR_ERR(info->console_thread);
	}
	wake_up_process(info->console_thread);

	return 0;
}

static void gs_console_write(struct console *co,
			     const char *buf, unsigned count)
{
	struct gscons_info *info = &gscons_info;
	unsigned long flags;

	spin_lock_irqsave(&info->con_lock, flags);
	gs_buf_put(&info->con_buf, buf, count);
	spin_unlock_irqrestore(&info->con_lock, flags);

	wake_up_process(info->console_thread);
}

static struct tty_driver *gs_console_device(struct console *co, int *index)
{
	struct tty_driver **p = (struct tty_driver **)co->data;

	if (!*p)
		return NULL;

	*index = co->index;
	return *p;
}

static struct console gserial_cons = {
	.name =		"ttyGS",
	.write =	gs_console_write,
	.device =	gs_console_device,
	.setup =	gs_console_setup,
	.flags =	CON_PRINTBUFFER,
	.index =	-1,
	.data =		&gs_tty_driver,
};

static void gserial_console_init(void)
{
	register_console(&gserial_cons);
}

static void gserial_console_exit(void)
{
	struct gscons_info *info = &gscons_info;

	unregister_console(&gserial_cons);
1259
	if (!IS_ERR_OR_NULL(info->console_thread))
1260
		kthread_stop(info->console_thread);
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
	gs_buf_free(&info->con_buf);
}

#else

static int gs_console_connect(int port_num)
{
	return 0;
}

static void gs_console_disconnect(struct usb_ep *ep)
{
}

static void gserial_console_init(void)
{
}

static void gserial_console_exit(void)
{
}

#endif

1285
static int
1286 1287 1288
gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
{
	struct gs_port	*port;
1289 1290 1291 1292 1293 1294 1295
	int		ret = 0;

	mutex_lock(&ports[port_num].lock);
	if (ports[port_num].port) {
		ret = -EBUSY;
		goto out;
	}
1296 1297

	port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1298 1299 1300 1301
	if (port == NULL) {
		ret = -ENOMEM;
		goto out;
	}
1302

J
Jiri Slaby 已提交
1303
	tty_port_init(&port->port);
1304 1305
	spin_lock_init(&port->port_lock);
	init_waitqueue_head(&port->drain_wait);
1306
	init_waitqueue_head(&port->close_wait);
1307 1308 1309 1310

	tasklet_init(&port->push, gs_rx_push, (unsigned long) port);

	INIT_LIST_HEAD(&port->read_pool);
1311
	INIT_LIST_HEAD(&port->read_queue);
1312 1313 1314 1315 1316 1317
	INIT_LIST_HEAD(&port->write_pool);

	port->port_num = port_num;
	port->port_line_coding = *coding;

	ports[port_num].port = port;
1318 1319 1320
out:
	mutex_unlock(&ports[port_num].lock);
	return ret;
1321 1322 1323 1324 1325 1326 1327
}

static int gs_closed(struct gs_port *port)
{
	int cond;

	spin_lock_irq(&port->port_lock);
J
Jiri Slaby 已提交
1328
	cond = (port->port.count == 0) && !port->openclose;
1329 1330 1331 1332
	spin_unlock_irq(&port->port_lock);
	return cond;
}

1333 1334 1335 1336
static void gserial_free_port(struct gs_port *port)
{
	tasklet_kill(&port->push);
	/* wait for old opens to finish */
1337
	wait_event(port->close_wait, gs_closed(port));
1338 1339 1340 1341 1342 1343
	WARN_ON(port->port_usb != NULL);
	tty_port_destroy(&port->port);
	kfree(port);
}

void gserial_free_line(unsigned char port_num)
1344 1345 1346
{
	struct gs_port	*port;

1347 1348 1349
	mutex_lock(&ports[port_num].lock);
	if (WARN_ON(!ports[port_num].port)) {
		mutex_unlock(&ports[port_num].lock);
1350
		return;
1351 1352 1353 1354
	}
	port = ports[port_num].port;
	ports[port_num].port = NULL;
	mutex_unlock(&ports[port_num].lock);
1355

1356 1357
	gserial_free_port(port);
	tty_unregister_device(gs_tty_driver, port_num);
1358
	gserial_console_exit();
1359 1360
}
EXPORT_SYMBOL_GPL(gserial_free_line);
1361

1362 1363 1364 1365 1366 1367
int gserial_alloc_line(unsigned char *line_num)
{
	struct usb_cdc_line_coding	coding;
	struct device			*tty_dev;
	int				ret;
	int				port_num;
1368

1369 1370 1371 1372
	coding.dwDTERate = cpu_to_le32(9600);
	coding.bCharFormat = 8;
	coding.bParityType = USB_CDC_NO_PARITY;
	coding.bDataBits = USB_CDC_1_STOP_BITS;
1373

1374 1375 1376 1377 1378 1379 1380
	for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) {
		ret = gs_port_alloc(port_num, &coding);
		if (ret == -EBUSY)
			continue;
		if (ret)
			return ret;
		break;
1381
	}
1382 1383
	if (ret)
		return ret;
1384

1385
	/* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1386

1387 1388 1389 1390 1391 1392
	tty_dev = tty_port_register_device(&ports[port_num].port->port,
			gs_tty_driver, port_num, NULL);
	if (IS_ERR(tty_dev)) {
		struct gs_port	*port;
		pr_err("%s: failed to register tty for port %d, err %ld\n",
				__func__, port_num, PTR_ERR(tty_dev));
1393

1394 1395 1396 1397 1398 1399 1400
		ret = PTR_ERR(tty_dev);
		port = ports[port_num].port;
		ports[port_num].port = NULL;
		gserial_free_port(port);
		goto err;
	}
	*line_num = port_num;
1401
	gserial_console_init();
1402 1403
err:
	return ret;
1404
}
1405
EXPORT_SYMBOL_GPL(gserial_alloc_line);
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421

/**
 * gserial_connect - notify TTY I/O glue that USB link is active
 * @gser: the function, set up with endpoints and descriptors
 * @port_num: which port is active
 * Context: any (usually from irq)
 *
 * This is called activate endpoints and let the TTY layer know that
 * the connection is active ... not unlike "carrier detect".  It won't
 * necessarily start I/O queues; unless the TTY is held open by any
 * task, there would be no point.  However, the endpoints will be
 * activated so the USB host can perform I/O, subject to basic USB
 * hardware flow control.
 *
 * Caller needs to have set up the endpoints and USB function in @dev
 * before calling this, as well as the appropriate (speed-specific)
1422 1423
 * endpoint descriptors, and also have allocate @port_num by calling
 * @gserial_alloc_line().
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
 *
 * Returns negative errno or zero.
 * On success, ep->driver_data will be overwritten.
 */
int gserial_connect(struct gserial *gser, u8 port_num)
{
	struct gs_port	*port;
	unsigned long	flags;
	int		status;

1434
	if (port_num >= MAX_U_SERIAL_PORTS)
1435 1436 1437
		return -ENXIO;

	port = ports[port_num].port;
1438 1439 1440 1441 1442 1443 1444 1445
	if (!port) {
		pr_err("serial line %d not allocated.\n", port_num);
		return -EINVAL;
	}
	if (port->port_usb) {
		pr_err("serial line %d is in use.\n", port_num);
		return -EBUSY;
	}
1446 1447

	/* activate the endpoints */
1448
	status = usb_ep_enable(gser->in);
1449 1450 1451 1452
	if (status < 0)
		return status;
	gser->in->driver_data = port;

1453
	status = usb_ep_enable(gser->out);
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
	if (status < 0)
		goto fail_out;
	gser->out->driver_data = port;

	/* then tell the tty glue that I/O can work */
	spin_lock_irqsave(&port->port_lock, flags);
	gser->ioport = port;
	port->port_usb = gser;

	/* REVISIT unclear how best to handle this state...
	 * we don't really couple it with the Linux TTY.
	 */
	gser->port_line_coding = port->port_line_coding;

	/* REVISIT if waiting on "carrier detect", signal. */

1470 1471
	/* if it's already open, start I/O ... and notify the serial
	 * protocol about open/close status (connect/disconnect).
1472
	 */
J
Jiri Slaby 已提交
1473
	if (port->port.count) {
1474 1475
		pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
		gs_start_io(port);
1476 1477 1478 1479 1480
		if (gser->connect)
			gser->connect(gser);
	} else {
		if (gser->disconnect)
			gser->disconnect(gser);
1481 1482
	}

1483
	status = gs_console_connect(port_num);
1484 1485 1486 1487 1488 1489 1490 1491
	spin_unlock_irqrestore(&port->port_lock, flags);

	return status;

fail_out:
	usb_ep_disable(gser->in);
	return status;
}
1492
EXPORT_SYMBOL_GPL(gserial_connect);
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
/**
 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
 * @gser: the function, on which gserial_connect() was called
 * Context: any (usually from irq)
 *
 * This is called to deactivate endpoints and let the TTY layer know
 * that the connection went inactive ... not unlike "hangup".
 *
 * On return, the state is as if gserial_connect() had never been called;
 * there is no active USB I/O on these endpoints.
 */
void gserial_disconnect(struct gserial *gser)
{
	struct gs_port	*port = gser->ioport;
	unsigned long	flags;

	if (!port)
		return;

	/* tell the TTY glue not to do I/O here any more */
	spin_lock_irqsave(&port->port_lock, flags);

	/* REVISIT as above: how best to track this? */
	port->port_line_coding = gser->port_line_coding;

	port->port_usb = NULL;
	gser->ioport = NULL;
J
Jiri Slaby 已提交
1520
	if (port->port.count > 0 || port->openclose) {
1521
		wake_up_interruptible(&port->drain_wait);
1522 1523
		if (port->port.tty)
			tty_hangup(port->port.tty);
1524 1525 1526 1527 1528 1529 1530 1531 1532
	}
	spin_unlock_irqrestore(&port->port_lock, flags);

	/* disable endpoints, aborting down any active I/O */
	usb_ep_disable(gser->out);
	usb_ep_disable(gser->in);

	/* finally, free any unused/unusable I/O buffers */
	spin_lock_irqsave(&port->port_lock, flags);
J
Jiri Slaby 已提交
1533
	if (port->port.count == 0 && !port->openclose)
1534
		gs_buf_free(&port->port_write_buf);
1535 1536 1537 1538 1539 1540 1541
	gs_free_requests(gser->out, &port->read_pool, NULL);
	gs_free_requests(gser->out, &port->read_queue, NULL);
	gs_free_requests(gser->in, &port->write_pool, NULL);

	port->read_allocated = port->read_started =
		port->write_allocated = port->write_started = 0;

1542
	gs_console_disconnect(gser->in);
1543 1544
	spin_unlock_irqrestore(&port->port_lock, flags);
}
1545 1546
EXPORT_SYMBOL_GPL(gserial_disconnect);

1547
static int userial_init(void)
1548 1549 1550 1551 1552 1553 1554 1555 1556
{
	unsigned			i;
	int				status;

	gs_tty_driver = alloc_tty_driver(MAX_U_SERIAL_PORTS);
	if (!gs_tty_driver)
		return -ENOMEM;

	gs_tty_driver->driver_name = "g_serial";
1557
	gs_tty_driver->name = "ttyGS";
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
	/* uses dynamically assigned dev_t values */

	gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
	gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
	gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
	gs_tty_driver->init_termios = tty_std_termios;

	/* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
	 * MS-Windows.  Otherwise, most of these flags shouldn't affect
	 * anything unless we were to actually hook up to a serial line.
	 */
	gs_tty_driver->init_termios.c_cflag =
			B9600 | CS8 | CREAD | HUPCL | CLOCAL;
	gs_tty_driver->init_termios.c_ispeed = 9600;
	gs_tty_driver->init_termios.c_ospeed = 9600;

	tty_set_operations(gs_tty_driver, &gs_tty_ops);
	for (i = 0; i < MAX_U_SERIAL_PORTS; i++)
		mutex_init(&ports[i].lock);

	/* export the driver ... */
	status = tty_register_driver(gs_tty_driver);
	if (status) {
		pr_err("%s: cannot register, err %d\n",
				__func__, status);
		goto fail;
	}

	pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
			MAX_U_SERIAL_PORTS,
			(MAX_U_SERIAL_PORTS == 1) ? "" : "s");

	return status;
fail:
	put_tty_driver(gs_tty_driver);
	gs_tty_driver = NULL;
	return status;
}
module_init(userial_init);

static void userial_cleanup(void)
{
	tty_unregister_driver(gs_tty_driver);
	put_tty_driver(gs_tty_driver);
	gs_tty_driver = NULL;
}
module_exit(userial_cleanup);

1606
MODULE_LICENSE("GPL");