2 * u_serial.c - utilities for USB gadget "serial port"/TTY support
4 * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
5 * Copyright (C) 2008 David Brownell
6 * Copyright (C) 2008 by Nokia Corporation
8 * This code also borrows from usbserial.c, which is
9 * Copyright (C) 1999 - 2002 Greg Kroah-Hartman (greg@kroah.com)
10 * Copyright (C) 2000 Peter Berger (pberger@brimson.com)
11 * Copyright (C) 2000 Al Borchers (alborchers@steinerpoint.com)
13 * This software is distributed under the terms of the GNU General
14 * Public License ("GPL") as published by the Free Software Foundation,
15 * either version 2 of that License or (at your option) any later version.
18 /* #define VERBOSE_DEBUG */
20 #include <linux/kernel.h>
21 #include <linux/interrupt.h>
22 #include <linux/device.h>
23 #include <linux/delay.h>
24 #include <linux/tty.h>
25 #include <linux/tty_flip.h>
31 * This component encapsulates the TTY layer glue needed to provide basic
32 * "serial port" functionality through the USB gadget stack. Each such
33 * port is exposed through a /dev/ttyGS* node.
35 * After initialization (gserial_setup), these TTY port devices stay
36 * available until they are removed (gserial_cleanup). Each one may be
37 * connected to a USB function (gserial_connect), or disconnected (with
38 * gserial_disconnect) when the USB host issues a config change event.
39 * Data can only flow when the port is connected to the host.
41 * A given TTY port can be made available in multiple configurations.
42 * For example, each one might expose a ttyGS0 node which provides a
43 * login application. In one case that might use CDC ACM interface 0,
44 * while another configuration might use interface 3 for that. The
45 * work to handle that (including descriptor management) is not part
48 * Configurations may expose more than one TTY port. For example, if
49 * ttyGS0 provides login service, then ttyGS1 might provide dialer access
50 * for a telephone or fax link. And ttyGS2 might be something that just
51 * needs a simple byte stream interface for some messaging protocol that
52 * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
55 #define PREFIX "ttyGS"
58 * gserial is the lifecycle interface, used by USB functions
59 * gs_port is the I/O nexus, used by the tty driver
60 * tty_struct links to the tty/filesystem framework
62 * gserial <---> gs_port ... links will be null when the USB link is
63 * inactive; managed by gserial_{connect,disconnect}(). each gserial
64 * instance can wrap its own USB control protocol.
65 * gserial->ioport == usb_ep->driver_data ... gs_port
66 * gs_port->port_usb ... gserial
68 * gs_port <---> tty_struct ... links will be null when the TTY file
69 * isn't opened; managed by gs_open()/gs_close()
70 * gserial->port_tty ... tty_struct
71 * tty_struct->driver_data ... gserial
74 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
75 * next layer of buffering. For TX that's a circular buffer; for RX
76 * consider it a NOP. A third layer is provided by the TTY code.
79 #define WRITE_BUF_SIZE 8192 /* TX only */
91 * The port structure holds info for each port, one for each minor number
92 * (and thus for each /dev/ node).
95 spinlock_t port_lock; /* guard port_* access */
97 struct gserial *port_usb;
98 struct tty_struct *port_tty;
101 bool openclose; /* open/close in progress */
104 wait_queue_head_t close_wait; /* wait for last close */
106 struct list_head read_pool;
107 struct list_head read_queue;
109 struct tasklet_struct push;
111 struct list_head write_pool;
112 struct gs_buf port_write_buf;
113 wait_queue_head_t drain_wait; /* wait while writes drain */
114 wait_queue_head_t full_wait; /* wait while buffer is full */
116 /* REVISIT this state ... */
117 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
120 /* increase N_PORTS if you need more */
122 static struct portmaster {
123 struct mutex lock; /* protect open/close */
124 struct gs_port *port;
126 static unsigned n_ports;
128 #define GS_CLOSE_TIMEOUT 15 /* seconds */
129 #define GS_FULL_TIMEOUT 2 /* seconds */
134 #define pr_vdebug(fmt, arg...) \
137 #define pr_vdebug(fmt, arg...) \
138 ({ if (0) pr_debug(fmt, ##arg); })
141 /*-------------------------------------------------------------------------*/
143 /* Circular Buffer */
148 * Allocate a circular buffer and all associated memory.
150 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
152 gb->buf_buf = kmalloc(size, GFP_KERNEL);
153 if (gb->buf_buf == NULL)
157 gb->buf_full = false;
158 gb->buf_put = gb->buf_buf;
159 gb->buf_get = gb->buf_buf;
167 * Free the buffer and all associated memory.
169 static void gs_buf_free(struct gs_buf *gb)
173 gb->buf_full = false;
179 * Clear out all data in the circular buffer.
181 static void gs_buf_clear(struct gs_buf *gb)
183 gb->buf_get = gb->buf_put;
184 gb->buf_full = false;
185 /* equivalent to a get of all data available */
191 * Return the number of bytes of data written into the circular
194 static unsigned gs_buf_data_avail(struct gs_buf *gb)
199 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
205 * Return the number of bytes of space available in the circular
208 static unsigned gs_buf_space_avail(struct gs_buf *gb)
213 if (gb->buf_get == gb->buf_put)
216 return (gb->buf_size + gb->buf_get - gb->buf_put) % gb->buf_size;
222 * Copy data data from a user buffer and put it into the circular buffer.
223 * Restrict to the amount of space available.
225 * Return the number of bytes copied.
228 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
232 len = gs_buf_space_avail(gb);
241 len = gb->buf_buf + gb->buf_size - gb->buf_put;
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;
247 memcpy(gb->buf_put, buf, count);
249 gb->buf_put += count;
250 else /* count == len */
251 gb->buf_put = gb->buf_buf;
260 * Get data from the circular buffer and copy to the given buffer.
261 * Restrict to the amount of data available.
263 * Return the number of bytes copied.
266 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
270 len = gs_buf_data_avail(gb);
277 len = gb->buf_buf + gb->buf_size - gb->buf_get;
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;
283 memcpy(buf, gb->buf_get, count);
285 gb->buf_get += count;
286 else /* count == len */
287 gb->buf_get = gb->buf_buf;
289 gb->buf_full = false;
294 /*-------------------------------------------------------------------------*/
296 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
301 * Allocate a usb_request and its buffer. Returns a pointer to the
302 * usb_request or NULL if there is an error.
305 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
307 struct usb_request *req;
309 req = usb_ep_alloc_request(ep, kmalloc_flags);
313 req->buf = kmalloc(len, kmalloc_flags);
314 if (req->buf == NULL) {
315 usb_ep_free_request(ep, req);
326 * Free a usb_request and its buffer.
328 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
331 usb_ep_free_request(ep, req);
337 * If there is data to send, a packet is built in the given
338 * buffer and the size is returned. If there is no data to
339 * send, 0 is returned.
341 * Called with port_lock held.
344 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
347 size = gs_buf_get(&port->port_write_buf, packet, size);
348 wake_up_interruptible(&port->full_wait);
356 * This function finds available write requests, calls
357 * gs_send_packet to fill these packets with data, and
358 * continues until either there are no more write requests
359 * available or no more data to send. This function is
360 * run whenever data arrives or write requests are available.
362 * Context: caller owns port_lock; port_usb is non-null.
364 static int gs_start_tx(struct gs_port *port)
366 __releases(&port->port_lock)
367 __acquires(&port->port_lock)
370 struct list_head *pool = &port->write_pool;
371 struct usb_ep *in = port->port_usb->in;
373 bool do_tty_wake = false;
375 while (!list_empty(pool)) {
376 struct usb_request *req;
379 req = list_entry(pool->next, struct usb_request, list);
380 len = gs_send_packet(port, req->buf, in->maxpacket);
382 wake_up_interruptible(&port->drain_wait);
388 list_del(&req->list);
389 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
391 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
392 port->port_num, len, *((u8 *)req->buf),
393 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
395 /* Drop lock while we call out of driver; completions
396 * could be issued while we do so. Disconnection may
397 * happen too; maybe immediately before we queue this!
399 * NOTE that we may keep sending data for a while after
400 * the TTY closed (dev->ioport->port_tty is NULL).
402 spin_unlock(&port->port_lock);
403 status = usb_ep_queue(in, req, GFP_ATOMIC);
404 spin_lock(&port->port_lock);
407 pr_debug("%s: %s %s err %d\n",
408 __func__, "queue", in->name, status);
409 list_add(&req->list, pool);
413 /* abort immediately after disconnect */
418 if (do_tty_wake && port->port_tty)
419 tty_wakeup(port->port_tty);
424 * Context: caller owns port_lock, and port_usb is set
426 static unsigned gs_start_rx(struct gs_port *port)
428 __releases(&port->port_lock)
429 __acquires(&port->port_lock)
432 struct list_head *pool = &port->read_pool;
433 struct usb_ep *out = port->port_usb->out;
434 unsigned started = 0;
436 while (!list_empty(pool)) {
437 struct usb_request *req;
439 struct tty_struct *tty;
441 /* no more rx if closed */
442 tty = port->port_tty;
446 req = list_entry(pool->next, struct usb_request, list);
447 list_del(&req->list);
448 req->length = out->maxpacket;
450 /* drop lock while we call out; the controller driver
451 * may need to call us back (e.g. for disconnect)
453 spin_unlock(&port->port_lock);
454 status = usb_ep_queue(out, req, GFP_ATOMIC);
455 spin_lock(&port->port_lock);
458 pr_debug("%s: %s %s err %d\n",
459 __func__, "queue", out->name, status);
460 list_add(&req->list, pool);
465 /* abort immediately after disconnect */
473 * RX tasklet takes data out of the RX queue and hands it up to the TTY
474 * layer until it refuses to take any more data (or is throttled back).
475 * Then it issues reads for any further data.
477 * If the RX queue becomes full enough that no usb_request is queued,
478 * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
479 * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
480 * can be buffered before the TTY layer's buffers (currently 64 KB).
482 static void gs_rx_push(unsigned long _port)
484 struct gs_port *port = (void *)_port;
485 struct tty_struct *tty;
486 struct list_head *queue = &port->read_queue;
487 bool disconnect = false;
488 bool do_push = false;
490 /* hand any queued data to the tty */
491 spin_lock_irq(&port->port_lock);
492 tty = port->port_tty;
493 while (!list_empty(queue)) {
494 struct usb_request *req;
496 req = list_first_entry(queue, struct usb_request, list);
498 /* discard data if tty was closed */
502 /* leave data queued if tty was rx throttled */
503 if (test_bit(TTY_THROTTLED, &tty->flags))
506 switch (req->status) {
509 pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
513 /* presumably a transient fault */
514 pr_warning(PREFIX "%d: unexpected RX status %d\n",
515 port->port_num, req->status);
518 /* normal completion */
522 /* push data to (open) tty */
524 char *packet = req->buf;
525 unsigned size = req->actual;
529 /* we may have pushed part of this packet already... */
536 count = tty_insert_flip_string(tty, packet, size);
540 /* stop pushing; TTY layer can't handle more */
541 port->n_read += count;
542 pr_vdebug(PREFIX "%d: rx block %d/%d\n",
550 list_move(&req->list, &port->read_pool);
553 /* Push from tty to ldisc; this is immediate with low_latency, and
554 * may trigger callbacks to this driver ... so drop the spinlock.
556 if (tty && do_push) {
557 spin_unlock_irq(&port->port_lock);
558 tty_flip_buffer_push(tty);
559 wake_up_interruptible(&tty->read_wait);
560 spin_lock_irq(&port->port_lock);
562 /* tty may have been closed */
563 tty = port->port_tty;
567 /* We want our data queue to become empty ASAP, keeping data
568 * in the tty and ldisc (not here). If we couldn't push any
569 * this time around, there may be trouble unless there's an
570 * implicit tty_unthrottle() call on its way...
572 * REVISIT we should probably add a timer to keep the tasklet
573 * from starving ... but it's not clear that case ever happens.
575 if (!list_empty(queue) && tty) {
576 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
578 tasklet_schedule(&port->push);
580 pr_warning(PREFIX "%d: RX not scheduled?\n",
585 /* If we're still connected, refill the USB RX queue. */
586 if (!disconnect && port->port_usb)
589 spin_unlock_irq(&port->port_lock);
592 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
594 struct gs_port *port = ep->driver_data;
596 /* Queue all received data until the tty layer is ready for it. */
597 spin_lock(&port->port_lock);
598 list_add_tail(&req->list, &port->read_queue);
599 tasklet_schedule(&port->push);
600 spin_unlock(&port->port_lock);
603 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
605 struct gs_port *port = ep->driver_data;
607 spin_lock(&port->port_lock);
608 list_add(&req->list, &port->write_pool);
610 switch (req->status) {
612 /* presumably a transient fault */
613 pr_warning("%s: unexpected %s status %d\n",
614 __func__, ep->name, req->status);
617 /* normal completion */
623 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
627 spin_unlock(&port->port_lock);
630 static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
632 struct usb_request *req;
634 while (!list_empty(head)) {
635 req = list_entry(head->next, struct usb_request, list);
636 list_del(&req->list);
637 gs_free_req(ep, req);
641 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
642 void (*fn)(struct usb_ep *, struct usb_request *))
645 struct usb_request *req;
647 /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
648 * do quite that many this time, don't fail ... we just won't
649 * be as speedy as we might otherwise be.
651 for (i = 0; i < QUEUE_SIZE; i++) {
652 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
654 return list_empty(head) ? -ENOMEM : 0;
656 list_add_tail(&req->list, head);
662 * gs_start_io - start USB I/O streams
663 * @dev: encapsulates endpoints to use
664 * Context: holding port_lock; port_tty and port_usb are non-null
666 * We only start I/O when something is connected to both sides of
667 * this port. If nothing is listening on the host side, we may
668 * be pointlessly filling up our TX buffers and FIFO.
670 static int gs_start_io(struct gs_port *port)
672 struct list_head *head = &port->read_pool;
673 struct usb_ep *ep = port->port_usb->out;
677 /* Allocate RX and TX I/O buffers. We can't easily do this much
678 * earlier (with GFP_KERNEL) because the requests are coupled to
679 * endpoints, as are the packet sizes we'll be using. Different
680 * configurations may use different endpoints with a given port;
681 * and high speed vs full speed changes packet sizes too.
683 status = gs_alloc_requests(ep, head, gs_read_complete);
687 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
690 gs_free_requests(ep, head);
694 /* queue read requests */
696 started = gs_start_rx(port);
698 /* unblock any pending writes into our circular buffer */
700 tty_wakeup(port->port_tty);
702 gs_free_requests(ep, head);
703 gs_free_requests(port->port_usb->in, &port->write_pool);
710 /*-------------------------------------------------------------------------*/
715 * gs_open sets up the link between a gs_port and its associated TTY.
716 * That link is broken *only* by TTY close(), and all driver methods
719 static int gs_open(struct tty_struct *tty, struct file *file)
721 int port_num = tty->index;
722 struct gs_port *port;
725 if (port_num < 0 || port_num >= n_ports)
729 mutex_lock(&ports[port_num].lock);
730 port = ports[port_num].port;
734 spin_lock_irq(&port->port_lock);
736 /* already open? Great. */
737 if (port->open_count) {
741 /* currently opening/closing? wait ... */
742 } else if (port->openclose) {
745 /* ... else we do the work */
748 port->openclose = true;
750 spin_unlock_irq(&port->port_lock);
752 mutex_unlock(&ports[port_num].lock);
759 /* must do the work */
762 /* wait for EAGAIN task to finish */
764 /* REVISIT could have a waitchannel here, if
765 * concurrent open performance is important
769 } while (status != -EAGAIN);
771 /* Do the "real open" */
772 spin_lock_irq(&port->port_lock);
774 /* allocate circular buffer on first open */
775 if (port->port_write_buf.buf_buf == NULL) {
777 spin_unlock_irq(&port->port_lock);
778 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
779 spin_lock_irq(&port->port_lock);
782 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
783 port->port_num, tty, file);
784 port->openclose = false;
785 goto exit_unlock_port;
789 /* REVISIT if REMOVED (ports[].port NULL), abort the open
790 * to let rmmod work faster (but this way isn't wrong).
793 /* REVISIT maybe wait for "carrier detect" */
795 tty->driver_data = port;
796 port->port_tty = tty;
798 port->open_count = 1;
799 port->openclose = false;
801 /* low_latency means ldiscs work in tasklet context, without
802 * needing a workqueue schedule ... easier to keep up.
804 tty->low_latency = 1;
806 /* if connected, start the I/O stream */
807 if (port->port_usb) {
808 struct gserial *gser = port->port_usb;
810 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
817 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
822 spin_unlock_irq(&port->port_lock);
826 static int gs_writes_finished(struct gs_port *p)
830 /* return true on disconnect or empty buffer */
831 spin_lock_irq(&p->port_lock);
832 cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
833 spin_unlock_irq(&p->port_lock);
838 static void gs_close(struct tty_struct *tty, struct file *file)
840 struct gs_port *port = tty->driver_data;
841 struct gserial *gser;
843 spin_lock_irq(&port->port_lock);
845 if (port->open_count != 1) {
846 if (port->open_count == 0)
853 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
855 /* mark port as closing but in use; we can drop port lock
856 * and sleep if necessary
858 port->openclose = true;
859 port->open_count = 0;
861 gser = port->port_usb;
862 if (gser && gser->disconnect)
863 gser->disconnect(gser);
865 /* wait for circular write buffer to drain, disconnect, or at
866 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
868 if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
869 spin_unlock_irq(&port->port_lock);
870 wait_event_interruptible_timeout(port->drain_wait,
871 gs_writes_finished(port),
872 GS_CLOSE_TIMEOUT * HZ);
873 spin_lock_irq(&port->port_lock);
874 gser = port->port_usb;
877 /* Iff we're disconnected, there can be no I/O in flight so it's
878 * ok to free the circular buffer; else just scrub it. And don't
879 * let the push tasklet fire again until we're re-opened.
882 gs_buf_free(&port->port_write_buf);
884 gs_buf_clear(&port->port_write_buf);
886 tty->driver_data = NULL;
887 port->port_tty = NULL;
889 port->openclose = false;
891 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
892 port->port_num, tty, file);
894 wake_up_interruptible(&port->close_wait);
896 spin_unlock_irq(&port->port_lock);
899 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
901 struct gs_port *port = tty->driver_data;
905 pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
906 port->port_num, tty, count);
908 if (port->port_write_buf.buf_full)
909 wait_event_interruptible_timeout(port->full_wait,
910 !port->port_write_buf.buf_full,
911 GS_FULL_TIMEOUT * HZ);
913 spin_lock_irqsave(&port->port_lock, flags);
914 if (unlikely(port->port_write_buf.buf_buf == NULL)) {
915 spin_unlock_irqrestore(&port->port_lock, flags);
920 count = gs_buf_put(&port->port_write_buf, buf, count);
921 /* treat count == 0 as flush_chars() */
923 status = gs_start_tx(port);
924 spin_unlock_irqrestore(&port->port_lock, flags);
929 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
931 struct gs_port *port = tty->driver_data;
935 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
936 port->port_num, tty, ch, __builtin_return_address(0));
938 spin_lock_irqsave(&port->port_lock, flags);
939 status = gs_buf_put(&port->port_write_buf, &ch, 1);
940 spin_unlock_irqrestore(&port->port_lock, flags);
945 static void gs_flush_chars(struct tty_struct *tty)
947 struct gs_port *port = tty->driver_data;
950 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
952 spin_lock_irqsave(&port->port_lock, flags);
955 spin_unlock_irqrestore(&port->port_lock, flags);
958 static int gs_write_room(struct tty_struct *tty)
960 struct gs_port *port = tty->driver_data;
964 spin_lock_irqsave(&port->port_lock, flags);
966 room = gs_buf_space_avail(&port->port_write_buf);
967 spin_unlock_irqrestore(&port->port_lock, flags);
969 pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
970 port->port_num, tty, room);
975 static int gs_chars_in_buffer(struct tty_struct *tty)
977 struct gs_port *port = tty->driver_data;
981 spin_lock_irqsave(&port->port_lock, flags);
982 chars = gs_buf_data_avail(&port->port_write_buf);
983 spin_unlock_irqrestore(&port->port_lock, flags);
985 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
986 port->port_num, tty, chars);
991 /* undo side effects of setting TTY_THROTTLED */
992 static void gs_unthrottle(struct tty_struct *tty)
994 struct gs_port *port = tty->driver_data;
997 spin_lock_irqsave(&port->port_lock, flags);
998 if (port->port_usb) {
999 /* Kickstart read queue processing. We don't do xon/xoff,
1000 * rts/cts, or other handshaking with the host, but if the
1001 * read queue backs up enough we'll be NAKing OUT packets.
1003 tasklet_schedule(&port->push);
1004 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
1006 spin_unlock_irqrestore(&port->port_lock, flags);
1009 static int gs_break_ctl(struct tty_struct *tty, int duration)
1011 struct gs_port *port = tty->driver_data;
1013 struct gserial *gser;
1015 pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
1016 port->port_num, duration);
1018 spin_lock_irq(&port->port_lock);
1019 gser = port->port_usb;
1020 if (gser && gser->send_break)
1021 status = gser->send_break(gser, duration);
1022 spin_unlock_irq(&port->port_lock);
1027 static const struct tty_operations gs_tty_ops = {
1031 .put_char = gs_put_char,
1032 .flush_chars = gs_flush_chars,
1033 .write_room = gs_write_room,
1034 .chars_in_buffer = gs_chars_in_buffer,
1035 .unthrottle = gs_unthrottle,
1036 .break_ctl = gs_break_ctl,
1039 /*-------------------------------------------------------------------------*/
1041 static struct tty_driver *gs_tty_driver;
1044 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1046 struct gs_port *port;
1048 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1052 spin_lock_init(&port->port_lock);
1053 init_waitqueue_head(&port->close_wait);
1054 init_waitqueue_head(&port->drain_wait);
1055 init_waitqueue_head(&port->full_wait);
1057 tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1059 INIT_LIST_HEAD(&port->read_pool);
1060 INIT_LIST_HEAD(&port->read_queue);
1061 INIT_LIST_HEAD(&port->write_pool);
1063 port->port_num = port_num;
1064 port->port_line_coding = *coding;
1066 ports[port_num].port = port;
1072 * gserial_setup - initialize TTY driver for one or more ports
1073 * @g: gadget to associate with these ports
1074 * @count: how many ports to support
1075 * Context: may sleep
1077 * The TTY stack needs to know in advance how many devices it should
1078 * plan to manage. Use this call to set up the ports you will be
1079 * exporting through USB. Later, connect them to functions based
1080 * on what configuration is activated by the USB host; and disconnect
1081 * them as appropriate.
1083 * An example would be a two-configuration device in which both
1084 * configurations expose port 0, but through different functions.
1085 * One configuration could even expose port 1 while the other
1088 * Returns negative errno or zero.
1090 int __init gserial_setup(struct usb_gadget *g, unsigned count)
1093 struct usb_cdc_line_coding coding;
1096 if (count == 0 || count > N_PORTS)
1099 gs_tty_driver = alloc_tty_driver(count);
1103 gs_tty_driver->owner = THIS_MODULE;
1104 gs_tty_driver->driver_name = "g_serial";
1105 gs_tty_driver->name = PREFIX;
1106 /* uses dynamically assigned dev_t values */
1108 gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1109 gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1110 gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1111 gs_tty_driver->init_termios = tty_std_termios;
1113 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1114 * MS-Windows. Otherwise, most of these flags shouldn't affect
1115 * anything unless we were to actually hook up to a serial line.
1117 gs_tty_driver->init_termios.c_cflag =
1118 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1119 gs_tty_driver->init_termios.c_ispeed = 9600;
1120 gs_tty_driver->init_termios.c_ospeed = 9600;
1122 coding.dwDTERate = __constant_cpu_to_le32(9600);
1123 coding.bCharFormat = 8;
1124 coding.bParityType = USB_CDC_NO_PARITY;
1125 coding.bDataBits = USB_CDC_1_STOP_BITS;
1127 tty_set_operations(gs_tty_driver, &gs_tty_ops);
1129 /* make devices be openable */
1130 for (i = 0; i < count; i++) {
1131 mutex_init(&ports[i].lock);
1132 status = gs_port_alloc(i, &coding);
1140 /* export the driver ... */
1141 status = tty_register_driver(gs_tty_driver);
1143 put_tty_driver(gs_tty_driver);
1144 pr_err("%s: cannot register, err %d\n",
1149 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1150 for (i = 0; i < count; i++) {
1151 struct device *tty_dev;
1153 tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
1154 if (IS_ERR(tty_dev))
1155 pr_warning("%s: no classdev for port %d, err %ld\n",
1156 __func__, i, PTR_ERR(tty_dev));
1159 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1160 count, (count == 1) ? "" : "s");
1165 kfree(ports[count].port);
1166 put_tty_driver(gs_tty_driver);
1167 gs_tty_driver = NULL;
1171 static int gs_closed(struct gs_port *port)
1175 spin_lock_irq(&port->port_lock);
1176 cond = (port->open_count == 0) && !port->openclose;
1177 spin_unlock_irq(&port->port_lock);
1182 * gserial_cleanup - remove TTY-over-USB driver and devices
1183 * Context: may sleep
1185 * This is called to free all resources allocated by @gserial_setup().
1186 * Accordingly, it may need to wait until some open /dev/ files have
1189 * The caller must have issued @gserial_disconnect() for any ports
1190 * that had previously been connected, so that there is never any
1191 * I/O pending when it's called.
1193 void gserial_cleanup(void)
1196 struct gs_port *port;
1201 /* start sysfs and /dev/ttyGS* node removal */
1202 for (i = 0; i < n_ports; i++)
1203 tty_unregister_device(gs_tty_driver, i);
1205 for (i = 0; i < n_ports; i++) {
1206 /* prevent new opens */
1207 mutex_lock(&ports[i].lock);
1208 port = ports[i].port;
1209 ports[i].port = NULL;
1210 mutex_unlock(&ports[i].lock);
1212 tasklet_kill(&port->push);
1214 /* wait for old opens to finish */
1215 wait_event(port->close_wait, gs_closed(port));
1217 WARN_ON(port->port_usb != NULL);
1223 tty_unregister_driver(gs_tty_driver);
1224 gs_tty_driver = NULL;
1226 pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1230 * gserial_connect - notify TTY I/O glue that USB link is active
1231 * @gser: the function, set up with endpoints and descriptors
1232 * @port_num: which port is active
1233 * Context: any (usually from irq)
1235 * This is called activate endpoints and let the TTY layer know that
1236 * the connection is active ... not unlike "carrier detect". It won't
1237 * necessarily start I/O queues; unless the TTY is held open by any
1238 * task, there would be no point. However, the endpoints will be
1239 * activated so the USB host can perform I/O, subject to basic USB
1240 * hardware flow control.
1242 * Caller needs to have set up the endpoints and USB function in @dev
1243 * before calling this, as well as the appropriate (speed-specific)
1244 * endpoint descriptors, and also have set up the TTY driver by calling
1247 * Returns negative errno or zero.
1248 * On success, ep->driver_data will be overwritten.
1250 int gserial_connect(struct gserial *gser, u8 port_num)
1252 struct gs_port *port;
1253 unsigned long flags;
1256 if (!gs_tty_driver || port_num >= n_ports)
1259 /* we "know" gserial_cleanup() hasn't been called */
1260 port = ports[port_num].port;
1262 /* activate the endpoints */
1263 status = usb_ep_enable(gser->in, gser->in_desc);
1266 gser->in->driver_data = port;
1268 status = usb_ep_enable(gser->out, gser->out_desc);
1271 gser->out->driver_data = port;
1273 /* then tell the tty glue that I/O can work */
1274 spin_lock_irqsave(&port->port_lock, flags);
1275 gser->ioport = port;
1276 port->port_usb = gser;
1278 /* REVISIT unclear how best to handle this state...
1279 * we don't really couple it with the Linux TTY.
1281 gser->port_line_coding = port->port_line_coding;
1283 /* REVISIT if waiting on "carrier detect", signal. */
1285 /* if it's already open, start I/O ... and notify the serial
1286 * protocol about open/close status (connect/disconnect).
1288 if (port->open_count) {
1289 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1292 gser->connect(gser);
1294 if (gser->disconnect)
1295 gser->disconnect(gser);
1298 spin_unlock_irqrestore(&port->port_lock, flags);
1303 usb_ep_disable(gser->in);
1304 gser->in->driver_data = NULL;
1309 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1310 * @gser: the function, on which gserial_connect() was called
1311 * Context: any (usually from irq)
1313 * This is called to deactivate endpoints and let the TTY layer know
1314 * that the connection went inactive ... not unlike "hangup".
1316 * On return, the state is as if gserial_connect() had never been called;
1317 * there is no active USB I/O on these endpoints.
1319 void gserial_disconnect(struct gserial *gser)
1321 struct gs_port *port = gser->ioport;
1322 unsigned long flags;
1327 /* tell the TTY glue not to do I/O here any more */
1328 spin_lock_irqsave(&port->port_lock, flags);
1330 /* REVISIT as above: how best to track this? */
1331 port->port_line_coding = gser->port_line_coding;
1333 port->port_usb = NULL;
1334 gser->ioport = NULL;
1335 if (port->open_count > 0 || port->openclose) {
1336 wake_up_interruptible(&port->drain_wait);
1338 tty_hangup(port->port_tty);
1340 spin_unlock_irqrestore(&port->port_lock, flags);
1342 /* disable endpoints, aborting down any active I/O */
1343 usb_ep_disable(gser->out);
1344 gser->out->driver_data = NULL;
1346 usb_ep_disable(gser->in);
1347 gser->in->driver_data = NULL;
1349 /* finally, free any unused/unusable I/O buffers */
1350 spin_lock_irqsave(&port->port_lock, flags);
1351 if (port->open_count == 0 && !port->openclose)
1352 gs_buf_free(&port->port_write_buf);
1353 gs_free_requests(gser->out, &port->read_pool);
1354 gs_free_requests(gser->out, &port->read_queue);
1355 gs_free_requests(gser->in, &port->write_pool);
1356 wake_up_interruptible(&port->full_wait);
1357 spin_unlock_irqrestore(&port->port_lock, flags);