1 // SPDX-License-Identifier: GPL-2.0+
3 * u_serial.c - utilities for USB gadget "serial port"/TTY support
5 * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
6 * Copyright (C) 2008 David Brownell
7 * Copyright (C) 2008 by Nokia Corporation
9 * This code also borrows from usbserial.c, which is
10 * Copyright (C) 1999 - 2002 Greg Kroah-Hartman (greg@kroah.com)
11 * Copyright (C) 2000 Peter Berger (pberger@brimson.com)
12 * Copyright (C) 2000 Al Borchers (alborchers@steinerpoint.com)
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 */
299 tty_port_tty_wakeup(&port->port);
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;
547 struct usb_ep *ep = port->port_usb->out;
551 /* Allocate RX and TX I/O buffers. We can't easily do this much
552 * earlier (with GFP_KERNEL) because the requests are coupled to
553 * endpoints, as are the packet sizes we'll be using. Different
554 * configurations may use different endpoints with a given port;
555 * and high speed vs full speed changes packet sizes too.
557 status = gs_alloc_requests(ep, head, gs_read_complete,
558 &port->read_allocated);
562 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
563 gs_write_complete, &port->write_allocated);
565 gs_free_requests(ep, head, &port->read_allocated);
569 /* queue read requests */
571 started = gs_start_rx(port);
575 /* Unblock any pending writes into our circular buffer, in case
576 * we didn't in gs_start_tx() */
577 tty_port_tty_wakeup(&port->port);
579 /* Free reqs only if we are still connected */
580 if (port->port_usb) {
581 gs_free_requests(ep, head, &port->read_allocated);
582 gs_free_requests(port->port_usb->in, &port->write_pool,
583 &port->write_allocated);
591 static int gserial_wakeup_host(struct gserial *gser)
593 struct usb_function *func = &gser->func;
594 struct usb_gadget *gadget = func->config->cdev->gadget;
596 if (func->func_suspended)
597 return usb_func_wakeup(func);
599 return usb_gadget_wakeup(gadget);
602 /*-------------------------------------------------------------------------*/
607 * gs_open sets up the link between a gs_port and its associated TTY.
608 * That link is broken *only* by TTY close(), and all driver methods
611 static int gs_open(struct tty_struct *tty, struct file *file)
613 int port_num = tty->index;
614 struct gs_port *port;
617 mutex_lock(&ports[port_num].lock);
618 port = ports[port_num].port;
624 spin_lock_irq(&port->port_lock);
626 /* allocate circular buffer on first open */
627 if (!kfifo_initialized(&port->port_write_buf)) {
629 spin_unlock_irq(&port->port_lock);
632 * portmaster's mutex still protects from simultaneous open(),
633 * and close() can't happen, yet.
636 status = kfifo_alloc(&port->port_write_buf,
637 WRITE_BUF_SIZE, GFP_KERNEL);
639 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
640 port_num, tty, file);
644 spin_lock_irq(&port->port_lock);
647 /* already open? Great. */
648 if (port->port.count++)
649 goto exit_unlock_port;
651 tty->driver_data = port;
652 port->port.tty = tty;
654 /* if connected, start the I/O stream */
655 if (port->port_usb) {
656 /* if port is suspended, wait resume to start I/0 stream */
657 if (!port->suspended) {
658 struct gserial *gser = port->port_usb;
660 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
666 pr_debug("delay start of ttyGS%d\n", port->port_num);
667 port->start_delayed = true;
671 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
674 spin_unlock_irq(&port->port_lock);
676 mutex_unlock(&ports[port_num].lock);
680 static int gs_close_flush_done(struct gs_port *p)
684 /* return true on disconnect or empty buffer or if raced with open() */
685 spin_lock_irq(&p->port_lock);
686 cond = p->port_usb == NULL || !kfifo_len(&p->port_write_buf) ||
688 spin_unlock_irq(&p->port_lock);
693 static void gs_close(struct tty_struct *tty, struct file *file)
695 struct gs_port *port = tty->driver_data;
696 struct gserial *gser;
698 spin_lock_irq(&port->port_lock);
700 if (port->port.count != 1) {
702 if (port->port.count == 0)
709 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
711 gser = port->port_usb;
712 if (gser && !port->suspended && gser->disconnect)
713 gser->disconnect(gser);
715 /* wait for circular write buffer to drain, disconnect, or at
716 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
718 if (kfifo_len(&port->port_write_buf) > 0 && gser) {
719 spin_unlock_irq(&port->port_lock);
720 wait_event_interruptible_timeout(port->drain_wait,
721 gs_close_flush_done(port),
722 GS_CLOSE_TIMEOUT * HZ);
723 spin_lock_irq(&port->port_lock);
725 if (port->port.count != 1)
726 goto raced_with_open;
728 gser = port->port_usb;
731 /* Iff we're disconnected, there can be no I/O in flight so it's
732 * ok to free the circular buffer; else just scrub it. And don't
733 * let the push async work fire again until we're re-opened.
736 kfifo_free(&port->port_write_buf);
738 kfifo_reset(&port->port_write_buf);
740 port->start_delayed = false;
741 port->port.count = 0;
742 port->port.tty = NULL;
744 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
745 port->port_num, tty, file);
747 wake_up(&port->close_wait);
749 spin_unlock_irq(&port->port_lock);
752 static ssize_t gs_write(struct tty_struct *tty, const u8 *buf, size_t count)
754 struct gs_port *port = tty->driver_data;
757 struct gserial *gser = port->port_usb;
759 pr_vdebug("gs_write: ttyGS%d (%p) writing %zu bytes\n",
760 port->port_num, tty, count);
762 spin_lock_irqsave(&port->port_lock, flags);
764 count = kfifo_in(&port->port_write_buf, buf, count);
766 if (port->suspended) {
767 spin_unlock_irqrestore(&port->port_lock, flags);
768 ret = gserial_wakeup_host(gser);
770 pr_debug("ttyGS%d: Remote wakeup failed:%d\n", port->port_num, ret);
773 spin_lock_irqsave(&port->port_lock, flags);
776 /* treat count == 0 as flush_chars() */
779 spin_unlock_irqrestore(&port->port_lock, flags);
784 static int gs_put_char(struct tty_struct *tty, u8 ch)
786 struct gs_port *port = tty->driver_data;
790 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %ps\n",
791 port->port_num, tty, ch, __builtin_return_address(0));
793 spin_lock_irqsave(&port->port_lock, flags);
794 status = kfifo_put(&port->port_write_buf, ch);
795 spin_unlock_irqrestore(&port->port_lock, flags);
800 static void gs_flush_chars(struct tty_struct *tty)
802 struct gs_port *port = tty->driver_data;
805 struct gserial *gser = port->port_usb;
807 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
809 spin_lock_irqsave(&port->port_lock, flags);
810 if (port->suspended) {
811 spin_unlock_irqrestore(&port->port_lock, flags);
812 ret = gserial_wakeup_host(gser);
814 pr_debug("ttyGS%d: Remote wakeup failed:%d\n", port->port_num, ret);
817 spin_lock_irqsave(&port->port_lock, flags);
822 spin_unlock_irqrestore(&port->port_lock, flags);
825 static unsigned int gs_write_room(struct tty_struct *tty)
827 struct gs_port *port = tty->driver_data;
829 unsigned int room = 0;
831 spin_lock_irqsave(&port->port_lock, flags);
833 room = kfifo_avail(&port->port_write_buf);
834 spin_unlock_irqrestore(&port->port_lock, flags);
836 pr_vdebug("gs_write_room: (%d,%p) room=%u\n",
837 port->port_num, tty, room);
842 static unsigned int gs_chars_in_buffer(struct tty_struct *tty)
844 struct gs_port *port = tty->driver_data;
848 spin_lock_irqsave(&port->port_lock, flags);
849 chars = kfifo_len(&port->port_write_buf);
850 spin_unlock_irqrestore(&port->port_lock, flags);
852 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%u\n",
853 port->port_num, tty, chars);
858 /* undo side effects of setting TTY_THROTTLED */
859 static void gs_unthrottle(struct tty_struct *tty)
861 struct gs_port *port = tty->driver_data;
864 spin_lock_irqsave(&port->port_lock, flags);
865 if (port->port_usb) {
866 /* Kickstart read queue processing. We don't do xon/xoff,
867 * rts/cts, or other handshaking with the host, but if the
868 * read queue backs up enough we'll be NAKing OUT packets.
870 pr_vdebug("ttyGS%d: unthrottle\n", port->port_num);
871 schedule_delayed_work(&port->push, 0);
873 spin_unlock_irqrestore(&port->port_lock, flags);
876 static int gs_break_ctl(struct tty_struct *tty, int duration)
878 struct gs_port *port = tty->driver_data;
880 struct gserial *gser;
882 pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
883 port->port_num, duration);
885 spin_lock_irq(&port->port_lock);
886 gser = port->port_usb;
887 if (gser && gser->send_break)
888 status = gser->send_break(gser, duration);
889 spin_unlock_irq(&port->port_lock);
894 static int gs_get_icount(struct tty_struct *tty,
895 struct serial_icounter_struct *icount)
897 struct gs_port *port = tty->driver_data;
898 struct async_icount cnow;
901 spin_lock_irqsave(&port->port_lock, flags);
903 spin_unlock_irqrestore(&port->port_lock, flags);
905 icount->rx = cnow.rx;
906 icount->tx = cnow.tx;
911 static const struct tty_operations gs_tty_ops = {
915 .put_char = gs_put_char,
916 .flush_chars = gs_flush_chars,
917 .write_room = gs_write_room,
918 .chars_in_buffer = gs_chars_in_buffer,
919 .unthrottle = gs_unthrottle,
920 .break_ctl = gs_break_ctl,
921 .get_icount = gs_get_icount,
924 /*-------------------------------------------------------------------------*/
926 static struct tty_driver *gs_tty_driver;
928 #ifdef CONFIG_U_SERIAL_CONSOLE
930 static void gs_console_complete_out(struct usb_ep *ep, struct usb_request *req)
932 struct gs_console *cons = req->context;
934 switch (req->status) {
936 pr_warn("%s: unexpected %s status %d\n",
937 __func__, ep->name, req->status);
940 /* normal completion */
941 spin_lock(&cons->lock);
943 schedule_work(&cons->work);
944 spin_unlock(&cons->lock);
949 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
954 static void __gs_console_push(struct gs_console *cons)
956 struct usb_request *req = cons->req;
961 return; /* disconnected */
966 ep = cons->console.data;
967 size = kfifo_out(&cons->buf, req->buf, ep->maxpacket);
971 if (cons->missed && ep->maxpacket >= 64) {
975 len = sprintf(buf, "\n[missed %zu bytes]\n", cons->missed);
976 kfifo_in(&cons->buf, buf, len);
982 spin_unlock_irq(&cons->lock);
983 if (usb_ep_queue(ep, req, GFP_ATOMIC))
985 spin_lock_irq(&cons->lock);
988 static void gs_console_work(struct work_struct *work)
990 struct gs_console *cons = container_of(work, struct gs_console, work);
992 spin_lock_irq(&cons->lock);
994 __gs_console_push(cons);
996 spin_unlock_irq(&cons->lock);
999 static void gs_console_write(struct console *co,
1000 const char *buf, unsigned count)
1002 struct gs_console *cons = container_of(co, struct gs_console, console);
1003 unsigned long flags;
1006 spin_lock_irqsave(&cons->lock, flags);
1008 n = kfifo_in(&cons->buf, buf, count);
1010 cons->missed += count - n;
1012 if (cons->req && !cons->req->length)
1013 schedule_work(&cons->work);
1015 spin_unlock_irqrestore(&cons->lock, flags);
1018 static struct tty_driver *gs_console_device(struct console *co, int *index)
1021 return gs_tty_driver;
1024 static int gs_console_connect(struct gs_port *port)
1026 struct gs_console *cons = port->console;
1027 struct usb_request *req;
1033 ep = port->port_usb->in;
1034 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
1037 req->complete = gs_console_complete_out;
1038 req->context = cons;
1041 spin_lock(&cons->lock);
1043 cons->console.data = ep;
1044 spin_unlock(&cons->lock);
1046 pr_debug("ttyGS%d: console connected!\n", port->port_num);
1048 schedule_work(&cons->work);
1053 static void gs_console_disconnect(struct gs_port *port)
1055 struct gs_console *cons = port->console;
1056 struct usb_request *req;
1062 spin_lock(&cons->lock);
1065 ep = cons->console.data;
1068 spin_unlock(&cons->lock);
1073 usb_ep_dequeue(ep, req);
1074 gs_free_req(ep, req);
1077 static int gs_console_init(struct gs_port *port)
1079 struct gs_console *cons;
1085 cons = kzalloc(sizeof(*port->console), GFP_KERNEL);
1089 strcpy(cons->console.name, "ttyGS");
1090 cons->console.write = gs_console_write;
1091 cons->console.device = gs_console_device;
1092 cons->console.flags = CON_PRINTBUFFER;
1093 cons->console.index = port->port_num;
1095 INIT_WORK(&cons->work, gs_console_work);
1096 spin_lock_init(&cons->lock);
1098 err = kfifo_alloc(&cons->buf, GS_CONSOLE_BUF_SIZE, GFP_KERNEL);
1100 pr_err("ttyGS%d: allocate console buffer failed\n", port->port_num);
1105 port->console = cons;
1106 register_console(&cons->console);
1108 spin_lock_irq(&port->port_lock);
1110 gs_console_connect(port);
1111 spin_unlock_irq(&port->port_lock);
1116 static void gs_console_exit(struct gs_port *port)
1118 struct gs_console *cons = port->console;
1123 unregister_console(&cons->console);
1125 spin_lock_irq(&port->port_lock);
1127 gs_console_disconnect(port);
1128 spin_unlock_irq(&port->port_lock);
1130 cancel_work_sync(&cons->work);
1131 kfifo_free(&cons->buf);
1133 port->console = NULL;
1136 ssize_t gserial_set_console(unsigned char port_num, const char *page, size_t count)
1138 struct gs_port *port;
1142 ret = kstrtobool(page, &enable);
1146 mutex_lock(&ports[port_num].lock);
1147 port = ports[port_num].port;
1149 if (WARN_ON(port == NULL)) {
1155 ret = gs_console_init(port);
1157 gs_console_exit(port);
1159 mutex_unlock(&ports[port_num].lock);
1161 return ret < 0 ? ret : count;
1163 EXPORT_SYMBOL_GPL(gserial_set_console);
1165 ssize_t gserial_get_console(unsigned char port_num, char *page)
1167 struct gs_port *port;
1170 mutex_lock(&ports[port_num].lock);
1171 port = ports[port_num].port;
1173 if (WARN_ON(port == NULL))
1176 ret = sprintf(page, "%u\n", !!port->console);
1178 mutex_unlock(&ports[port_num].lock);
1182 EXPORT_SYMBOL_GPL(gserial_get_console);
1186 static int gs_console_connect(struct gs_port *port)
1191 static void gs_console_disconnect(struct gs_port *port)
1195 static int gs_console_init(struct gs_port *port)
1200 static void gs_console_exit(struct gs_port *port)
1207 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1209 struct gs_port *port;
1212 mutex_lock(&ports[port_num].lock);
1213 if (ports[port_num].port) {
1218 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1224 tty_port_init(&port->port);
1225 spin_lock_init(&port->port_lock);
1226 init_waitqueue_head(&port->drain_wait);
1227 init_waitqueue_head(&port->close_wait);
1229 INIT_DELAYED_WORK(&port->push, gs_rx_push);
1231 INIT_LIST_HEAD(&port->read_pool);
1232 INIT_LIST_HEAD(&port->read_queue);
1233 INIT_LIST_HEAD(&port->write_pool);
1235 port->port_num = port_num;
1236 port->port_line_coding = *coding;
1238 ports[port_num].port = port;
1240 mutex_unlock(&ports[port_num].lock);
1244 static int gs_closed(struct gs_port *port)
1248 spin_lock_irq(&port->port_lock);
1249 cond = port->port.count == 0;
1250 spin_unlock_irq(&port->port_lock);
1255 static void gserial_free_port(struct gs_port *port)
1257 cancel_delayed_work_sync(&port->push);
1258 /* wait for old opens to finish */
1259 wait_event(port->close_wait, gs_closed(port));
1260 WARN_ON(port->port_usb != NULL);
1261 tty_port_destroy(&port->port);
1265 void gserial_free_line(unsigned char port_num)
1267 struct gs_port *port;
1269 mutex_lock(&ports[port_num].lock);
1270 if (!ports[port_num].port) {
1271 mutex_unlock(&ports[port_num].lock);
1274 port = ports[port_num].port;
1275 gs_console_exit(port);
1276 ports[port_num].port = NULL;
1277 mutex_unlock(&ports[port_num].lock);
1279 gserial_free_port(port);
1280 tty_unregister_device(gs_tty_driver, port_num);
1282 EXPORT_SYMBOL_GPL(gserial_free_line);
1284 int gserial_alloc_line_no_console(unsigned char *line_num)
1286 struct usb_cdc_line_coding coding;
1287 struct gs_port *port;
1288 struct device *tty_dev;
1292 coding.dwDTERate = cpu_to_le32(9600);
1293 coding.bCharFormat = 8;
1294 coding.bParityType = USB_CDC_NO_PARITY;
1295 coding.bDataBits = USB_CDC_1_STOP_BITS;
1297 for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) {
1298 ret = gs_port_alloc(port_num, &coding);
1308 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1310 port = ports[port_num].port;
1311 tty_dev = tty_port_register_device(&port->port,
1312 gs_tty_driver, port_num, NULL);
1313 if (IS_ERR(tty_dev)) {
1314 pr_err("%s: failed to register tty for port %d, err %ld\n",
1315 __func__, port_num, PTR_ERR(tty_dev));
1317 ret = PTR_ERR(tty_dev);
1318 mutex_lock(&ports[port_num].lock);
1319 ports[port_num].port = NULL;
1320 mutex_unlock(&ports[port_num].lock);
1321 gserial_free_port(port);
1324 *line_num = port_num;
1328 EXPORT_SYMBOL_GPL(gserial_alloc_line_no_console);
1330 int gserial_alloc_line(unsigned char *line_num)
1332 int ret = gserial_alloc_line_no_console(line_num);
1334 if (!ret && !*line_num)
1335 gs_console_init(ports[*line_num].port);
1339 EXPORT_SYMBOL_GPL(gserial_alloc_line);
1342 * gserial_connect - notify TTY I/O glue that USB link is active
1343 * @gser: the function, set up with endpoints and descriptors
1344 * @port_num: which port is active
1345 * Context: any (usually from irq)
1347 * This is called activate endpoints and let the TTY layer know that
1348 * the connection is active ... not unlike "carrier detect". It won't
1349 * necessarily start I/O queues; unless the TTY is held open by any
1350 * task, there would be no point. However, the endpoints will be
1351 * activated so the USB host can perform I/O, subject to basic USB
1352 * hardware flow control.
1354 * Caller needs to have set up the endpoints and USB function in @dev
1355 * before calling this, as well as the appropriate (speed-specific)
1356 * endpoint descriptors, and also have allocate @port_num by calling
1357 * @gserial_alloc_line().
1359 * Returns negative errno or zero.
1360 * On success, ep->driver_data will be overwritten.
1362 int gserial_connect(struct gserial *gser, u8 port_num)
1364 struct gs_port *port;
1365 unsigned long flags;
1368 if (port_num >= MAX_U_SERIAL_PORTS)
1371 port = ports[port_num].port;
1373 pr_err("serial line %d not allocated.\n", port_num);
1376 if (port->port_usb) {
1377 pr_err("serial line %d is in use.\n", port_num);
1381 /* activate the endpoints */
1382 status = usb_ep_enable(gser->in);
1385 gser->in->driver_data = port;
1387 status = usb_ep_enable(gser->out);
1390 gser->out->driver_data = port;
1392 /* then tell the tty glue that I/O can work */
1393 spin_lock_irqsave(&port->port_lock, flags);
1394 gser->ioport = port;
1395 port->port_usb = gser;
1397 /* REVISIT unclear how best to handle this state...
1398 * we don't really couple it with the Linux TTY.
1400 gser->port_line_coding = port->port_line_coding;
1402 /* REVISIT if waiting on "carrier detect", signal. */
1404 /* if it's already open, start I/O ... and notify the serial
1405 * protocol about open/close status (connect/disconnect).
1407 if (port->port.count) {
1408 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1411 gser->connect(gser);
1413 if (gser->disconnect)
1414 gser->disconnect(gser);
1417 status = gs_console_connect(port);
1418 spin_unlock_irqrestore(&port->port_lock, flags);
1423 usb_ep_disable(gser->in);
1426 EXPORT_SYMBOL_GPL(gserial_connect);
1428 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1429 * @gser: the function, on which gserial_connect() was called
1430 * Context: any (usually from irq)
1432 * This is called to deactivate endpoints and let the TTY layer know
1433 * that the connection went inactive ... not unlike "hangup".
1435 * On return, the state is as if gserial_connect() had never been called;
1436 * there is no active USB I/O on these endpoints.
1438 void gserial_disconnect(struct gserial *gser)
1440 struct gs_port *port = gser->ioport;
1441 unsigned long flags;
1446 spin_lock_irqsave(&serial_port_lock, flags);
1448 /* tell the TTY glue not to do I/O here any more */
1449 spin_lock(&port->port_lock);
1451 gs_console_disconnect(port);
1453 /* REVISIT as above: how best to track this? */
1454 port->port_line_coding = gser->port_line_coding;
1456 port->port_usb = NULL;
1457 gser->ioport = NULL;
1458 if (port->port.count > 0) {
1459 wake_up_interruptible(&port->drain_wait);
1461 tty_hangup(port->port.tty);
1463 port->suspended = false;
1464 spin_unlock(&port->port_lock);
1465 spin_unlock_irqrestore(&serial_port_lock, flags);
1467 /* disable endpoints, aborting down any active I/O */
1468 usb_ep_disable(gser->out);
1469 usb_ep_disable(gser->in);
1471 /* finally, free any unused/unusable I/O buffers */
1472 spin_lock_irqsave(&port->port_lock, flags);
1473 if (port->port.count == 0)
1474 kfifo_free(&port->port_write_buf);
1475 gs_free_requests(gser->out, &port->read_pool, NULL);
1476 gs_free_requests(gser->out, &port->read_queue, NULL);
1477 gs_free_requests(gser->in, &port->write_pool, NULL);
1479 port->read_allocated = port->read_started =
1480 port->write_allocated = port->write_started = 0;
1482 spin_unlock_irqrestore(&port->port_lock, flags);
1484 EXPORT_SYMBOL_GPL(gserial_disconnect);
1486 void gserial_suspend(struct gserial *gser)
1488 struct gs_port *port;
1489 unsigned long flags;
1491 spin_lock_irqsave(&serial_port_lock, flags);
1492 port = gser->ioport;
1495 spin_unlock_irqrestore(&serial_port_lock, flags);
1499 if (port->write_busy || port->write_started) {
1500 /* Wakeup to host if there are ongoing transfers */
1501 spin_unlock_irqrestore(&serial_port_lock, flags);
1502 if (!gserial_wakeup_host(gser))
1505 /* Check if port is valid after acquiring lock back */
1506 spin_lock_irqsave(&serial_port_lock, flags);
1508 spin_unlock_irqrestore(&serial_port_lock, flags);
1513 spin_lock(&port->port_lock);
1514 spin_unlock(&serial_port_lock);
1515 port->suspended = true;
1516 port->start_delayed = true;
1517 spin_unlock_irqrestore(&port->port_lock, flags);
1519 EXPORT_SYMBOL_GPL(gserial_suspend);
1521 void gserial_resume(struct gserial *gser)
1523 struct gs_port *port;
1524 unsigned long flags;
1526 spin_lock_irqsave(&serial_port_lock, flags);
1527 port = gser->ioport;
1530 spin_unlock_irqrestore(&serial_port_lock, flags);
1534 spin_lock(&port->port_lock);
1535 spin_unlock(&serial_port_lock);
1536 port->suspended = false;
1537 if (!port->start_delayed) {
1538 spin_unlock_irqrestore(&port->port_lock, flags);
1542 pr_debug("delayed start ttyGS%d\n", port->port_num);
1545 gser->connect(gser);
1546 port->start_delayed = false;
1547 spin_unlock_irqrestore(&port->port_lock, flags);
1549 EXPORT_SYMBOL_GPL(gserial_resume);
1551 static int __init userial_init(void)
1553 struct tty_driver *driver;
1557 driver = tty_alloc_driver(MAX_U_SERIAL_PORTS, TTY_DRIVER_REAL_RAW |
1558 TTY_DRIVER_DYNAMIC_DEV);
1560 return PTR_ERR(driver);
1562 driver->driver_name = "g_serial";
1563 driver->name = "ttyGS";
1564 /* uses dynamically assigned dev_t values */
1566 driver->type = TTY_DRIVER_TYPE_SERIAL;
1567 driver->subtype = SERIAL_TYPE_NORMAL;
1568 driver->init_termios = tty_std_termios;
1570 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1571 * MS-Windows. Otherwise, most of these flags shouldn't affect
1572 * anything unless we were to actually hook up to a serial line.
1574 driver->init_termios.c_cflag =
1575 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1576 driver->init_termios.c_ispeed = 9600;
1577 driver->init_termios.c_ospeed = 9600;
1579 tty_set_operations(driver, &gs_tty_ops);
1580 for (i = 0; i < MAX_U_SERIAL_PORTS; i++)
1581 mutex_init(&ports[i].lock);
1583 /* export the driver ... */
1584 status = tty_register_driver(driver);
1586 pr_err("%s: cannot register, err %d\n",
1591 gs_tty_driver = driver;
1593 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1595 str_plural(MAX_U_SERIAL_PORTS));
1599 tty_driver_kref_put(driver);
1602 module_init(userial_init);
1604 static void __exit userial_cleanup(void)
1606 tty_unregister_driver(gs_tty_driver);
1607 tty_driver_kref_put(gs_tty_driver);
1608 gs_tty_driver = NULL;
1610 module_exit(userial_cleanup);
1612 MODULE_DESCRIPTION("utilities for USB gadget \"serial port\"/TTY support");
1613 MODULE_LICENSE("GPL");