usb gadget: split out serial core
[linux-2.6/libata-dev.git] / drivers / usb / gadget / u_serial.c
blob88d4f5452c49baaf42ed6e342139b2977dbc1cea
1 /*
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>
27 #include "u_serial.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
46 * of this component.
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.
56 * gserial is the lifecycle interface, used by USB functions
57 * gs_port is the I/O nexus, used by the tty driver
58 * tty_struct links to the tty/filesystem framework
60 * gserial <---> gs_port ... links will be null when the USB link is
61 * inactive; managed by gserial_{connect,disconnect}().
62 * gserial->ioport == usb_ep->driver_data ... gs_port
63 * gs_port->port_usb ... gserial
65 * gs_port <---> tty_struct ... links will be null when the TTY file
66 * isn't opened; managed by gs_open()/gs_close()
67 * gserial->port_tty ... tty_struct
68 * tty_struct->driver_data ... gserial
71 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
72 * next layer of buffering. For TX that's a circular buffer; for RX
73 * consider it a NOP. A third layer is provided by the TTY code.
75 #define QUEUE_SIZE 16
76 #define WRITE_BUF_SIZE 8192 /* TX only */
78 /* circular buffer */
79 struct gs_buf {
80 unsigned buf_size;
81 char *buf_buf;
82 char *buf_get;
83 char *buf_put;
87 * The port structure holds info for each port, one for each minor number
88 * (and thus for each /dev/ node).
90 struct gs_port {
91 spinlock_t port_lock; /* guard port_* access */
93 struct gserial *port_usb;
94 struct tty_struct *port_tty;
96 unsigned open_count;
97 bool openclose; /* open/close in progress */
98 u8 port_num;
100 wait_queue_head_t close_wait; /* wait for last close */
102 struct list_head read_pool;
103 struct tasklet_struct push;
105 struct list_head write_pool;
106 struct gs_buf port_write_buf;
107 wait_queue_head_t drain_wait; /* wait while writes drain */
109 /* REVISIT this state ... */
110 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
113 /* increase N_PORTS if you need more */
114 #define N_PORTS 4
115 static struct portmaster {
116 struct mutex lock; /* protect open/close */
117 struct gs_port *port;
118 } ports[N_PORTS];
119 static unsigned n_ports;
121 #define GS_CLOSE_TIMEOUT 15 /* seconds */
125 #ifdef VERBOSE_DEBUG
126 #define pr_vdebug(fmt, arg...) \
127 pr_debug(fmt, ##arg)
128 #else
129 #define pr_vdebug(fmt, arg...) \
130 ({ if (0) pr_debug(fmt, ##arg); })
131 #endif
133 /*-------------------------------------------------------------------------*/
135 /* Circular Buffer */
138 * gs_buf_alloc
140 * Allocate a circular buffer and all associated memory.
142 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
144 gb->buf_buf = kmalloc(size, GFP_KERNEL);
145 if (gb->buf_buf == NULL)
146 return -ENOMEM;
148 gb->buf_size = size;
149 gb->buf_put = gb->buf_buf;
150 gb->buf_get = gb->buf_buf;
152 return 0;
156 * gs_buf_free
158 * Free the buffer and all associated memory.
160 static void gs_buf_free(struct gs_buf *gb)
162 kfree(gb->buf_buf);
163 gb->buf_buf = NULL;
167 * gs_buf_clear
169 * Clear out all data in the circular buffer.
171 static void gs_buf_clear(struct gs_buf *gb)
173 gb->buf_get = gb->buf_put;
174 /* equivalent to a get of all data available */
178 * gs_buf_data_avail
180 * Return the number of bytes of data available in the circular
181 * buffer.
183 static unsigned gs_buf_data_avail(struct gs_buf *gb)
185 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
189 * gs_buf_space_avail
191 * Return the number of bytes of space available in the circular
192 * buffer.
194 static unsigned gs_buf_space_avail(struct gs_buf *gb)
196 return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
200 * gs_buf_put
202 * Copy data data from a user buffer and put it into the circular buffer.
203 * Restrict to the amount of space available.
205 * Return the number of bytes copied.
207 static unsigned
208 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
210 unsigned len;
212 len = gs_buf_space_avail(gb);
213 if (count > len)
214 count = len;
216 if (count == 0)
217 return 0;
219 len = gb->buf_buf + gb->buf_size - gb->buf_put;
220 if (count > len) {
221 memcpy(gb->buf_put, buf, len);
222 memcpy(gb->buf_buf, buf+len, count - len);
223 gb->buf_put = gb->buf_buf + count - len;
224 } else {
225 memcpy(gb->buf_put, buf, count);
226 if (count < len)
227 gb->buf_put += count;
228 else /* count == len */
229 gb->buf_put = gb->buf_buf;
232 return count;
236 * gs_buf_get
238 * Get data from the circular buffer and copy to the given buffer.
239 * Restrict to the amount of data available.
241 * Return the number of bytes copied.
243 static unsigned
244 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
246 unsigned len;
248 len = gs_buf_data_avail(gb);
249 if (count > len)
250 count = len;
252 if (count == 0)
253 return 0;
255 len = gb->buf_buf + gb->buf_size - gb->buf_get;
256 if (count > len) {
257 memcpy(buf, gb->buf_get, len);
258 memcpy(buf+len, gb->buf_buf, count - len);
259 gb->buf_get = gb->buf_buf + count - len;
260 } else {
261 memcpy(buf, gb->buf_get, count);
262 if (count < len)
263 gb->buf_get += count;
264 else /* count == len */
265 gb->buf_get = gb->buf_buf;
268 return count;
271 /*-------------------------------------------------------------------------*/
273 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
276 * gs_alloc_req
278 * Allocate a usb_request and its buffer. Returns a pointer to the
279 * usb_request or NULL if there is an error.
281 static struct usb_request *
282 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
284 struct usb_request *req;
286 req = usb_ep_alloc_request(ep, kmalloc_flags);
288 if (req != NULL) {
289 req->length = len;
290 req->buf = kmalloc(len, kmalloc_flags);
291 if (req->buf == NULL) {
292 usb_ep_free_request(ep, req);
293 return NULL;
297 return req;
301 * gs_free_req
303 * Free a usb_request and its buffer.
305 static void gs_free_req(struct usb_ep *ep, struct usb_request *req)
307 kfree(req->buf);
308 usb_ep_free_request(ep, req);
312 * gs_send_packet
314 * If there is data to send, a packet is built in the given
315 * buffer and the size is returned. If there is no data to
316 * send, 0 is returned.
318 * Called with port_lock held.
320 static unsigned
321 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
323 unsigned len;
325 len = gs_buf_data_avail(&port->port_write_buf);
326 if (len < size)
327 size = len;
328 if (size != 0)
329 size = gs_buf_get(&port->port_write_buf, packet, size);
330 return size;
334 * gs_start_tx
336 * This function finds available write requests, calls
337 * gs_send_packet to fill these packets with data, and
338 * continues until either there are no more write requests
339 * available or no more data to send. This function is
340 * run whenever data arrives or write requests are available.
342 * Context: caller owns port_lock; port_usb is non-null.
344 static int gs_start_tx(struct gs_port *port)
346 __releases(&port->port_lock)
347 __acquires(&port->port_lock)
350 struct list_head *pool = &port->write_pool;
351 struct usb_ep *in = port->port_usb->in;
352 int status = 0;
353 bool do_tty_wake = false;
355 while (!list_empty(pool)) {
356 struct usb_request *req;
357 int len;
359 req = list_entry(pool->next, struct usb_request, list);
360 len = gs_send_packet(port, req->buf, in->maxpacket);
361 if (len == 0) {
362 wake_up_interruptible(&port->drain_wait);
363 break;
365 do_tty_wake = true;
367 req->length = len;
368 list_del(&req->list);
370 #ifdef VERBOSE_DEBUG
371 pr_debug("%s: %s, len=%d, 0x%02x 0x%02x 0x%02x ...\n",
372 __func__, in->name, len, *((u8 *)req->buf),
373 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
374 #endif
376 /* Drop lock while we call out of driver; completions
377 * could be issued while we do so. Disconnection may
378 * happen too; maybe immediately before we queue this!
380 * NOTE that we may keep sending data for a while after
381 * the TTY closed (dev->ioport->port_tty is NULL).
383 spin_unlock(&port->port_lock);
384 status = usb_ep_queue(in, req, GFP_ATOMIC);
385 spin_lock(&port->port_lock);
387 if (status) {
388 pr_debug("%s: %s %s err %d\n",
389 __func__, "queue", in->name, status);
390 list_add(&req->list, pool);
391 break;
394 /* abort immediately after disconnect */
395 if (!port->port_usb)
396 break;
399 if (do_tty_wake && port->port_tty)
400 tty_wakeup(port->port_tty);
401 return status;
404 static void gs_rx_push(unsigned long _port)
406 struct gs_port *port = (void *)_port;
407 struct tty_struct *tty = port->port_tty;
409 /* With low_latency, tty_flip_buffer_push() doesn't put its
410 * real work through a workqueue, so the ldisc has a better
411 * chance to keep up with peak USB data rates.
413 if (tty) {
414 tty_flip_buffer_push(tty);
415 wake_up_interruptible(&tty->read_wait);
420 * gs_recv_packet
422 * Called for each USB packet received. Reads the packet
423 * header and stuffs the data in the appropriate tty buffer.
424 * Returns 0 if successful, or a negative error number.
426 * Called during USB completion routine, on interrupt time.
427 * With port_lock.
429 static int gs_recv_packet(struct gs_port *port, char *packet, unsigned size)
431 unsigned len;
432 struct tty_struct *tty;
434 /* I/O completions can continue for a while after close(), until the
435 * request queue empties. Just discard any data we receive, until
436 * something reopens this TTY ... as if there were no HW flow control.
438 tty = port->port_tty;
439 if (tty == NULL) {
440 pr_vdebug("%s: ttyGS%d, after close\n",
441 __func__, port->port_num);
442 return -EIO;
445 len = tty_insert_flip_string(tty, packet, size);
446 if (len > 0)
447 tasklet_schedule(&port->push);
448 if (len < size)
449 pr_debug("%s: ttyGS%d, drop %d bytes\n",
450 __func__, port->port_num, size - len);
451 return 0;
455 * Context: caller owns port_lock, and port_usb is set
457 static unsigned gs_start_rx(struct gs_port *port)
459 __releases(&port->port_lock)
460 __acquires(&port->port_lock)
463 struct list_head *pool = &port->read_pool;
464 struct usb_ep *out = port->port_usb->out;
465 unsigned started = 0;
467 while (!list_empty(pool)) {
468 struct usb_request *req;
469 int status;
470 struct tty_struct *tty;
472 /* no more rx if closed or throttled */
473 tty = port->port_tty;
474 if (!tty || test_bit(TTY_THROTTLED, &tty->flags))
475 break;
477 req = list_entry(pool->next, struct usb_request, list);
478 list_del(&req->list);
479 req->length = out->maxpacket;
481 /* drop lock while we call out; the controller driver
482 * may need to call us back (e.g. for disconnect)
484 spin_unlock(&port->port_lock);
485 status = usb_ep_queue(out, req, GFP_ATOMIC);
486 spin_lock(&port->port_lock);
488 if (status) {
489 pr_debug("%s: %s %s err %d\n",
490 __func__, "queue", out->name, status);
491 list_add(&req->list, pool);
492 break;
494 started++;
496 /* abort immediately after disconnect */
497 if (!port->port_usb)
498 break;
500 return started;
503 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
505 int status;
506 struct gs_port *port = ep->driver_data;
508 spin_lock(&port->port_lock);
509 list_add(&req->list, &port->read_pool);
511 switch (req->status) {
512 case 0:
513 /* normal completion */
514 status = gs_recv_packet(port, req->buf, req->actual);
515 if (status && status != -EIO)
516 pr_debug("%s: %s %s err %d\n",
517 __func__, "recv", ep->name, status);
518 gs_start_rx(port);
519 break;
521 case -ESHUTDOWN:
522 /* disconnect */
523 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
524 break;
526 default:
527 /* presumably a transient fault */
528 pr_warning("%s: unexpected %s status %d\n",
529 __func__, ep->name, req->status);
530 gs_start_rx(port);
531 break;
533 spin_unlock(&port->port_lock);
536 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
538 struct gs_port *port = ep->driver_data;
540 spin_lock(&port->port_lock);
541 list_add(&req->list, &port->write_pool);
543 switch (req->status) {
544 default:
545 /* presumably a transient fault */
546 pr_warning("%s: unexpected %s status %d\n",
547 __func__, ep->name, req->status);
548 /* FALL THROUGH */
549 case 0:
550 /* normal completion */
551 gs_start_tx(port);
552 break;
554 case -ESHUTDOWN:
555 /* disconnect */
556 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
557 break;
560 spin_unlock(&port->port_lock);
563 static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
565 struct usb_request *req;
567 while (!list_empty(head)) {
568 req = list_entry(head->next, struct usb_request, list);
569 list_del(&req->list);
570 gs_free_req(ep, req);
574 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
575 void (*fn)(struct usb_ep *, struct usb_request *))
577 int i;
578 struct usb_request *req;
580 /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
581 * do quite that many this time, don't fail ... we just won't
582 * be as speedy as we might otherwise be.
584 for (i = 0; i < QUEUE_SIZE; i++) {
585 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
586 if (!req)
587 return list_empty(head) ? -ENOMEM : 0;
588 req->complete = fn;
589 list_add_tail(&req->list, head);
591 return 0;
595 * gs_start_io - start USB I/O streams
596 * @dev: encapsulates endpoints to use
597 * Context: holding port_lock; port_tty and port_usb are non-null
599 * We only start I/O when something is connected to both sides of
600 * this port. If nothing is listening on the host side, we may
601 * be pointlessly filling up our TX buffers and FIFO.
603 static int gs_start_io(struct gs_port *port)
605 struct list_head *head = &port->read_pool;
606 struct usb_ep *ep = port->port_usb->out;
607 int status;
608 unsigned started;
610 /* Allocate RX and TX I/O buffers. We can't easily do this much
611 * earlier (with GFP_KERNEL) because the requests are coupled to
612 * endpoints, as are the packet sizes we'll be using. Different
613 * configurations may use different endpoints with a given port;
614 * and high speed vs full speed changes packet sizes too.
616 status = gs_alloc_requests(ep, head, gs_read_complete);
617 if (status)
618 return status;
620 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
621 gs_write_complete);
622 if (status) {
623 gs_free_requests(ep, head);
624 return status;
627 /* queue read requests */
628 started = gs_start_rx(port);
630 /* unblock any pending writes into our circular buffer */
631 if (started) {
632 tty_wakeup(port->port_tty);
633 } else {
634 gs_free_requests(ep, head);
635 gs_free_requests(port->port_usb->in, &port->write_pool);
638 return started ? 0 : status;
641 /*-------------------------------------------------------------------------*/
643 /* TTY Driver */
646 * gs_open sets up the link between a gs_port and its associated TTY.
647 * That link is broken *only* by TTY close(), and all driver methods
648 * know that.
650 static int gs_open(struct tty_struct *tty, struct file *file)
652 int port_num = tty->index;
653 struct gs_port *port;
654 int status;
656 if (port_num < 0 || port_num >= n_ports)
657 return -ENXIO;
659 do {
660 mutex_lock(&ports[port_num].lock);
661 port = ports[port_num].port;
662 if (!port)
663 status = -ENODEV;
664 else {
665 spin_lock_irq(&port->port_lock);
667 /* already open? Great. */
668 if (port->open_count) {
669 status = 0;
670 port->open_count++;
672 /* currently opening/closing? wait ... */
673 } else if (port->openclose) {
674 status = -EBUSY;
676 /* ... else we do the work */
677 } else {
678 status = -EAGAIN;
679 port->openclose = true;
681 spin_unlock_irq(&port->port_lock);
683 mutex_unlock(&ports[port_num].lock);
685 switch (status) {
686 default:
687 /* fully handled */
688 return status;
689 case -EAGAIN:
690 /* must do the work */
691 break;
692 case -EBUSY:
693 /* wait for EAGAIN task to finish */
694 msleep(1);
695 /* REVISIT could have a waitchannel here, if
696 * concurrent open performance is important
698 break;
700 } while (status != -EAGAIN);
702 /* Do the "real open" */
703 spin_lock_irq(&port->port_lock);
705 /* allocate circular buffer on first open */
706 if (port->port_write_buf.buf_buf == NULL) {
708 spin_unlock_irq(&port->port_lock);
709 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
710 spin_lock_irq(&port->port_lock);
712 if (status) {
713 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
714 port->port_num, tty, file);
715 port->openclose = false;
716 goto exit_unlock_port;
720 /* REVISIT if REMOVED (ports[].port NULL), abort the open
721 * to let rmmod work faster (but this way isn't wrong).
724 /* REVISIT maybe wait for "carrier detect" */
726 tty->driver_data = port;
727 port->port_tty = tty;
729 port->open_count = 1;
730 port->openclose = false;
732 /* low_latency means ldiscs work in tasklet context, without
733 * needing a workqueue schedule ... easier to keep up.
735 tty->low_latency = 1;
737 /* if connected, start the I/O stream */
738 if (port->port_usb) {
739 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
740 gs_start_io(port);
742 /* REVISIT for ACM, issue "network connected" event */
745 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
747 status = 0;
749 exit_unlock_port:
750 spin_unlock_irq(&port->port_lock);
751 return status;
754 static int gs_writes_finished(struct gs_port *p)
756 int cond;
758 /* return true on disconnect or empty buffer */
759 spin_lock_irq(&p->port_lock);
760 cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
761 spin_unlock_irq(&p->port_lock);
763 return cond;
766 static void gs_close(struct tty_struct *tty, struct file *file)
768 struct gs_port *port = tty->driver_data;
770 spin_lock_irq(&port->port_lock);
772 if (port->open_count != 1) {
773 if (port->open_count == 0)
774 WARN_ON(1);
775 else
776 --port->open_count;
777 goto exit;
780 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
782 /* mark port as closing but in use; we can drop port lock
783 * and sleep if necessary
785 port->openclose = true;
786 port->open_count = 0;
788 if (port->port_usb)
789 /* REVISIT for ACM, issue "network disconnected" event */;
791 /* wait for circular write buffer to drain, disconnect, or at
792 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
794 if (gs_buf_data_avail(&port->port_write_buf) > 0
795 && port->port_usb) {
796 spin_unlock_irq(&port->port_lock);
797 wait_event_interruptible_timeout(port->drain_wait,
798 gs_writes_finished(port),
799 GS_CLOSE_TIMEOUT * HZ);
800 spin_lock_irq(&port->port_lock);
803 /* Iff we're disconnected, there can be no I/O in flight so it's
804 * ok to free the circular buffer; else just scrub it. And don't
805 * let the push tasklet fire again until we're re-opened.
807 if (port->port_usb == NULL)
808 gs_buf_free(&port->port_write_buf);
809 else
810 gs_buf_clear(&port->port_write_buf);
812 tasklet_kill(&port->push);
814 tty->driver_data = NULL;
815 port->port_tty = NULL;
817 port->openclose = false;
819 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
820 port->port_num, tty, file);
822 wake_up_interruptible(&port->close_wait);
823 exit:
824 spin_unlock_irq(&port->port_lock);
827 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
829 struct gs_port *port = tty->driver_data;
830 unsigned long flags;
831 int status;
833 pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
834 port->port_num, tty, count);
836 spin_lock_irqsave(&port->port_lock, flags);
837 if (count)
838 count = gs_buf_put(&port->port_write_buf, buf, count);
839 /* treat count == 0 as flush_chars() */
840 if (port->port_usb)
841 status = gs_start_tx(port);
842 spin_unlock_irqrestore(&port->port_lock, flags);
844 return count;
847 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
849 struct gs_port *port = tty->driver_data;
850 unsigned long flags;
851 int status;
853 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
854 port->port_num, tty, ch, __builtin_return_address(0));
856 spin_lock_irqsave(&port->port_lock, flags);
857 status = gs_buf_put(&port->port_write_buf, &ch, 1);
858 spin_unlock_irqrestore(&port->port_lock, flags);
860 return status;
863 static void gs_flush_chars(struct tty_struct *tty)
865 struct gs_port *port = tty->driver_data;
866 unsigned long flags;
868 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
870 spin_lock_irqsave(&port->port_lock, flags);
871 if (port->port_usb)
872 gs_start_tx(port);
873 spin_unlock_irqrestore(&port->port_lock, flags);
876 static int gs_write_room(struct tty_struct *tty)
878 struct gs_port *port = tty->driver_data;
879 unsigned long flags;
880 int room = 0;
882 spin_lock_irqsave(&port->port_lock, flags);
883 if (port->port_usb)
884 room = gs_buf_space_avail(&port->port_write_buf);
885 spin_unlock_irqrestore(&port->port_lock, flags);
887 pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
888 port->port_num, tty, room);
890 return room;
893 static int gs_chars_in_buffer(struct tty_struct *tty)
895 struct gs_port *port = tty->driver_data;
896 unsigned long flags;
897 int chars = 0;
899 spin_lock_irqsave(&port->port_lock, flags);
900 chars = gs_buf_data_avail(&port->port_write_buf);
901 spin_unlock_irqrestore(&port->port_lock, flags);
903 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
904 port->port_num, tty, chars);
906 return chars;
909 /* undo side effects of setting TTY_THROTTLED */
910 static void gs_unthrottle(struct tty_struct *tty)
912 struct gs_port *port = tty->driver_data;
913 unsigned long flags;
914 unsigned started = 0;
916 spin_lock_irqsave(&port->port_lock, flags);
917 if (port->port_usb)
918 started = gs_start_rx(port);
919 spin_unlock_irqrestore(&port->port_lock, flags);
921 pr_vdebug("gs_unthrottle: ttyGS%d, %d packets\n",
922 port->port_num, started);
925 static const struct tty_operations gs_tty_ops = {
926 .open = gs_open,
927 .close = gs_close,
928 .write = gs_write,
929 .put_char = gs_put_char,
930 .flush_chars = gs_flush_chars,
931 .write_room = gs_write_room,
932 .chars_in_buffer = gs_chars_in_buffer,
933 .unthrottle = gs_unthrottle,
936 /*-------------------------------------------------------------------------*/
938 static struct tty_driver *gs_tty_driver;
940 static int __init
941 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
943 struct gs_port *port;
945 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
946 if (port == NULL)
947 return -ENOMEM;
949 spin_lock_init(&port->port_lock);
950 init_waitqueue_head(&port->close_wait);
951 init_waitqueue_head(&port->drain_wait);
953 tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
955 INIT_LIST_HEAD(&port->read_pool);
956 INIT_LIST_HEAD(&port->write_pool);
958 port->port_num = port_num;
959 port->port_line_coding = *coding;
961 ports[port_num].port = port;
963 return 0;
967 * gserial_setup - initialize TTY driver for one or more ports
968 * @g: gadget to associate with these ports
969 * @count: how many ports to support
970 * Context: may sleep
972 * The TTY stack needs to know in advance how many devices it should
973 * plan to manage. Use this call to set up the ports you will be
974 * exporting through USB. Later, connect them to functions based
975 * on what configuration is activated by the USB host; and disconnect
976 * them as appropriate.
978 * An example would be a two-configuration device in which both
979 * configurations expose port 0, but through different functions.
980 * One configuration could even expose port 1 while the other
981 * one doesn't.
983 * Returns negative errno or zero.
985 int __init gserial_setup(struct usb_gadget *g, unsigned count)
987 unsigned i;
988 struct usb_cdc_line_coding coding;
989 int status;
991 if (count == 0 || count > N_PORTS)
992 return -EINVAL;
994 gs_tty_driver = alloc_tty_driver(count);
995 if (!gs_tty_driver)
996 return -ENOMEM;
998 gs_tty_driver->owner = THIS_MODULE;
999 gs_tty_driver->driver_name = "g_serial";
1000 gs_tty_driver->name = "ttyGS";
1001 /* uses dynamically assigned dev_t values */
1003 gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1004 gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1005 gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1006 gs_tty_driver->init_termios = tty_std_termios;
1008 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1009 * MS-Windows. Otherwise, most of these flags shouldn't affect
1010 * anything unless we were to actually hook up to a serial line.
1012 gs_tty_driver->init_termios.c_cflag =
1013 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1014 gs_tty_driver->init_termios.c_ispeed = 9600;
1015 gs_tty_driver->init_termios.c_ospeed = 9600;
1017 coding.dwDTERate = __constant_cpu_to_le32(9600);
1018 coding.bCharFormat = 8;
1019 coding.bParityType = USB_CDC_NO_PARITY;
1020 coding.bDataBits = USB_CDC_1_STOP_BITS;
1022 tty_set_operations(gs_tty_driver, &gs_tty_ops);
1024 /* make devices be openable */
1025 for (i = 0; i < count; i++) {
1026 mutex_init(&ports[i].lock);
1027 status = gs_port_alloc(i, &coding);
1028 if (status) {
1029 count = i;
1030 goto fail;
1033 n_ports = count;
1035 /* export the driver ... */
1036 status = tty_register_driver(gs_tty_driver);
1037 if (status) {
1038 put_tty_driver(gs_tty_driver);
1039 pr_err("%s: cannot register, err %d\n",
1040 __func__, status);
1041 goto fail;
1044 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1045 for (i = 0; i < count; i++) {
1046 struct device *tty_dev;
1048 tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
1049 if (IS_ERR(tty_dev))
1050 pr_warning("%s: no classdev for port %d, err %ld\n",
1051 __func__, i, PTR_ERR(tty_dev));
1054 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1055 count, (count == 1) ? "" : "s");
1057 return status;
1058 fail:
1059 while (count--)
1060 kfree(ports[count].port);
1061 put_tty_driver(gs_tty_driver);
1062 gs_tty_driver = NULL;
1063 return status;
1066 static int gs_closed(struct gs_port *port)
1068 int cond;
1070 spin_lock_irq(&port->port_lock);
1071 cond = (port->open_count == 0) && !port->openclose;
1072 spin_unlock_irq(&port->port_lock);
1073 return cond;
1077 * gserial_cleanup - remove TTY-over-USB driver and devices
1078 * Context: may sleep
1080 * This is called to free all resources allocated by @gserial_setup().
1081 * Accordingly, it may need to wait until some open /dev/ files have
1082 * closed.
1084 * The caller must have issued @gserial_disconnect() for any ports
1085 * that had previously been connected, so that there is never any
1086 * I/O pending when it's called.
1088 void gserial_cleanup(void)
1090 unsigned i;
1091 struct gs_port *port;
1093 /* start sysfs and /dev/ttyGS* node removal */
1094 for (i = 0; i < n_ports; i++)
1095 tty_unregister_device(gs_tty_driver, i);
1097 for (i = 0; i < n_ports; i++) {
1098 /* prevent new opens */
1099 mutex_lock(&ports[i].lock);
1100 port = ports[i].port;
1101 ports[i].port = NULL;
1102 mutex_unlock(&ports[i].lock);
1104 /* wait for old opens to finish */
1105 wait_event(port->close_wait, gs_closed(port));
1107 WARN_ON(port->port_usb != NULL);
1109 kfree(port);
1111 n_ports = 0;
1113 tty_unregister_driver(gs_tty_driver);
1114 gs_tty_driver = NULL;
1116 pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1120 * gserial_connect - notify TTY I/O glue that USB link is active
1121 * @gser: the function, set up with endpoints and descriptors
1122 * @port_num: which port is active
1123 * Context: any (usually from irq)
1125 * This is called activate endpoints and let the TTY layer know that
1126 * the connection is active ... not unlike "carrier detect". It won't
1127 * necessarily start I/O queues; unless the TTY is held open by any
1128 * task, there would be no point. However, the endpoints will be
1129 * activated so the USB host can perform I/O, subject to basic USB
1130 * hardware flow control.
1132 * Caller needs to have set up the endpoints and USB function in @dev
1133 * before calling this, as well as the appropriate (speed-specific)
1134 * endpoint descriptors, and also have set up the TTY driver by calling
1135 * @gserial_setup().
1137 * Returns negative errno or zero.
1138 * On success, ep->driver_data will be overwritten.
1140 int gserial_connect(struct gserial *gser, u8 port_num)
1142 struct gs_port *port;
1143 unsigned long flags;
1144 int status;
1146 if (!gs_tty_driver || port_num >= n_ports)
1147 return -ENXIO;
1149 /* we "know" gserial_cleanup() hasn't been called */
1150 port = ports[port_num].port;
1152 /* activate the endpoints */
1153 status = usb_ep_enable(gser->in, gser->in_desc);
1154 if (status < 0)
1155 return status;
1156 gser->in->driver_data = port;
1158 status = usb_ep_enable(gser->out, gser->out_desc);
1159 if (status < 0)
1160 goto fail_out;
1161 gser->out->driver_data = port;
1163 /* then tell the tty glue that I/O can work */
1164 spin_lock_irqsave(&port->port_lock, flags);
1165 gser->ioport = port;
1166 port->port_usb = gser;
1168 /* REVISIT unclear how best to handle this state...
1169 * we don't really couple it with the Linux TTY.
1171 gser->port_line_coding = port->port_line_coding;
1173 /* REVISIT if waiting on "carrier detect", signal. */
1175 /* REVISIT for ACM, issue "network connection" status notification:
1176 * connected if open_count, else disconnected.
1179 /* if it's already open, start I/O */
1180 if (port->open_count) {
1181 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1182 gs_start_io(port);
1185 spin_unlock_irqrestore(&port->port_lock, flags);
1187 return status;
1189 fail_out:
1190 usb_ep_disable(gser->in);
1191 gser->in->driver_data = NULL;
1192 return status;
1196 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1197 * @gser: the function, on which gserial_connect() was called
1198 * Context: any (usually from irq)
1200 * This is called to deactivate endpoints and let the TTY layer know
1201 * that the connection went inactive ... not unlike "hangup".
1203 * On return, the state is as if gserial_connect() had never been called;
1204 * there is no active USB I/O on these endpoints.
1206 void gserial_disconnect(struct gserial *gser)
1208 struct gs_port *port = gser->ioport;
1209 unsigned long flags;
1211 if (!port)
1212 return;
1214 /* tell the TTY glue not to do I/O here any more */
1215 spin_lock_irqsave(&port->port_lock, flags);
1217 /* REVISIT as above: how best to track this? */
1218 port->port_line_coding = gser->port_line_coding;
1220 port->port_usb = NULL;
1221 gser->ioport = NULL;
1222 if (port->open_count > 0 || port->openclose) {
1223 wake_up_interruptible(&port->drain_wait);
1224 if (port->port_tty)
1225 tty_hangup(port->port_tty);
1227 spin_unlock_irqrestore(&port->port_lock, flags);
1229 /* disable endpoints, aborting down any active I/O */
1230 usb_ep_disable(gser->out);
1231 gser->out->driver_data = NULL;
1233 usb_ep_disable(gser->in);
1234 gser->in->driver_data = NULL;
1236 /* finally, free any unused/unusable I/O buffers */
1237 spin_lock_irqsave(&port->port_lock, flags);
1238 if (port->open_count == 0 && !port->openclose)
1239 gs_buf_free(&port->port_write_buf);
1240 gs_free_requests(gser->out, &port->read_pool);
1241 gs_free_requests(gser->in, &port->write_pool);
1242 spin_unlock_irqrestore(&port->port_lock, flags);