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 */
90 * The port structure holds info for each port, one for each minor number
91 * (and thus for each /dev/ node).
94 spinlock_t port_lock; /* guard port_* access */
96 struct gserial *port_usb;
97 struct tty_struct *port_tty;
100 bool openclose; /* open/close in progress */
103 wait_queue_head_t close_wait; /* wait for last close */
105 struct list_head read_pool;
106 struct list_head read_queue;
108 struct tasklet_struct push;
110 struct list_head write_pool;
111 struct gs_buf port_write_buf;
112 wait_queue_head_t drain_wait; /* wait while writes drain */
114 /* REVISIT this state ... */
115 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
118 /* increase N_PORTS if you need more */
120 static struct portmaster {
121 struct mutex lock; /* protect open/close */
122 struct gs_port *port;
124 static unsigned n_ports;
126 #define GS_CLOSE_TIMEOUT 15 /* seconds */
131 #define pr_vdebug(fmt, arg...) \
134 #define pr_vdebug(fmt, arg...) \
135 ({ if (0) pr_debug(fmt, ##arg); })
138 /*-------------------------------------------------------------------------*/
140 /* Circular Buffer */
145 * Allocate a circular buffer and all associated memory.
147 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
149 gb->buf_buf = kmalloc(size, GFP_KERNEL);
150 if (gb->buf_buf == NULL)
154 gb->buf_put = gb->buf_buf;
155 gb->buf_get = gb->buf_buf;
163 * Free the buffer and all associated memory.
165 static void gs_buf_free(struct gs_buf *gb)
174 * Clear out all data in the circular buffer.
176 static void gs_buf_clear(struct gs_buf *gb)
178 gb->buf_get = gb->buf_put;
179 /* equivalent to a get of all data available */
185 * Return the number of bytes of data written into the circular
188 static unsigned gs_buf_data_avail(struct gs_buf *gb)
190 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
196 * Return the number of bytes of space available in the circular
199 static unsigned gs_buf_space_avail(struct gs_buf *gb)
201 return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
207 * Copy data data from a user buffer and put it into the circular buffer.
208 * Restrict to the amount of space available.
210 * Return the number of bytes copied.
213 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
217 len = gs_buf_space_avail(gb);
224 len = gb->buf_buf + gb->buf_size - gb->buf_put;
226 memcpy(gb->buf_put, buf, len);
227 memcpy(gb->buf_buf, buf+len, count - len);
228 gb->buf_put = gb->buf_buf + count - len;
230 memcpy(gb->buf_put, buf, count);
232 gb->buf_put += count;
233 else /* count == len */
234 gb->buf_put = gb->buf_buf;
243 * Get data from the circular buffer and copy to the given buffer.
244 * Restrict to the amount of data available.
246 * Return the number of bytes copied.
249 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
253 len = gs_buf_data_avail(gb);
260 len = gb->buf_buf + gb->buf_size - gb->buf_get;
262 memcpy(buf, gb->buf_get, len);
263 memcpy(buf+len, gb->buf_buf, count - len);
264 gb->buf_get = gb->buf_buf + count - len;
266 memcpy(buf, gb->buf_get, count);
268 gb->buf_get += count;
269 else /* count == len */
270 gb->buf_get = gb->buf_buf;
276 /*-------------------------------------------------------------------------*/
278 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
283 * Allocate a usb_request and its buffer. Returns a pointer to the
284 * usb_request or NULL if there is an error.
287 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
289 struct usb_request *req;
291 req = usb_ep_alloc_request(ep, kmalloc_flags);
295 req->buf = kmalloc(len, kmalloc_flags);
296 if (req->buf == NULL) {
297 usb_ep_free_request(ep, req);
308 * Free a usb_request and its buffer.
310 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
313 usb_ep_free_request(ep, req);
319 * If there is data to send, a packet is built in the given
320 * buffer and the size is returned. If there is no data to
321 * send, 0 is returned.
323 * Called with port_lock held.
326 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
330 len = gs_buf_data_avail(&port->port_write_buf);
334 size = gs_buf_get(&port->port_write_buf, packet, size);
341 * This function finds available write requests, calls
342 * gs_send_packet to fill these packets with data, and
343 * continues until either there are no more write requests
344 * available or no more data to send. This function is
345 * run whenever data arrives or write requests are available.
347 * Context: caller owns port_lock; port_usb is non-null.
349 static int gs_start_tx(struct gs_port *port)
351 __releases(&port->port_lock)
352 __acquires(&port->port_lock)
355 struct list_head *pool = &port->write_pool;
356 struct usb_ep *in = port->port_usb->in;
358 bool do_tty_wake = false;
360 while (!list_empty(pool)) {
361 struct usb_request *req;
364 req = list_entry(pool->next, struct usb_request, list);
365 len = gs_send_packet(port, req->buf, in->maxpacket);
367 wake_up_interruptible(&port->drain_wait);
373 list_del(&req->list);
374 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
376 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
377 port->port_num, len, *((u8 *)req->buf),
378 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
380 /* Drop lock while we call out of driver; completions
381 * could be issued while we do so. Disconnection may
382 * happen too; maybe immediately before we queue this!
384 * NOTE that we may keep sending data for a while after
385 * the TTY closed (dev->ioport->port_tty is NULL).
387 spin_unlock(&port->port_lock);
388 status = usb_ep_queue(in, req, GFP_ATOMIC);
389 spin_lock(&port->port_lock);
392 pr_debug("%s: %s %s err %d\n",
393 __func__, "queue", in->name, status);
394 list_add(&req->list, pool);
398 /* abort immediately after disconnect */
403 if (do_tty_wake && port->port_tty)
404 tty_wakeup(port->port_tty);
409 * Context: caller owns port_lock, and port_usb is set
411 static unsigned gs_start_rx(struct gs_port *port)
413 __releases(&port->port_lock)
414 __acquires(&port->port_lock)
417 struct list_head *pool = &port->read_pool;
418 struct usb_ep *out = port->port_usb->out;
419 unsigned started = 0;
421 while (!list_empty(pool)) {
422 struct usb_request *req;
424 struct tty_struct *tty;
426 /* no more rx if closed */
427 tty = port->port_tty;
431 req = list_entry(pool->next, struct usb_request, list);
432 list_del(&req->list);
433 req->length = out->maxpacket;
435 /* drop lock while we call out; the controller driver
436 * may need to call us back (e.g. for disconnect)
438 spin_unlock(&port->port_lock);
439 status = usb_ep_queue(out, req, GFP_ATOMIC);
440 spin_lock(&port->port_lock);
443 pr_debug("%s: %s %s err %d\n",
444 __func__, "queue", out->name, status);
445 list_add(&req->list, pool);
450 /* abort immediately after disconnect */
458 * RX tasklet takes data out of the RX queue and hands it up to the TTY
459 * layer until it refuses to take any more data (or is throttled back).
460 * Then it issues reads for any further data.
462 * If the RX queue becomes full enough that no usb_request is queued,
463 * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
464 * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
465 * can be buffered before the TTY layer's buffers (currently 64 KB).
467 static void gs_rx_push(unsigned long _port)
469 struct gs_port *port = (void *)_port;
470 struct tty_struct *tty;
471 struct list_head *queue = &port->read_queue;
472 bool disconnect = false;
473 bool do_push = false;
475 /* hand any queued data to the tty */
476 spin_lock_irq(&port->port_lock);
477 tty = port->port_tty;
478 while (!list_empty(queue)) {
479 struct usb_request *req;
481 req = list_first_entry(queue, struct usb_request, list);
483 /* discard data if tty was closed */
487 /* leave data queued if tty was rx throttled */
488 if (test_bit(TTY_THROTTLED, &tty->flags))
491 switch (req->status) {
494 pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
498 /* presumably a transient fault */
499 pr_warning(PREFIX "%d: unexpected RX status %d\n",
500 port->port_num, req->status);
503 /* normal completion */
507 /* push data to (open) tty */
509 char *packet = req->buf;
510 unsigned size = req->actual;
514 /* we may have pushed part of this packet already... */
521 count = tty_insert_flip_string(tty, packet, size);
525 /* stop pushing; TTY layer can't handle more */
526 port->n_read += count;
527 pr_vdebug(PREFIX "%d: rx block %d/%d\n",
535 list_move(&req->list, &port->read_pool);
538 /* Push from tty to ldisc; without low_latency set this is handled by
539 * a workqueue, so we won't get callbacks and can hold port_lock
541 if (tty && do_push) {
542 tty_flip_buffer_push(tty);
546 /* We want our data queue to become empty ASAP, keeping data
547 * in the tty and ldisc (not here). If we couldn't push any
548 * this time around, there may be trouble unless there's an
549 * implicit tty_unthrottle() call on its way...
551 * REVISIT we should probably add a timer to keep the tasklet
552 * from starving ... but it's not clear that case ever happens.
554 if (!list_empty(queue) && tty) {
555 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
557 tasklet_schedule(&port->push);
559 pr_warning(PREFIX "%d: RX not scheduled?\n",
564 /* If we're still connected, refill the USB RX queue. */
565 if (!disconnect && port->port_usb)
568 spin_unlock_irq(&port->port_lock);
571 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
573 struct gs_port *port = ep->driver_data;
575 /* Queue all received data until the tty layer is ready for it. */
576 spin_lock(&port->port_lock);
577 list_add_tail(&req->list, &port->read_queue);
578 tasklet_schedule(&port->push);
579 spin_unlock(&port->port_lock);
582 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
584 struct gs_port *port = ep->driver_data;
586 spin_lock(&port->port_lock);
587 list_add(&req->list, &port->write_pool);
589 switch (req->status) {
591 /* presumably a transient fault */
592 pr_warning("%s: unexpected %s status %d\n",
593 __func__, ep->name, req->status);
596 /* normal completion */
602 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
606 spin_unlock(&port->port_lock);
609 static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
611 struct usb_request *req;
613 while (!list_empty(head)) {
614 req = list_entry(head->next, struct usb_request, list);
615 list_del(&req->list);
616 gs_free_req(ep, req);
620 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
621 void (*fn)(struct usb_ep *, struct usb_request *))
624 struct usb_request *req;
626 /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
627 * do quite that many this time, don't fail ... we just won't
628 * be as speedy as we might otherwise be.
630 for (i = 0; i < QUEUE_SIZE; i++) {
631 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
633 return list_empty(head) ? -ENOMEM : 0;
635 list_add_tail(&req->list, head);
641 * gs_start_io - start USB I/O streams
642 * @dev: encapsulates endpoints to use
643 * Context: holding port_lock; port_tty and port_usb are non-null
645 * We only start I/O when something is connected to both sides of
646 * this port. If nothing is listening on the host side, we may
647 * be pointlessly filling up our TX buffers and FIFO.
649 static int gs_start_io(struct gs_port *port)
651 struct list_head *head = &port->read_pool;
652 struct usb_ep *ep = port->port_usb->out;
656 /* Allocate RX and TX I/O buffers. We can't easily do this much
657 * earlier (with GFP_KERNEL) because the requests are coupled to
658 * endpoints, as are the packet sizes we'll be using. Different
659 * configurations may use different endpoints with a given port;
660 * and high speed vs full speed changes packet sizes too.
662 status = gs_alloc_requests(ep, head, gs_read_complete);
666 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
669 gs_free_requests(ep, head);
673 /* queue read requests */
675 started = gs_start_rx(port);
677 /* unblock any pending writes into our circular buffer */
679 tty_wakeup(port->port_tty);
681 gs_free_requests(ep, head);
682 gs_free_requests(port->port_usb->in, &port->write_pool);
689 /*-------------------------------------------------------------------------*/
694 * gs_open sets up the link between a gs_port and its associated TTY.
695 * That link is broken *only* by TTY close(), and all driver methods
698 static int gs_open(struct tty_struct *tty, struct file *file)
700 int port_num = tty->index;
701 struct gs_port *port;
704 if (port_num < 0 || port_num >= n_ports)
708 mutex_lock(&ports[port_num].lock);
709 port = ports[port_num].port;
713 spin_lock_irq(&port->port_lock);
715 /* already open? Great. */
716 if (port->open_count) {
720 /* currently opening/closing? wait ... */
721 } else if (port->openclose) {
724 /* ... else we do the work */
727 port->openclose = true;
729 spin_unlock_irq(&port->port_lock);
731 mutex_unlock(&ports[port_num].lock);
738 /* must do the work */
741 /* wait for EAGAIN task to finish */
743 /* REVISIT could have a waitchannel here, if
744 * concurrent open performance is important
748 } while (status != -EAGAIN);
750 /* Do the "real open" */
751 spin_lock_irq(&port->port_lock);
753 /* allocate circular buffer on first open */
754 if (port->port_write_buf.buf_buf == NULL) {
756 spin_unlock_irq(&port->port_lock);
757 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
758 spin_lock_irq(&port->port_lock);
761 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
762 port->port_num, tty, file);
763 port->openclose = false;
764 goto exit_unlock_port;
768 /* REVISIT if REMOVED (ports[].port NULL), abort the open
769 * to let rmmod work faster (but this way isn't wrong).
772 /* REVISIT maybe wait for "carrier detect" */
774 tty->driver_data = port;
775 port->port_tty = tty;
777 port->open_count = 1;
778 port->openclose = false;
780 /* if connected, start the I/O stream */
781 if (port->port_usb) {
782 struct gserial *gser = port->port_usb;
784 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
791 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
796 spin_unlock_irq(&port->port_lock);
800 static int gs_writes_finished(struct gs_port *p)
804 /* return true on disconnect or empty buffer */
805 spin_lock_irq(&p->port_lock);
806 cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
807 spin_unlock_irq(&p->port_lock);
812 static void gs_close(struct tty_struct *tty, struct file *file)
814 struct gs_port *port = tty->driver_data;
815 struct gserial *gser;
817 spin_lock_irq(&port->port_lock);
819 if (port->open_count != 1) {
820 if (port->open_count == 0)
827 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
829 /* mark port as closing but in use; we can drop port lock
830 * and sleep if necessary
832 port->openclose = true;
833 port->open_count = 0;
835 gser = port->port_usb;
836 if (gser && gser->disconnect)
837 gser->disconnect(gser);
839 /* wait for circular write buffer to drain, disconnect, or at
840 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
842 if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
843 spin_unlock_irq(&port->port_lock);
844 wait_event_interruptible_timeout(port->drain_wait,
845 gs_writes_finished(port),
846 GS_CLOSE_TIMEOUT * HZ);
847 spin_lock_irq(&port->port_lock);
848 gser = port->port_usb;
851 /* Iff we're disconnected, there can be no I/O in flight so it's
852 * ok to free the circular buffer; else just scrub it. And don't
853 * let the push tasklet fire again until we're re-opened.
856 gs_buf_free(&port->port_write_buf);
858 gs_buf_clear(&port->port_write_buf);
860 tty->driver_data = NULL;
861 port->port_tty = NULL;
863 port->openclose = false;
865 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
866 port->port_num, tty, file);
868 wake_up_interruptible(&port->close_wait);
870 spin_unlock_irq(&port->port_lock);
873 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
875 struct gs_port *port = tty->driver_data;
879 pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
880 port->port_num, tty, count);
882 spin_lock_irqsave(&port->port_lock, flags);
884 count = gs_buf_put(&port->port_write_buf, buf, count);
885 /* treat count == 0 as flush_chars() */
887 status = gs_start_tx(port);
888 spin_unlock_irqrestore(&port->port_lock, flags);
893 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
895 struct gs_port *port = tty->driver_data;
899 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
900 port->port_num, tty, ch, __builtin_return_address(0));
902 spin_lock_irqsave(&port->port_lock, flags);
903 status = gs_buf_put(&port->port_write_buf, &ch, 1);
904 spin_unlock_irqrestore(&port->port_lock, flags);
909 static void gs_flush_chars(struct tty_struct *tty)
911 struct gs_port *port = tty->driver_data;
914 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
916 spin_lock_irqsave(&port->port_lock, flags);
919 spin_unlock_irqrestore(&port->port_lock, flags);
922 static int gs_write_room(struct tty_struct *tty)
924 struct gs_port *port = tty->driver_data;
928 spin_lock_irqsave(&port->port_lock, flags);
930 room = gs_buf_space_avail(&port->port_write_buf);
931 spin_unlock_irqrestore(&port->port_lock, flags);
933 pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
934 port->port_num, tty, room);
939 static int gs_chars_in_buffer(struct tty_struct *tty)
941 struct gs_port *port = tty->driver_data;
945 spin_lock_irqsave(&port->port_lock, flags);
946 chars = gs_buf_data_avail(&port->port_write_buf);
947 spin_unlock_irqrestore(&port->port_lock, flags);
949 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
950 port->port_num, tty, chars);
955 /* undo side effects of setting TTY_THROTTLED */
956 static void gs_unthrottle(struct tty_struct *tty)
958 struct gs_port *port = tty->driver_data;
961 spin_lock_irqsave(&port->port_lock, flags);
962 if (port->port_usb) {
963 /* Kickstart read queue processing. We don't do xon/xoff,
964 * rts/cts, or other handshaking with the host, but if the
965 * read queue backs up enough we'll be NAKing OUT packets.
967 tasklet_schedule(&port->push);
968 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
970 spin_unlock_irqrestore(&port->port_lock, flags);
973 static int gs_break_ctl(struct tty_struct *tty, int duration)
975 struct gs_port *port = tty->driver_data;
977 struct gserial *gser;
979 pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
980 port->port_num, duration);
982 spin_lock_irq(&port->port_lock);
983 gser = port->port_usb;
984 if (gser && gser->send_break)
985 status = gser->send_break(gser, duration);
986 spin_unlock_irq(&port->port_lock);
991 static const struct tty_operations gs_tty_ops = {
995 .put_char = gs_put_char,
996 .flush_chars = gs_flush_chars,
997 .write_room = gs_write_room,
998 .chars_in_buffer = gs_chars_in_buffer,
999 .unthrottle = gs_unthrottle,
1000 .break_ctl = gs_break_ctl,
1003 /*-------------------------------------------------------------------------*/
1005 static struct tty_driver *gs_tty_driver;
1008 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1010 struct gs_port *port;
1012 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1016 spin_lock_init(&port->port_lock);
1017 init_waitqueue_head(&port->close_wait);
1018 init_waitqueue_head(&port->drain_wait);
1020 tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1022 INIT_LIST_HEAD(&port->read_pool);
1023 INIT_LIST_HEAD(&port->read_queue);
1024 INIT_LIST_HEAD(&port->write_pool);
1026 port->port_num = port_num;
1027 port->port_line_coding = *coding;
1029 ports[port_num].port = port;
1035 * gserial_setup - initialize TTY driver for one or more ports
1036 * @g: gadget to associate with these ports
1037 * @count: how many ports to support
1038 * Context: may sleep
1040 * The TTY stack needs to know in advance how many devices it should
1041 * plan to manage. Use this call to set up the ports you will be
1042 * exporting through USB. Later, connect them to functions based
1043 * on what configuration is activated by the USB host; and disconnect
1044 * them as appropriate.
1046 * An example would be a two-configuration device in which both
1047 * configurations expose port 0, but through different functions.
1048 * One configuration could even expose port 1 while the other
1051 * Returns negative errno or zero.
1053 int __init gserial_setup(struct usb_gadget *g, unsigned count)
1056 struct usb_cdc_line_coding coding;
1059 if (count == 0 || count > N_PORTS)
1062 gs_tty_driver = alloc_tty_driver(count);
1066 gs_tty_driver->owner = THIS_MODULE;
1067 gs_tty_driver->driver_name = "g_serial";
1068 gs_tty_driver->name = PREFIX;
1069 /* uses dynamically assigned dev_t values */
1071 gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1072 gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1073 gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1074 gs_tty_driver->init_termios = tty_std_termios;
1076 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1077 * MS-Windows. Otherwise, most of these flags shouldn't affect
1078 * anything unless we were to actually hook up to a serial line.
1080 gs_tty_driver->init_termios.c_cflag =
1081 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1082 gs_tty_driver->init_termios.c_ispeed = 9600;
1083 gs_tty_driver->init_termios.c_ospeed = 9600;
1085 coding.dwDTERate = cpu_to_le32(9600);
1086 coding.bCharFormat = 8;
1087 coding.bParityType = USB_CDC_NO_PARITY;
1088 coding.bDataBits = USB_CDC_1_STOP_BITS;
1090 tty_set_operations(gs_tty_driver, &gs_tty_ops);
1092 /* make devices be openable */
1093 for (i = 0; i < count; i++) {
1094 mutex_init(&ports[i].lock);
1095 status = gs_port_alloc(i, &coding);
1103 /* export the driver ... */
1104 status = tty_register_driver(gs_tty_driver);
1106 pr_err("%s: cannot register, err %d\n",
1111 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1112 for (i = 0; i < count; i++) {
1113 struct device *tty_dev;
1115 tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
1116 if (IS_ERR(tty_dev))
1117 pr_warning("%s: no classdev for port %d, err %ld\n",
1118 __func__, i, PTR_ERR(tty_dev));
1121 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1122 count, (count == 1) ? "" : "s");
1127 kfree(ports[count].port);
1128 put_tty_driver(gs_tty_driver);
1129 gs_tty_driver = NULL;
1133 static int gs_closed(struct gs_port *port)
1137 spin_lock_irq(&port->port_lock);
1138 cond = (port->open_count == 0) && !port->openclose;
1139 spin_unlock_irq(&port->port_lock);
1144 * gserial_cleanup - remove TTY-over-USB driver and devices
1145 * Context: may sleep
1147 * This is called to free all resources allocated by @gserial_setup().
1148 * Accordingly, it may need to wait until some open /dev/ files have
1151 * The caller must have issued @gserial_disconnect() for any ports
1152 * that had previously been connected, so that there is never any
1153 * I/O pending when it's called.
1155 void gserial_cleanup(void)
1158 struct gs_port *port;
1163 /* start sysfs and /dev/ttyGS* node removal */
1164 for (i = 0; i < n_ports; i++)
1165 tty_unregister_device(gs_tty_driver, i);
1167 for (i = 0; i < n_ports; i++) {
1168 /* prevent new opens */
1169 mutex_lock(&ports[i].lock);
1170 port = ports[i].port;
1171 ports[i].port = NULL;
1172 mutex_unlock(&ports[i].lock);
1174 tasklet_kill(&port->push);
1176 /* wait for old opens to finish */
1177 wait_event(port->close_wait, gs_closed(port));
1179 WARN_ON(port->port_usb != NULL);
1185 tty_unregister_driver(gs_tty_driver);
1186 gs_tty_driver = NULL;
1188 pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1192 * gserial_connect - notify TTY I/O glue that USB link is active
1193 * @gser: the function, set up with endpoints and descriptors
1194 * @port_num: which port is active
1195 * Context: any (usually from irq)
1197 * This is called activate endpoints and let the TTY layer know that
1198 * the connection is active ... not unlike "carrier detect". It won't
1199 * necessarily start I/O queues; unless the TTY is held open by any
1200 * task, there would be no point. However, the endpoints will be
1201 * activated so the USB host can perform I/O, subject to basic USB
1202 * hardware flow control.
1204 * Caller needs to have set up the endpoints and USB function in @dev
1205 * before calling this, as well as the appropriate (speed-specific)
1206 * endpoint descriptors, and also have set up the TTY driver by calling
1209 * Returns negative errno or zero.
1210 * On success, ep->driver_data will be overwritten.
1212 int gserial_connect(struct gserial *gser, u8 port_num)
1214 struct gs_port *port;
1215 unsigned long flags;
1218 if (!gs_tty_driver || port_num >= n_ports)
1221 /* we "know" gserial_cleanup() hasn't been called */
1222 port = ports[port_num].port;
1224 /* activate the endpoints */
1225 status = usb_ep_enable(gser->in, gser->in_desc);
1228 gser->in->driver_data = port;
1230 status = usb_ep_enable(gser->out, gser->out_desc);
1233 gser->out->driver_data = port;
1235 /* then tell the tty glue that I/O can work */
1236 spin_lock_irqsave(&port->port_lock, flags);
1237 gser->ioport = port;
1238 port->port_usb = gser;
1240 /* REVISIT unclear how best to handle this state...
1241 * we don't really couple it with the Linux TTY.
1243 gser->port_line_coding = port->port_line_coding;
1245 /* REVISIT if waiting on "carrier detect", signal. */
1247 /* if it's already open, start I/O ... and notify the serial
1248 * protocol about open/close status (connect/disconnect).
1250 if (port->open_count) {
1251 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1254 gser->connect(gser);
1256 if (gser->disconnect)
1257 gser->disconnect(gser);
1260 spin_unlock_irqrestore(&port->port_lock, flags);
1265 usb_ep_disable(gser->in);
1266 gser->in->driver_data = NULL;
1271 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1272 * @gser: the function, on which gserial_connect() was called
1273 * Context: any (usually from irq)
1275 * This is called to deactivate endpoints and let the TTY layer know
1276 * that the connection went inactive ... not unlike "hangup".
1278 * On return, the state is as if gserial_connect() had never been called;
1279 * there is no active USB I/O on these endpoints.
1281 void gserial_disconnect(struct gserial *gser)
1283 struct gs_port *port = gser->ioport;
1284 unsigned long flags;
1289 /* tell the TTY glue not to do I/O here any more */
1290 spin_lock_irqsave(&port->port_lock, flags);
1292 /* REVISIT as above: how best to track this? */
1293 port->port_line_coding = gser->port_line_coding;
1295 port->port_usb = NULL;
1296 gser->ioport = NULL;
1297 if (port->open_count > 0 || port->openclose) {
1298 wake_up_interruptible(&port->drain_wait);
1300 tty_hangup(port->port_tty);
1302 spin_unlock_irqrestore(&port->port_lock, flags);
1304 /* disable endpoints, aborting down any active I/O */
1305 usb_ep_disable(gser->out);
1306 gser->out->driver_data = NULL;
1308 usb_ep_disable(gser->in);
1309 gser->in->driver_data = NULL;
1311 /* finally, free any unused/unusable I/O buffers */
1312 spin_lock_irqsave(&port->port_lock, flags);
1313 if (port->open_count == 0 && !port->openclose)
1314 gs_buf_free(&port->port_write_buf);
1315 gs_free_requests(gser->out, &port->read_pool);
1316 gs_free_requests(gser->out, &port->read_queue);
1317 gs_free_requests(gser->in, &port->write_pool);
1318 spin_unlock_irqrestore(&port->port_lock, flags);