1 // SPDX-License-Identifier: GPL-2.0+
3 * u_serial.c - utilities for USB gadget "serial port"/TTY support
6 * Copyright (C) 2008 David Brownell
7 * Copyright (C) 2008 by Nokia Corporation
9 * This code also borrows from usbserial.c, which is
15 /* #define VERBOSE_DEBUG */
17 #include <linux/kernel.h>
18 #include <linux/sched.h>
19 #include <linux/device.h>
20 #include <linux/delay.h>
21 #include <linux/tty.h>
22 #include <linux/tty_flip.h>
23 #include <linux/slab.h>
24 #include <linux/string_choices.h>
25 #include <linux/export.h>
26 #include <linux/module.h>
27 #include <linux/console.h>
28 #include <linux/kstrtox.h>
29 #include <linux/kthread.h>
30 #include <linux/workqueue.h>
31 #include <linux/kfifo.h>
32 #include <linux/serial.h>
38 * This component encapsulates the TTY layer glue needed to provide basic
39 * "serial port" functionality through the USB gadget stack. Each such
40 * port is exposed through a /dev/ttyGS* node.
42 * After this module has been loaded, the individual TTY port can be requested
43 * (gserial_alloc_line()) and it will stay available until they are removed
44 * (gserial_free_line()). Each one may be connected to a USB function
45 * (gserial_connect), or disconnected (with gserial_disconnect) when the USB
46 * host issues a config change event. Data can only flow when the port is
47 * connected to the host.
49 * A given TTY port can be made available in multiple configurations.
50 * For example, each one might expose a ttyGS0 node which provides a
51 * login application. In one case that might use CDC ACM interface 0,
52 * while another configuration might use interface 3 for that. The
53 * work to handle that (including descriptor management) is not part
56 * Configurations may expose more than one TTY port. For example, if
57 * ttyGS0 provides login service, then ttyGS1 might provide dialer access
58 * for a telephone or fax link. And ttyGS2 might be something that just
59 * needs a simple byte stream interface for some messaging protocol that
60 * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
63 * gserial is the lifecycle interface, used by USB functions
64 * gs_port is the I/O nexus, used by the tty driver
65 * tty_struct links to the tty/filesystem framework
67 * gserial <---> gs_port ... links will be null when the USB link is
68 * inactive; managed by gserial_{connect,disconnect}(). each gserial
69 * instance can wrap its own USB control protocol.
70 * gserial->ioport == usb_ep->driver_data ... gs_port
71 * gs_port->port_usb ... gserial
73 * gs_port <---> tty_struct ... links will be null when the TTY file
74 * isn't opened; managed by gs_open()/gs_close()
75 * gserial->port_tty ... tty_struct
76 * tty_struct->driver_data ... gserial
79 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
80 * next layer of buffering. For TX that's a circular buffer; for RX
81 * consider it a NOP. A third layer is provided by the TTY code.
84 #define WRITE_BUF_SIZE 8192 /* TX only */
85 #define GS_CONSOLE_BUF_SIZE 8192
87 /* Prevents race conditions while accessing gser->ioport */
88 static DEFINE_SPINLOCK(serial_port_lock);
92 struct console console;
93 struct work_struct work;
95 struct usb_request *req;
101 * The port structure holds info for each port, one for each minor number
102 * (and thus for each /dev/ node).
105 struct tty_port port;
106 spinlock_t port_lock; /* guard port_* access */
108 struct gserial *port_usb;
109 #ifdef CONFIG_U_SERIAL_CONSOLE
110 struct gs_console *console;
115 struct list_head read_pool;
118 struct list_head read_queue;
120 struct delayed_work push;
122 struct list_head write_pool;
125 struct kfifo port_write_buf;
126 wait_queue_head_t drain_wait; /* wait while writes drain */
128 wait_queue_head_t close_wait;
129 bool suspended; /* port suspended */
130 bool start_delayed; /* delay start when suspended */
131 struct async_icount icount;
133 /* REVISIT this state ... */
134 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
137 static struct portmaster {
138 struct mutex lock; /* protect open/close */
139 struct gs_port *port;
140 } ports[MAX_U_SERIAL_PORTS];
142 #define GS_CLOSE_TIMEOUT 15 /* seconds */
148 #define pr_vdebug(fmt, arg...) \
150 #endif /* pr_vdebug */
153 #define pr_vdebug(fmt, arg...) \
154 ({ if (0) pr_debug(fmt, ##arg); })
155 #endif /* pr_vdebug */
158 /*-------------------------------------------------------------------------*/
160 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
165 * Allocate a usb_request and its buffer. Returns a pointer to the
166 * usb_request or NULL if there is an error.
169 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
171 struct usb_request *req;
173 req = usb_ep_alloc_request(ep, kmalloc_flags);
177 req->buf = kmalloc(len, kmalloc_flags);
178 if (req->buf == NULL) {
179 usb_ep_free_request(ep, req);
186 EXPORT_SYMBOL_GPL(gs_alloc_req);
191 * Free a usb_request and its buffer.
193 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
196 usb_ep_free_request(ep, req);
198 EXPORT_SYMBOL_GPL(gs_free_req);
203 * If there is data to send, a packet is built in the given
204 * buffer and the size is returned. If there is no data to
205 * send, 0 is returned.
207 * Called with port_lock held.
210 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
214 len = kfifo_len(&port->port_write_buf);
218 size = kfifo_out(&port->port_write_buf, packet, size);
225 * This function finds available write requests, calls
226 * gs_send_packet to fill these packets with data, and
227 * continues until either there are no more write requests
228 * available or no more data to send. This function is
229 * run whenever data arrives or write requests are available.
231 * Context: caller owns port_lock; port_usb is non-null.
233 static int gs_start_tx(struct gs_port *port)
235 __releases(&port->port_lock)
236 __acquires(&port->port_lock)
239 struct list_head *pool = &port->write_pool;
242 bool do_tty_wake = false;
247 in = port->port_usb->in;
249 while (!port->write_busy && !list_empty(pool)) {
250 struct usb_request *req;
253 if (port->write_started >= QUEUE_SIZE)
256 req = list_entry(pool->next, struct usb_request, list);
257 len = gs_send_packet(port, req->buf, in->maxpacket);
259 wake_up_interruptible(&port->drain_wait);
263 port->icount.tx += len;
266 list_del(&req->list);
267 req->zero = kfifo_is_empty(&port->port_write_buf);
269 pr_vdebug("ttyGS%d: tx len=%d, %3ph ...\n", port->port_num, len, req->buf);
271 /* Drop lock while we call out of driver; completions
272 * could be issued while we do so. Disconnection may
273 * happen too; maybe immediately before we queue this!
275 * NOTE that we may keep sending data for a while after
276 * the TTY closed (dev->ioport->port_tty is NULL).
278 port->write_busy = true;
279 spin_unlock(&port->port_lock);
280 status = usb_ep_queue(in, req, GFP_ATOMIC);
281 spin_lock(&port->port_lock);
282 port->write_busy = false;
285 pr_debug("%s: %s %s err %d\n",
286 __func__, "queue", in->name, status);
287 list_add(&req->list, pool);
291 port->write_started++;
293 /* abort immediately after disconnect */
298 if (do_tty_wake && port->port.tty)
299 tty_wakeup(port->port.tty);
304 * Context: caller owns port_lock, and port_usb is set
306 static unsigned gs_start_rx(struct gs_port *port)
308 __releases(&port->port_lock)
309 __acquires(&port->port_lock)
312 struct list_head *pool = &port->read_pool;
313 struct usb_ep *out = port->port_usb->out;
315 while (!list_empty(pool)) {
316 struct usb_request *req;
318 struct tty_struct *tty;
320 /* no more rx if closed */
321 tty = port->port.tty;
325 if (port->read_started >= QUEUE_SIZE)
328 req = list_entry(pool->next, struct usb_request, list);
329 list_del(&req->list);
330 req->length = out->maxpacket;
332 /* drop lock while we call out; the controller driver
333 * may need to call us back (e.g. for disconnect)
335 spin_unlock(&port->port_lock);
336 status = usb_ep_queue(out, req, GFP_ATOMIC);
337 spin_lock(&port->port_lock);
340 pr_debug("%s: %s %s err %d\n",
341 __func__, "queue", out->name, status);
342 list_add(&req->list, pool);
345 port->read_started++;
347 /* abort immediately after disconnect */
351 return port->read_started;
355 * RX work takes data out of the RX queue and hands it up to the TTY
356 * layer until it refuses to take any more data (or is throttled back).
357 * Then it issues reads for any further data.
359 * If the RX queue becomes full enough that no usb_request is queued,
360 * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
361 * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
362 * can be buffered before the TTY layer's buffers (currently 64 KB).
364 static void gs_rx_push(struct work_struct *work)
366 struct delayed_work *w = to_delayed_work(work);
367 struct gs_port *port = container_of(w, struct gs_port, push);
368 struct tty_struct *tty;
369 struct list_head *queue = &port->read_queue;
370 bool disconnect = false;
371 bool do_push = false;
373 /* hand any queued data to the tty */
374 spin_lock_irq(&port->port_lock);
375 tty = port->port.tty;
376 while (!list_empty(queue)) {
377 struct usb_request *req;
379 req = list_first_entry(queue, struct usb_request, list);
381 /* leave data queued if tty was rx throttled */
382 if (tty && tty_throttled(tty))
385 switch (req->status) {
388 pr_vdebug("ttyGS%d: shutdown\n", port->port_num);
392 /* presumably a transient fault */
393 pr_warn("ttyGS%d: unexpected RX status %d\n",
394 port->port_num, req->status);
397 /* normal completion */
401 /* push data to (open) tty */
402 if (req->actual && tty) {
403 char *packet = req->buf;
404 unsigned size = req->actual;
408 /* we may have pushed part of this packet already... */
415 port->icount.rx += size;
416 count = tty_insert_flip_string(&port->port, packet,
421 /* stop pushing; TTY layer can't handle more */
422 port->n_read += count;
423 pr_vdebug("ttyGS%d: rx block %d/%d\n",
424 port->port_num, count, req->actual);
430 list_move(&req->list, &port->read_pool);
431 port->read_started--;
434 /* Push from tty to ldisc; this is handled by a workqueue,
435 * so we won't get callbacks and can hold port_lock
438 tty_flip_buffer_push(&port->port);
441 /* We want our data queue to become empty ASAP, keeping data
442 * in the tty and ldisc (not here). If we couldn't push any
443 * this time around, RX may be starved, so wait until next jiffy.
445 * We may leave non-empty queue only when there is a tty, and
446 * either it is throttled or there is no more room in flip buffer.
448 if (!list_empty(queue) && !tty_throttled(tty))
449 schedule_delayed_work(&port->push, 1);
451 /* If we're still connected, refill the USB RX queue. */
452 if (!disconnect && port->port_usb)
455 spin_unlock_irq(&port->port_lock);
458 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
460 struct gs_port *port = ep->driver_data;
462 /* Queue all received data until the tty layer is ready for it. */
463 spin_lock(&port->port_lock);
464 list_add_tail(&req->list, &port->read_queue);
465 schedule_delayed_work(&port->push, 0);
466 spin_unlock(&port->port_lock);
469 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
471 struct gs_port *port = ep->driver_data;
473 spin_lock(&port->port_lock);
474 list_add(&req->list, &port->write_pool);
475 port->write_started--;
477 switch (req->status) {
479 /* presumably a transient fault */
480 pr_warn("%s: unexpected %s status %d\n",
481 __func__, ep->name, req->status);
484 /* normal completion */
490 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
494 spin_unlock(&port->port_lock);
497 static void gs_free_requests(struct usb_ep *ep, struct list_head *head,
500 struct usb_request *req;
502 while (!list_empty(head)) {
503 req = list_entry(head->next, struct usb_request, list);
504 list_del(&req->list);
505 gs_free_req(ep, req);
511 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
512 void (*fn)(struct usb_ep *, struct usb_request *),
516 struct usb_request *req;
517 int n = allocated ? QUEUE_SIZE - *allocated : QUEUE_SIZE;
519 /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
520 * do quite that many this time, don't fail ... we just won't
521 * be as speedy as we might otherwise be.
523 for (i = 0; i < n; i++) {
524 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
526 return list_empty(head) ? -ENOMEM : 0;
528 list_add_tail(&req->list, head);
536 * gs_start_io - start USB I/O streams
538 * Context: holding port_lock; port_tty and port_usb are non-null
540 * We only start I/O when something is connected to both sides of
541 * this port. If nothing is listening on the host side, we may
542 * be pointlessly filling up our TX buffers and FIFO.
544 static int gs_start_io(struct gs_port *port)
546 struct list_head *head = &port->read_pool;
551 if (!port->port_usb || !port->port.tty)
554 /* Allocate RX and TX I/O buffers. We can't easily do this much
555 * earlier (with GFP_KERNEL) because the requests are coupled to
556 * endpoints, as are the packet sizes we'll be using. Different
557 * configurations may use different endpoints with a given port;
558 * and high speed vs full speed changes packet sizes too.
560 ep = port->port_usb->out;
561 status = gs_alloc_requests(ep, head, gs_read_complete,
562 &port->read_allocated);
566 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
567 gs_write_complete, &port->write_allocated);
569 gs_free_requests(ep, head, &port->read_allocated);
573 /* queue read requests */
575 started = gs_start_rx(port);
579 /* Unblock any pending writes into our circular buffer, in case
580 * we didn't in gs_start_tx() */
581 tty_wakeup(port->port.tty);
583 /* Free reqs only if we are still connected */
584 if (port->port_usb) {
585 gs_free_requests(ep, head, &port->read_allocated);
586 gs_free_requests(port->port_usb->in, &port->write_pool,
587 &port->write_allocated);
595 /*-------------------------------------------------------------------------*/
600 * gs_open sets up the link between a gs_port and its associated TTY.
601 * That link is broken *only* by TTY close(), and all driver methods
604 static int gs_open(struct tty_struct *tty, struct file *file)
606 int port_num = tty->index;
607 struct gs_port *port;
610 mutex_lock(&ports[port_num].lock);
611 port = ports[port_num].port;
617 spin_lock_irq(&port->port_lock);
619 /* allocate circular buffer on first open */
620 if (!kfifo_initialized(&port->port_write_buf)) {
622 spin_unlock_irq(&port->port_lock);
625 * portmaster's mutex still protects from simultaneous open(),
626 * and close() can't happen, yet.
629 status = kfifo_alloc(&port->port_write_buf,
630 WRITE_BUF_SIZE, GFP_KERNEL);
632 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
633 port_num, tty, file);
637 spin_lock_irq(&port->port_lock);
640 /* already open? Great. */
641 if (port->port.count++)
642 goto exit_unlock_port;
644 tty->driver_data = port;
645 port->port.tty = tty;
647 /* if connected, start the I/O stream */
648 if (port->port_usb) {
649 /* if port is suspended, wait resume to start I/0 stream */
650 if (!port->suspended) {
651 struct gserial *gser = port->port_usb;
653 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
659 pr_debug("delay start of ttyGS%d\n", port->port_num);
660 port->start_delayed = true;
664 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
667 spin_unlock_irq(&port->port_lock);
669 mutex_unlock(&ports[port_num].lock);
673 static int gs_close_flush_done(struct gs_port *p)
677 /* return true on disconnect or empty buffer or if raced with open() */
678 spin_lock_irq(&p->port_lock);
679 cond = p->port_usb == NULL || !kfifo_len(&p->port_write_buf) ||
681 spin_unlock_irq(&p->port_lock);
686 static void gs_close(struct tty_struct *tty, struct file *file)
688 struct gs_port *port = tty->driver_data;
689 struct gserial *gser;
691 spin_lock_irq(&port->port_lock);
693 if (port->port.count != 1) {
695 if (port->port.count == 0)
702 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
704 gser = port->port_usb;
705 if (gser && !port->suspended && gser->disconnect)
706 gser->disconnect(gser);
708 /* wait for circular write buffer to drain, disconnect, or at
709 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
711 if (kfifo_len(&port->port_write_buf) > 0 && gser) {
712 spin_unlock_irq(&port->port_lock);
713 wait_event_interruptible_timeout(port->drain_wait,
714 gs_close_flush_done(port),
715 GS_CLOSE_TIMEOUT * HZ);
716 spin_lock_irq(&port->port_lock);
718 if (port->port.count != 1)
719 goto raced_with_open;
721 gser = port->port_usb;
724 /* Iff we're disconnected, there can be no I/O in flight so it's
725 * ok to free the circular buffer; else just scrub it. And don't
726 * let the push async work fire again until we're re-opened.
729 kfifo_free(&port->port_write_buf);
731 kfifo_reset(&port->port_write_buf);
733 port->start_delayed = false;
734 port->port.count = 0;
735 port->port.tty = NULL;
737 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
738 port->port_num, tty, file);
740 wake_up(&port->close_wait);
742 spin_unlock_irq(&port->port_lock);
745 static ssize_t gs_write(struct tty_struct *tty, const u8 *buf, size_t count)
747 struct gs_port *port = tty->driver_data;
750 pr_vdebug("gs_write: ttyGS%d (%p) writing %zu bytes\n",
751 port->port_num, tty, count);
753 spin_lock_irqsave(&port->port_lock, flags);
755 count = kfifo_in(&port->port_write_buf, buf, count);
756 /* treat count == 0 as flush_chars() */
759 spin_unlock_irqrestore(&port->port_lock, flags);
764 static int gs_put_char(struct tty_struct *tty, u8 ch)
766 struct gs_port *port = tty->driver_data;
770 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %ps\n",
771 port->port_num, tty, ch, __builtin_return_address(0));
773 spin_lock_irqsave(&port->port_lock, flags);
774 status = kfifo_put(&port->port_write_buf, ch);
775 spin_unlock_irqrestore(&port->port_lock, flags);
780 static void gs_flush_chars(struct tty_struct *tty)
782 struct gs_port *port = tty->driver_data;
785 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
787 spin_lock_irqsave(&port->port_lock, flags);
790 spin_unlock_irqrestore(&port->port_lock, flags);
793 static unsigned int gs_write_room(struct tty_struct *tty)
795 struct gs_port *port = tty->driver_data;
797 unsigned int room = 0;
799 spin_lock_irqsave(&port->port_lock, flags);
801 room = kfifo_avail(&port->port_write_buf);
802 spin_unlock_irqrestore(&port->port_lock, flags);
804 pr_vdebug("gs_write_room: (%d,%p) room=%u\n",
805 port->port_num, tty, room);
810 static unsigned int gs_chars_in_buffer(struct tty_struct *tty)
812 struct gs_port *port = tty->driver_data;
816 spin_lock_irqsave(&port->port_lock, flags);
817 chars = kfifo_len(&port->port_write_buf);
818 spin_unlock_irqrestore(&port->port_lock, flags);
820 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%u\n",
821 port->port_num, tty, chars);
826 /* undo side effects of setting TTY_THROTTLED */
827 static void gs_unthrottle(struct tty_struct *tty)
829 struct gs_port *port = tty->driver_data;
832 spin_lock_irqsave(&port->port_lock, flags);
833 if (port->port_usb) {
834 /* Kickstart read queue processing. We don't do xon/xoff,
835 * rts/cts, or other handshaking with the host, but if the
836 * read queue backs up enough we'll be NAKing OUT packets.
838 pr_vdebug("ttyGS%d: unthrottle\n", port->port_num);
839 schedule_delayed_work(&port->push, 0);
841 spin_unlock_irqrestore(&port->port_lock, flags);
844 static int gs_break_ctl(struct tty_struct *tty, int duration)
846 struct gs_port *port = tty->driver_data;
848 struct gserial *gser;
850 pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
851 port->port_num, duration);
853 spin_lock_irq(&port->port_lock);
854 gser = port->port_usb;
855 if (gser && gser->send_break)
856 status = gser->send_break(gser, duration);
857 spin_unlock_irq(&port->port_lock);
862 static int gs_get_icount(struct tty_struct *tty,
863 struct serial_icounter_struct *icount)
865 struct gs_port *port = tty->driver_data;
866 struct async_icount cnow;
869 spin_lock_irqsave(&port->port_lock, flags);
871 spin_unlock_irqrestore(&port->port_lock, flags);
873 icount->rx = cnow.rx;
874 icount->tx = cnow.tx;
879 static const struct tty_operations gs_tty_ops = {
883 .put_char = gs_put_char,
884 .flush_chars = gs_flush_chars,
885 .write_room = gs_write_room,
886 .chars_in_buffer = gs_chars_in_buffer,
887 .unthrottle = gs_unthrottle,
888 .break_ctl = gs_break_ctl,
889 .get_icount = gs_get_icount,
892 /*-------------------------------------------------------------------------*/
894 static struct tty_driver *gs_tty_driver;
896 #ifdef CONFIG_U_SERIAL_CONSOLE
898 static void gs_console_complete_out(struct usb_ep *ep, struct usb_request *req)
900 struct gs_console *cons = req->context;
902 switch (req->status) {
904 pr_warn("%s: unexpected %s status %d\n",
905 __func__, ep->name, req->status);
908 /* normal completion */
909 spin_lock(&cons->lock);
911 schedule_work(&cons->work);
912 spin_unlock(&cons->lock);
917 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
922 static void __gs_console_push(struct gs_console *cons)
924 struct usb_request *req = cons->req;
929 return; /* disconnected */
934 ep = cons->console.data;
935 size = kfifo_out(&cons->buf, req->buf, ep->maxpacket);
939 if (cons->missed && ep->maxpacket >= 64) {
943 len = sprintf(buf, "\n[missed %zu bytes]\n", cons->missed);
944 kfifo_in(&cons->buf, buf, len);
950 spin_unlock_irq(&cons->lock);
951 if (usb_ep_queue(ep, req, GFP_ATOMIC))
953 spin_lock_irq(&cons->lock);
956 static void gs_console_work(struct work_struct *work)
958 struct gs_console *cons = container_of(work, struct gs_console, work);
960 spin_lock_irq(&cons->lock);
962 __gs_console_push(cons);
964 spin_unlock_irq(&cons->lock);
967 static void gs_console_write(struct console *co,
968 const char *buf, unsigned count)
970 struct gs_console *cons = container_of(co, struct gs_console, console);
974 spin_lock_irqsave(&cons->lock, flags);
976 n = kfifo_in(&cons->buf, buf, count);
978 cons->missed += count - n;
980 if (cons->req && !cons->req->length)
981 schedule_work(&cons->work);
983 spin_unlock_irqrestore(&cons->lock, flags);
986 static struct tty_driver *gs_console_device(struct console *co, int *index)
989 return gs_tty_driver;
992 static int gs_console_connect(struct gs_port *port)
994 struct gs_console *cons = port->console;
995 struct usb_request *req;
1001 ep = port->port_usb->in;
1002 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
1005 req->complete = gs_console_complete_out;
1006 req->context = cons;
1009 spin_lock(&cons->lock);
1011 cons->console.data = ep;
1012 spin_unlock(&cons->lock);
1014 pr_debug("ttyGS%d: console connected!\n", port->port_num);
1016 schedule_work(&cons->work);
1021 static void gs_console_disconnect(struct gs_port *port)
1023 struct gs_console *cons = port->console;
1024 struct usb_request *req;
1030 spin_lock(&cons->lock);
1033 ep = cons->console.data;
1036 spin_unlock(&cons->lock);
1041 usb_ep_dequeue(ep, req);
1042 gs_free_req(ep, req);
1045 static int gs_console_init(struct gs_port *port)
1047 struct gs_console *cons;
1053 cons = kzalloc(sizeof(*port->console), GFP_KERNEL);
1057 strcpy(cons->console.name, "ttyGS");
1058 cons->console.write = gs_console_write;
1059 cons->console.device = gs_console_device;
1060 cons->console.flags = CON_PRINTBUFFER;
1061 cons->console.index = port->port_num;
1063 INIT_WORK(&cons->work, gs_console_work);
1064 spin_lock_init(&cons->lock);
1066 err = kfifo_alloc(&cons->buf, GS_CONSOLE_BUF_SIZE, GFP_KERNEL);
1068 pr_err("ttyGS%d: allocate console buffer failed\n", port->port_num);
1073 port->console = cons;
1074 register_console(&cons->console);
1076 spin_lock_irq(&port->port_lock);
1078 gs_console_connect(port);
1079 spin_unlock_irq(&port->port_lock);
1084 static void gs_console_exit(struct gs_port *port)
1086 struct gs_console *cons = port->console;
1091 unregister_console(&cons->console);
1093 spin_lock_irq(&port->port_lock);
1095 gs_console_disconnect(port);
1096 spin_unlock_irq(&port->port_lock);
1098 cancel_work_sync(&cons->work);
1099 kfifo_free(&cons->buf);
1101 port->console = NULL;
1104 ssize_t gserial_set_console(unsigned char port_num, const char *page, size_t count)
1106 struct gs_port *port;
1110 ret = kstrtobool(page, &enable);
1114 mutex_lock(&ports[port_num].lock);
1115 port = ports[port_num].port;
1117 if (WARN_ON(port == NULL)) {
1123 ret = gs_console_init(port);
1125 gs_console_exit(port);
1127 mutex_unlock(&ports[port_num].lock);
1129 return ret < 0 ? ret : count;
1131 EXPORT_SYMBOL_GPL(gserial_set_console);
1133 ssize_t gserial_get_console(unsigned char port_num, char *page)
1135 struct gs_port *port;
1138 mutex_lock(&ports[port_num].lock);
1139 port = ports[port_num].port;
1141 if (WARN_ON(port == NULL))
1144 ret = sprintf(page, "%u\n", !!port->console);
1146 mutex_unlock(&ports[port_num].lock);
1150 EXPORT_SYMBOL_GPL(gserial_get_console);
1154 static int gs_console_connect(struct gs_port *port)
1159 static void gs_console_disconnect(struct gs_port *port)
1163 static int gs_console_init(struct gs_port *port)
1168 static void gs_console_exit(struct gs_port *port)
1175 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1177 struct gs_port *port;
1180 mutex_lock(&ports[port_num].lock);
1181 if (ports[port_num].port) {
1186 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1192 tty_port_init(&port->port);
1193 spin_lock_init(&port->port_lock);
1194 init_waitqueue_head(&port->drain_wait);
1195 init_waitqueue_head(&port->close_wait);
1197 INIT_DELAYED_WORK(&port->push, gs_rx_push);
1199 INIT_LIST_HEAD(&port->read_pool);
1200 INIT_LIST_HEAD(&port->read_queue);
1201 INIT_LIST_HEAD(&port->write_pool);
1203 port->port_num = port_num;
1204 port->port_line_coding = *coding;
1206 ports[port_num].port = port;
1208 mutex_unlock(&ports[port_num].lock);
1212 static int gs_closed(struct gs_port *port)
1216 spin_lock_irq(&port->port_lock);
1217 cond = port->port.count == 0;
1218 spin_unlock_irq(&port->port_lock);
1223 static void gserial_free_port(struct gs_port *port)
1225 cancel_delayed_work_sync(&port->push);
1226 /* wait for old opens to finish */
1227 wait_event(port->close_wait, gs_closed(port));
1228 WARN_ON(port->port_usb != NULL);
1229 tty_port_destroy(&port->port);
1233 void gserial_free_line(unsigned char port_num)
1235 struct gs_port *port;
1237 mutex_lock(&ports[port_num].lock);
1238 if (!ports[port_num].port) {
1239 mutex_unlock(&ports[port_num].lock);
1242 port = ports[port_num].port;
1243 gs_console_exit(port);
1244 ports[port_num].port = NULL;
1245 mutex_unlock(&ports[port_num].lock);
1247 gserial_free_port(port);
1248 tty_unregister_device(gs_tty_driver, port_num);
1250 EXPORT_SYMBOL_GPL(gserial_free_line);
1252 int gserial_alloc_line_no_console(unsigned char *line_num)
1254 struct usb_cdc_line_coding coding;
1255 struct gs_port *port;
1256 struct device *tty_dev;
1260 coding.dwDTERate = cpu_to_le32(9600);
1261 coding.bCharFormat = 8;
1262 coding.bParityType = USB_CDC_NO_PARITY;
1263 coding.bDataBits = USB_CDC_1_STOP_BITS;
1265 for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) {
1266 ret = gs_port_alloc(port_num, &coding);
1276 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1278 port = ports[port_num].port;
1279 tty_dev = tty_port_register_device(&port->port,
1280 gs_tty_driver, port_num, NULL);
1281 if (IS_ERR(tty_dev)) {
1282 pr_err("%s: failed to register tty for port %d, err %ld\n",
1283 __func__, port_num, PTR_ERR(tty_dev));
1285 ret = PTR_ERR(tty_dev);
1286 mutex_lock(&ports[port_num].lock);
1287 ports[port_num].port = NULL;
1288 mutex_unlock(&ports[port_num].lock);
1289 gserial_free_port(port);
1292 *line_num = port_num;
1296 EXPORT_SYMBOL_GPL(gserial_alloc_line_no_console);
1298 int gserial_alloc_line(unsigned char *line_num)
1300 int ret = gserial_alloc_line_no_console(line_num);
1302 if (!ret && !*line_num)
1303 gs_console_init(ports[*line_num].port);
1307 EXPORT_SYMBOL_GPL(gserial_alloc_line);
1310 * gserial_connect - notify TTY I/O glue that USB link is active
1311 * @gser: the function, set up with endpoints and descriptors
1312 * @port_num: which port is active
1313 * Context: any (usually from irq)
1315 * This is called activate endpoints and let the TTY layer know that
1316 * the connection is active ... not unlike "carrier detect". It won't
1317 * necessarily start I/O queues; unless the TTY is held open by any
1318 * task, there would be no point. However, the endpoints will be
1319 * activated so the USB host can perform I/O, subject to basic USB
1320 * hardware flow control.
1322 * Caller needs to have set up the endpoints and USB function in @dev
1323 * before calling this, as well as the appropriate (speed-specific)
1324 * endpoint descriptors, and also have allocate @port_num by calling
1325 * @gserial_alloc_line().
1327 * Returns negative errno or zero.
1328 * On success, ep->driver_data will be overwritten.
1330 int gserial_connect(struct gserial *gser, u8 port_num)
1332 struct gs_port *port;
1333 unsigned long flags;
1336 if (port_num >= MAX_U_SERIAL_PORTS)
1339 port = ports[port_num].port;
1341 pr_err("serial line %d not allocated.\n", port_num);
1344 if (port->port_usb) {
1345 pr_err("serial line %d is in use.\n", port_num);
1349 /* activate the endpoints */
1350 status = usb_ep_enable(gser->in);
1353 gser->in->driver_data = port;
1355 status = usb_ep_enable(gser->out);
1358 gser->out->driver_data = port;
1360 /* then tell the tty glue that I/O can work */
1361 spin_lock_irqsave(&port->port_lock, flags);
1362 gser->ioport = port;
1363 port->port_usb = gser;
1365 /* REVISIT unclear how best to handle this state...
1366 * we don't really couple it with the Linux TTY.
1368 gser->port_line_coding = port->port_line_coding;
1370 /* REVISIT if waiting on "carrier detect", signal. */
1372 /* if it's already open, start I/O ... and notify the serial
1373 * protocol about open/close status (connect/disconnect).
1375 if (port->port.count) {
1376 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1379 gser->connect(gser);
1381 if (gser->disconnect)
1382 gser->disconnect(gser);
1385 status = gs_console_connect(port);
1386 spin_unlock_irqrestore(&port->port_lock, flags);
1391 usb_ep_disable(gser->in);
1394 EXPORT_SYMBOL_GPL(gserial_connect);
1396 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1397 * @gser: the function, on which gserial_connect() was called
1398 * Context: any (usually from irq)
1400 * This is called to deactivate endpoints and let the TTY layer know
1401 * that the connection went inactive ... not unlike "hangup".
1403 * On return, the state is as if gserial_connect() had never been called;
1404 * there is no active USB I/O on these endpoints.
1406 void gserial_disconnect(struct gserial *gser)
1408 struct gs_port *port = gser->ioport;
1409 unsigned long flags;
1414 spin_lock_irqsave(&serial_port_lock, flags);
1416 /* tell the TTY glue not to do I/O here any more */
1417 spin_lock(&port->port_lock);
1419 gs_console_disconnect(port);
1421 /* REVISIT as above: how best to track this? */
1422 port->port_line_coding = gser->port_line_coding;
1424 port->port_usb = NULL;
1425 gser->ioport = NULL;
1426 if (port->port.count > 0) {
1427 wake_up_interruptible(&port->drain_wait);
1429 tty_hangup(port->port.tty);
1431 port->suspended = false;
1432 spin_unlock(&port->port_lock);
1433 spin_unlock_irqrestore(&serial_port_lock, flags);
1435 /* disable endpoints, aborting down any active I/O */
1436 usb_ep_disable(gser->out);
1437 usb_ep_disable(gser->in);
1439 /* finally, free any unused/unusable I/O buffers */
1440 spin_lock_irqsave(&port->port_lock, flags);
1441 if (port->port.count == 0)
1442 kfifo_free(&port->port_write_buf);
1443 gs_free_requests(gser->out, &port->read_pool, NULL);
1444 gs_free_requests(gser->out, &port->read_queue, NULL);
1445 gs_free_requests(gser->in, &port->write_pool, NULL);
1447 port->read_allocated = port->read_started =
1448 port->write_allocated = port->write_started = 0;
1450 spin_unlock_irqrestore(&port->port_lock, flags);
1452 EXPORT_SYMBOL_GPL(gserial_disconnect);
1454 void gserial_suspend(struct gserial *gser)
1456 struct gs_port *port;
1457 unsigned long flags;
1459 spin_lock_irqsave(&serial_port_lock, flags);
1460 port = gser->ioport;
1463 spin_unlock_irqrestore(&serial_port_lock, flags);
1467 spin_lock(&port->port_lock);
1468 spin_unlock(&serial_port_lock);
1469 port->suspended = true;
1470 port->start_delayed = true;
1471 spin_unlock_irqrestore(&port->port_lock, flags);
1473 EXPORT_SYMBOL_GPL(gserial_suspend);
1475 void gserial_resume(struct gserial *gser)
1477 struct gs_port *port;
1478 unsigned long flags;
1480 spin_lock_irqsave(&serial_port_lock, flags);
1481 port = gser->ioport;
1484 spin_unlock_irqrestore(&serial_port_lock, flags);
1488 spin_lock(&port->port_lock);
1489 spin_unlock(&serial_port_lock);
1490 port->suspended = false;
1491 if (!port->start_delayed) {
1492 spin_unlock_irqrestore(&port->port_lock, flags);
1496 pr_debug("delayed start ttyGS%d\n", port->port_num);
1499 gser->connect(gser);
1500 port->start_delayed = false;
1501 spin_unlock_irqrestore(&port->port_lock, flags);
1503 EXPORT_SYMBOL_GPL(gserial_resume);
1505 static int __init userial_init(void)
1507 struct tty_driver *driver;
1511 driver = tty_alloc_driver(MAX_U_SERIAL_PORTS, TTY_DRIVER_REAL_RAW |
1512 TTY_DRIVER_DYNAMIC_DEV);
1514 return PTR_ERR(driver);
1516 driver->driver_name = "g_serial";
1517 driver->name = "ttyGS";
1518 /* uses dynamically assigned dev_t values */
1520 driver->type = TTY_DRIVER_TYPE_SERIAL;
1521 driver->subtype = SERIAL_TYPE_NORMAL;
1522 driver->init_termios = tty_std_termios;
1524 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1525 * MS-Windows. Otherwise, most of these flags shouldn't affect
1526 * anything unless we were to actually hook up to a serial line.
1528 driver->init_termios.c_cflag =
1529 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1530 driver->init_termios.c_ispeed = 9600;
1531 driver->init_termios.c_ospeed = 9600;
1533 tty_set_operations(driver, &gs_tty_ops);
1534 for (i = 0; i < MAX_U_SERIAL_PORTS; i++)
1535 mutex_init(&ports[i].lock);
1537 /* export the driver ... */
1538 status = tty_register_driver(driver);
1540 pr_err("%s: cannot register, err %d\n",
1545 gs_tty_driver = driver;
1547 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1549 str_plural(MAX_U_SERIAL_PORTS));
1553 tty_driver_kref_put(driver);
1556 module_init(userial_init);
1558 static void __exit userial_cleanup(void)
1560 tty_unregister_driver(gs_tty_driver);
1561 tty_driver_kref_put(gs_tty_driver);
1562 gs_tty_driver = NULL;
1564 module_exit(userial_cleanup);
1566 MODULE_DESCRIPTION("utilities for USB gadget \"serial port\"/TTY support");
1567 MODULE_LICENSE("GPL");