GUI: Fix Tomato RAF theme for all builds. Compilation typo.
[tomato.git] / release / src-rt-6.x.4708 / linux / linux-2.6.36 / drivers / usb / gadget / u_serial.c
blob01e5354a4c20ffd5b072fdff6a828d08e9049317
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/sched.h>
22 #include <linux/interrupt.h>
23 #include <linux/device.h>
24 #include <linux/delay.h>
25 #include <linux/tty.h>
26 #include <linux/tty_flip.h>
27 #include <linux/slab.h>
29 #include "u_serial.h"
33 * This component encapsulates the TTY layer glue needed to provide basic
34 * "serial port" functionality through the USB gadget stack. Each such
35 * port is exposed through a /dev/ttyGS* node.
37 * After initialization (gserial_setup), these TTY port devices stay
38 * available until they are removed (gserial_cleanup). Each one may be
39 * connected to a USB function (gserial_connect), or disconnected (with
40 * gserial_disconnect) when the USB host issues a config change event.
41 * Data can only flow when the port is connected to the host.
43 * A given TTY port can be made available in multiple configurations.
44 * For example, each one might expose a ttyGS0 node which provides a
45 * login application. In one case that might use CDC ACM interface 0,
46 * while another configuration might use interface 3 for that. The
47 * work to handle that (including descriptor management) is not part
48 * of this component.
50 * Configurations may expose more than one TTY port. For example, if
51 * ttyGS0 provides login service, then ttyGS1 might provide dialer access
52 * for a telephone or fax link. And ttyGS2 might be something that just
53 * needs a simple byte stream interface for some messaging protocol that
54 * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
57 #define PREFIX "ttyGS"
60 * gserial is the lifecycle interface, used by USB functions
61 * gs_port is the I/O nexus, used by the tty driver
62 * tty_struct links to the tty/filesystem framework
64 * gserial <---> gs_port ... links will be null when the USB link is
65 * inactive; managed by gserial_{connect,disconnect}(). each gserial
66 * instance can wrap its own USB control protocol.
67 * gserial->ioport == usb_ep->driver_data ... gs_port
68 * gs_port->port_usb ... gserial
70 * gs_port <---> tty_struct ... links will be null when the TTY file
71 * isn't opened; managed by gs_open()/gs_close()
72 * gserial->port_tty ... tty_struct
73 * tty_struct->driver_data ... gserial
76 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
77 * next layer of buffering. For TX that's a circular buffer; for RX
78 * consider it a NOP. A third layer is provided by the TTY code.
80 #define QUEUE_SIZE 16
81 #define WRITE_BUF_SIZE 8192 /* TX only */
83 /* circular buffer */
84 struct gs_buf {
85 unsigned buf_size;
86 char *buf_buf;
87 char *buf_get;
88 char *buf_put;
92 * The port structure holds info for each port, one for each minor number
93 * (and thus for each /dev/ node).
95 struct gs_port {
96 spinlock_t port_lock; /* guard port_* access */
98 struct gserial *port_usb;
99 struct tty_struct *port_tty;
101 unsigned open_count;
102 bool openclose; /* open/close in progress */
103 u8 port_num;
105 wait_queue_head_t close_wait; /* wait for last close */
107 struct list_head read_pool;
108 struct list_head read_queue;
109 unsigned n_read;
110 struct tasklet_struct push;
112 struct list_head write_pool;
113 struct gs_buf port_write_buf;
114 wait_queue_head_t drain_wait; /* wait while writes drain */
116 /* REVISIT this state ... */
117 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
120 /* increase N_PORTS if you need more */
121 #define N_PORTS 4
122 static struct portmaster {
123 struct mutex lock; /* protect open/close */
124 struct gs_port *port;
125 } ports[N_PORTS];
126 static unsigned n_ports;
128 #define GS_CLOSE_TIMEOUT 15 /* seconds */
132 #ifdef VERBOSE_DEBUG
133 #define pr_vdebug(fmt, arg...) \
134 pr_debug(fmt, ##arg)
135 #else
136 #define pr_vdebug(fmt, arg...) \
137 ({ if (0) pr_debug(fmt, ##arg); })
138 #endif
140 /*-------------------------------------------------------------------------*/
142 /* Circular Buffer */
145 * gs_buf_alloc
147 * Allocate a circular buffer and all associated memory.
149 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
151 gb->buf_buf = kmalloc(size, GFP_KERNEL);
152 if (gb->buf_buf == NULL)
153 return -ENOMEM;
155 gb->buf_size = size;
156 gb->buf_put = gb->buf_buf;
157 gb->buf_get = gb->buf_buf;
159 return 0;
163 * gs_buf_free
165 * Free the buffer and all associated memory.
167 static void gs_buf_free(struct gs_buf *gb)
169 kfree(gb->buf_buf);
170 gb->buf_buf = NULL;
174 * gs_buf_clear
176 * Clear out all data in the circular buffer.
178 static void gs_buf_clear(struct gs_buf *gb)
180 gb->buf_get = gb->buf_put;
181 /* equivalent to a get of all data available */
185 * gs_buf_data_avail
187 * Return the number of bytes of data written into the circular
188 * buffer.
190 static unsigned gs_buf_data_avail(struct gs_buf *gb)
192 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
196 * gs_buf_space_avail
198 * Return the number of bytes of space available in the circular
199 * buffer.
201 static unsigned gs_buf_space_avail(struct gs_buf *gb)
203 return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
207 * gs_buf_put
209 * Copy data data from a user buffer and put it into the circular buffer.
210 * Restrict to the amount of space available.
212 * Return the number of bytes copied.
214 static unsigned
215 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
217 unsigned len;
219 len = gs_buf_space_avail(gb);
220 if (count > len)
221 count = len;
223 if (count == 0)
224 return 0;
226 len = gb->buf_buf + gb->buf_size - gb->buf_put;
227 if (count > len) {
228 memcpy(gb->buf_put, buf, len);
229 memcpy(gb->buf_buf, buf+len, count - len);
230 gb->buf_put = gb->buf_buf + count - len;
231 } else {
232 memcpy(gb->buf_put, buf, count);
233 if (count < len)
234 gb->buf_put += count;
235 else /* count == len */
236 gb->buf_put = gb->buf_buf;
239 return count;
243 * gs_buf_get
245 * Get data from the circular buffer and copy to the given buffer.
246 * Restrict to the amount of data available.
248 * Return the number of bytes copied.
250 static unsigned
251 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
253 unsigned len;
255 len = gs_buf_data_avail(gb);
256 if (count > len)
257 count = len;
259 if (count == 0)
260 return 0;
262 len = gb->buf_buf + gb->buf_size - gb->buf_get;
263 if (count > len) {
264 memcpy(buf, gb->buf_get, len);
265 memcpy(buf+len, gb->buf_buf, count - len);
266 gb->buf_get = gb->buf_buf + count - len;
267 } else {
268 memcpy(buf, gb->buf_get, count);
269 if (count < len)
270 gb->buf_get += count;
271 else /* count == len */
272 gb->buf_get = gb->buf_buf;
275 return count;
278 /*-------------------------------------------------------------------------*/
280 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
283 * gs_alloc_req
285 * Allocate a usb_request and its buffer. Returns a pointer to the
286 * usb_request or NULL if there is an error.
288 struct usb_request *
289 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
291 struct usb_request *req;
293 req = usb_ep_alloc_request(ep, kmalloc_flags);
295 if (req != NULL) {
296 req->length = len;
297 req->buf = kmalloc(len, kmalloc_flags);
298 if (req->buf == NULL) {
299 usb_ep_free_request(ep, req);
300 return NULL;
304 return req;
308 * gs_free_req
310 * Free a usb_request and its buffer.
312 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
314 kfree(req->buf);
315 usb_ep_free_request(ep, req);
319 * gs_send_packet
321 * If there is data to send, a packet is built in the given
322 * buffer and the size is returned. If there is no data to
323 * send, 0 is returned.
325 * Called with port_lock held.
327 static unsigned
328 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
330 unsigned len;
332 len = gs_buf_data_avail(&port->port_write_buf);
333 if (len < size)
334 size = len;
335 if (size != 0)
336 size = gs_buf_get(&port->port_write_buf, packet, size);
337 return size;
341 * gs_start_tx
343 * This function finds available write requests, calls
344 * gs_send_packet to fill these packets with data, and
345 * continues until either there are no more write requests
346 * available or no more data to send. This function is
347 * run whenever data arrives or write requests are available.
349 * Context: caller owns port_lock; port_usb is non-null.
351 static int gs_start_tx(struct gs_port *port)
353 __releases(&port->port_lock)
354 __acquires(&port->port_lock)
357 struct list_head *pool = &port->write_pool;
358 struct usb_ep *in = port->port_usb->in;
359 int status = 0;
360 bool do_tty_wake = false;
362 while (!list_empty(pool)) {
363 struct usb_request *req;
364 int len;
366 req = list_entry(pool->next, struct usb_request, list);
367 len = gs_send_packet(port, req->buf, in->maxpacket);
368 if (len == 0) {
369 wake_up_interruptible(&port->drain_wait);
370 break;
372 do_tty_wake = true;
374 req->length = len;
375 list_del(&req->list);
376 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
378 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
379 port->port_num, len, *((u8 *)req->buf),
380 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
382 /* Drop lock while we call out of driver; completions
383 * could be issued while we do so. Disconnection may
384 * happen too; maybe immediately before we queue this!
386 * NOTE that we may keep sending data for a while after
387 * the TTY closed (dev->ioport->port_tty is NULL).
389 spin_unlock(&port->port_lock);
390 status = usb_ep_queue(in, req, GFP_ATOMIC);
391 spin_lock(&port->port_lock);
393 if (status) {
394 pr_debug("%s: %s %s err %d\n",
395 __func__, "queue", in->name, status);
396 list_add(&req->list, pool);
397 break;
400 /* abort immediately after disconnect */
401 if (!port->port_usb)
402 break;
405 if (do_tty_wake && port->port_tty)
406 tty_wakeup(port->port_tty);
407 return status;
411 * Context: caller owns port_lock, and port_usb is set
413 static unsigned gs_start_rx(struct gs_port *port)
415 __releases(&port->port_lock)
416 __acquires(&port->port_lock)
419 struct list_head *pool = &port->read_pool;
420 struct usb_ep *out = port->port_usb->out;
421 unsigned started = 0;
423 while (!list_empty(pool)) {
424 struct usb_request *req;
425 int status;
426 struct tty_struct *tty;
428 /* no more rx if closed */
429 tty = port->port_tty;
430 if (!tty)
431 break;
433 req = list_entry(pool->next, struct usb_request, list);
434 list_del(&req->list);
435 req->length = out->maxpacket;
437 /* drop lock while we call out; the controller driver
438 * may need to call us back (e.g. for disconnect)
440 spin_unlock(&port->port_lock);
441 status = usb_ep_queue(out, req, GFP_ATOMIC);
442 spin_lock(&port->port_lock);
444 if (status) {
445 pr_debug("%s: %s %s err %d\n",
446 __func__, "queue", out->name, status);
447 list_add(&req->list, pool);
448 break;
450 started++;
452 /* abort immediately after disconnect */
453 if (!port->port_usb)
454 break;
456 return started;
460 * RX tasklet takes data out of the RX queue and hands it up to the TTY
461 * layer until it refuses to take any more data (or is throttled back).
462 * Then it issues reads for any further data.
464 * If the RX queue becomes full enough that no usb_request is queued,
465 * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
466 * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
467 * can be buffered before the TTY layer's buffers (currently 64 KB).
469 static void gs_rx_push(unsigned long _port)
471 struct gs_port *port = (void *)_port;
472 struct tty_struct *tty;
473 struct list_head *queue = &port->read_queue;
474 bool disconnect = false;
475 bool do_push = false;
477 /* hand any queued data to the tty */
478 spin_lock_irq(&port->port_lock);
479 tty = port->port_tty;
480 while (!list_empty(queue)) {
481 struct usb_request *req;
483 req = list_first_entry(queue, struct usb_request, list);
485 /* discard data if tty was closed */
486 if (!tty)
487 goto recycle;
489 /* leave data queued if tty was rx throttled */
490 if (test_bit(TTY_THROTTLED, &tty->flags))
491 break;
493 switch (req->status) {
494 case -ESHUTDOWN:
495 disconnect = true;
496 pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
497 break;
499 default:
500 /* presumably a transient fault */
501 pr_warning(PREFIX "%d: unexpected RX status %d\n",
502 port->port_num, req->status);
503 /* FALLTHROUGH */
504 case 0:
505 /* normal completion */
506 break;
509 /* push data to (open) tty */
510 if (req->actual) {
511 char *packet = req->buf;
512 unsigned size = req->actual;
513 unsigned n;
514 int count;
516 /* we may have pushed part of this packet already... */
517 n = port->n_read;
518 if (n) {
519 packet += n;
520 size -= n;
523 count = tty_insert_flip_string(tty, packet, size);
524 if (count)
525 do_push = true;
526 if (count != size) {
527 /* stop pushing; TTY layer can't handle more */
528 port->n_read += count;
529 pr_vdebug(PREFIX "%d: rx block %d/%d\n",
530 port->port_num,
531 count, req->actual);
532 break;
534 port->n_read = 0;
536 recycle:
537 list_move(&req->list, &port->read_pool);
540 /* Push from tty to ldisc; without low_latency set this is handled by
541 * a workqueue, so we won't get callbacks and can hold port_lock
543 if (tty && do_push) {
544 tty_flip_buffer_push(tty);
548 /* We want our data queue to become empty ASAP, keeping data
549 * in the tty and ldisc (not here). If we couldn't push any
550 * this time around, there may be trouble unless there's an
551 * implicit tty_unthrottle() call on its way...
553 * REVISIT we should probably add a timer to keep the tasklet
554 * from starving ... but it's not clear that case ever happens.
556 if (!list_empty(queue) && tty) {
557 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
558 if (do_push)
559 tasklet_schedule(&port->push);
560 else
561 pr_warning(PREFIX "%d: RX not scheduled?\n",
562 port->port_num);
566 /* If we're still connected, refill the USB RX queue. */
567 if (!disconnect && port->port_usb)
568 gs_start_rx(port);
570 spin_unlock_irq(&port->port_lock);
573 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
575 struct gs_port *port = ep->driver_data;
577 /* Queue all received data until the tty layer is ready for it. */
578 spin_lock(&port->port_lock);
579 list_add_tail(&req->list, &port->read_queue);
580 tasklet_schedule(&port->push);
581 spin_unlock(&port->port_lock);
584 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
586 struct gs_port *port = ep->driver_data;
588 spin_lock(&port->port_lock);
589 list_add(&req->list, &port->write_pool);
591 switch (req->status) {
592 default:
593 /* presumably a transient fault */
594 pr_warning("%s: unexpected %s status %d\n",
595 __func__, ep->name, req->status);
596 /* FALL THROUGH */
597 case 0:
598 /* normal completion */
599 gs_start_tx(port);
600 break;
602 case -ESHUTDOWN:
603 /* disconnect */
604 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
605 break;
608 spin_unlock(&port->port_lock);
611 static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
613 struct usb_request *req;
615 while (!list_empty(head)) {
616 req = list_entry(head->next, struct usb_request, list);
617 list_del(&req->list);
618 gs_free_req(ep, req);
622 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
623 void (*fn)(struct usb_ep *, struct usb_request *))
625 int i;
626 struct usb_request *req;
628 /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
629 * do quite that many this time, don't fail ... we just won't
630 * be as speedy as we might otherwise be.
632 for (i = 0; i < QUEUE_SIZE; i++) {
633 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
634 if (!req)
635 return list_empty(head) ? -ENOMEM : 0;
636 req->complete = fn;
637 list_add_tail(&req->list, head);
639 return 0;
643 * gs_start_io - start USB I/O streams
644 * @dev: encapsulates endpoints to use
645 * Context: holding port_lock; port_tty and port_usb are non-null
647 * We only start I/O when something is connected to both sides of
648 * this port. If nothing is listening on the host side, we may
649 * be pointlessly filling up our TX buffers and FIFO.
651 static int gs_start_io(struct gs_port *port)
653 struct list_head *head = &port->read_pool;
654 struct usb_ep *ep = port->port_usb->out;
655 int status;
656 unsigned started;
658 /* Allocate RX and TX I/O buffers. We can't easily do this much
659 * earlier (with GFP_KERNEL) because the requests are coupled to
660 * endpoints, as are the packet sizes we'll be using. Different
661 * configurations may use different endpoints with a given port;
662 * and high speed vs full speed changes packet sizes too.
664 status = gs_alloc_requests(ep, head, gs_read_complete);
665 if (status)
666 return status;
668 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
669 gs_write_complete);
670 if (status) {
671 gs_free_requests(ep, head);
672 return status;
675 /* queue read requests */
676 port->n_read = 0;
677 started = gs_start_rx(port);
679 /* unblock any pending writes into our circular buffer */
680 if (started) {
681 tty_wakeup(port->port_tty);
682 } else {
683 gs_free_requests(ep, head);
684 gs_free_requests(port->port_usb->in, &port->write_pool);
685 status = -EIO;
688 return status;
691 /*-------------------------------------------------------------------------*/
693 /* TTY Driver */
696 * gs_open sets up the link between a gs_port and its associated TTY.
697 * That link is broken *only* by TTY close(), and all driver methods
698 * know that.
700 static int gs_open(struct tty_struct *tty, struct file *file)
702 int port_num = tty->index;
703 struct gs_port *port;
704 int status;
706 if (port_num < 0 || port_num >= n_ports)
707 return -ENXIO;
709 do {
710 mutex_lock(&ports[port_num].lock);
711 port = ports[port_num].port;
712 if (!port)
713 status = -ENODEV;
714 else {
715 spin_lock_irq(&port->port_lock);
717 /* already open? Great. */
718 if (port->open_count) {
719 status = 0;
720 port->open_count++;
722 /* currently opening/closing? wait ... */
723 } else if (port->openclose) {
724 status = -EBUSY;
726 /* ... else we do the work */
727 } else {
728 status = -EAGAIN;
729 port->openclose = true;
731 spin_unlock_irq(&port->port_lock);
733 mutex_unlock(&ports[port_num].lock);
735 switch (status) {
736 default:
737 /* fully handled */
738 return status;
739 case -EAGAIN:
740 /* must do the work */
741 break;
742 case -EBUSY:
743 /* wait for EAGAIN task to finish */
744 msleep(1);
745 /* REVISIT could have a waitchannel here, if
746 * concurrent open performance is important
748 break;
750 } while (status != -EAGAIN);
752 /* Do the "real open" */
753 spin_lock_irq(&port->port_lock);
755 /* allocate circular buffer on first open */
756 if (port->port_write_buf.buf_buf == NULL) {
758 spin_unlock_irq(&port->port_lock);
759 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
760 spin_lock_irq(&port->port_lock);
762 if (status) {
763 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
764 port->port_num, tty, file);
765 port->openclose = false;
766 goto exit_unlock_port;
770 /* REVISIT if REMOVED (ports[].port NULL), abort the open
771 * to let rmmod work faster (but this way isn't wrong).
774 /* REVISIT maybe wait for "carrier detect" */
776 tty->driver_data = port;
777 port->port_tty = tty;
779 port->open_count = 1;
780 port->openclose = false;
782 /* if connected, start the I/O stream */
783 if (port->port_usb) {
784 struct gserial *gser = port->port_usb;
786 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
787 gs_start_io(port);
789 if (gser->connect)
790 gser->connect(gser);
793 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
795 status = 0;
797 exit_unlock_port:
798 spin_unlock_irq(&port->port_lock);
799 return status;
802 static int gs_writes_finished(struct gs_port *p)
804 int cond;
806 /* return true on disconnect or empty buffer */
807 spin_lock_irq(&p->port_lock);
808 cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
809 spin_unlock_irq(&p->port_lock);
811 return cond;
814 static void gs_close(struct tty_struct *tty, struct file *file)
816 struct gs_port *port = tty->driver_data;
817 struct gserial *gser;
819 spin_lock_irq(&port->port_lock);
821 if (port->open_count != 1) {
822 if (port->open_count == 0)
823 WARN_ON(1);
824 else
825 --port->open_count;
826 goto exit;
829 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
831 /* mark port as closing but in use; we can drop port lock
832 * and sleep if necessary
834 port->openclose = true;
835 port->open_count = 0;
837 gser = port->port_usb;
838 if (gser && gser->disconnect)
839 gser->disconnect(gser);
841 /* wait for circular write buffer to drain, disconnect, or at
842 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
844 if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
845 spin_unlock_irq(&port->port_lock);
846 wait_event_interruptible_timeout(port->drain_wait,
847 gs_writes_finished(port),
848 GS_CLOSE_TIMEOUT * HZ);
849 spin_lock_irq(&port->port_lock);
850 gser = port->port_usb;
853 /* Iff we're disconnected, there can be no I/O in flight so it's
854 * ok to free the circular buffer; else just scrub it. And don't
855 * let the push tasklet fire again until we're re-opened.
857 if (gser == NULL)
858 gs_buf_free(&port->port_write_buf);
859 else
860 gs_buf_clear(&port->port_write_buf);
862 tty->driver_data = NULL;
863 port->port_tty = NULL;
865 port->openclose = false;
867 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
868 port->port_num, tty, file);
870 wake_up_interruptible(&port->close_wait);
871 exit:
872 spin_unlock_irq(&port->port_lock);
875 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
877 struct gs_port *port = tty->driver_data;
878 unsigned long flags;
879 int status;
881 pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
882 port->port_num, tty, count);
884 spin_lock_irqsave(&port->port_lock, flags);
885 if (count)
886 count = gs_buf_put(&port->port_write_buf, buf, count);
887 /* treat count == 0 as flush_chars() */
888 if (port->port_usb)
889 status = gs_start_tx(port);
890 spin_unlock_irqrestore(&port->port_lock, flags);
892 return count;
895 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
897 struct gs_port *port = tty->driver_data;
898 unsigned long flags;
899 int status;
901 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
902 port->port_num, tty, ch, __builtin_return_address(0));
904 spin_lock_irqsave(&port->port_lock, flags);
905 status = gs_buf_put(&port->port_write_buf, &ch, 1);
906 spin_unlock_irqrestore(&port->port_lock, flags);
908 return status;
911 static void gs_flush_chars(struct tty_struct *tty)
913 struct gs_port *port = tty->driver_data;
914 unsigned long flags;
916 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
918 spin_lock_irqsave(&port->port_lock, flags);
919 if (port->port_usb)
920 gs_start_tx(port);
921 spin_unlock_irqrestore(&port->port_lock, flags);
924 static int gs_write_room(struct tty_struct *tty)
926 struct gs_port *port = tty->driver_data;
927 unsigned long flags;
928 int room = 0;
930 spin_lock_irqsave(&port->port_lock, flags);
931 if (port->port_usb)
932 room = gs_buf_space_avail(&port->port_write_buf);
933 spin_unlock_irqrestore(&port->port_lock, flags);
935 pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
936 port->port_num, tty, room);
938 return room;
941 static int gs_chars_in_buffer(struct tty_struct *tty)
943 struct gs_port *port = tty->driver_data;
944 unsigned long flags;
945 int chars = 0;
947 spin_lock_irqsave(&port->port_lock, flags);
948 chars = gs_buf_data_avail(&port->port_write_buf);
949 spin_unlock_irqrestore(&port->port_lock, flags);
951 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
952 port->port_num, tty, chars);
954 return chars;
957 /* undo side effects of setting TTY_THROTTLED */
958 static void gs_unthrottle(struct tty_struct *tty)
960 struct gs_port *port = tty->driver_data;
961 unsigned long flags;
963 spin_lock_irqsave(&port->port_lock, flags);
964 if (port->port_usb) {
965 /* Kickstart read queue processing. We don't do xon/xoff,
966 * rts/cts, or other handshaking with the host, but if the
967 * read queue backs up enough we'll be NAKing OUT packets.
969 tasklet_schedule(&port->push);
970 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
972 spin_unlock_irqrestore(&port->port_lock, flags);
975 static int gs_break_ctl(struct tty_struct *tty, int duration)
977 struct gs_port *port = tty->driver_data;
978 int status = 0;
979 struct gserial *gser;
981 pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
982 port->port_num, duration);
984 spin_lock_irq(&port->port_lock);
985 gser = port->port_usb;
986 if (gser && gser->send_break)
987 status = gser->send_break(gser, duration);
988 spin_unlock_irq(&port->port_lock);
990 return status;
993 static const struct tty_operations gs_tty_ops = {
994 .open = gs_open,
995 .close = gs_close,
996 .write = gs_write,
997 .put_char = gs_put_char,
998 .flush_chars = gs_flush_chars,
999 .write_room = gs_write_room,
1000 .chars_in_buffer = gs_chars_in_buffer,
1001 .unthrottle = gs_unthrottle,
1002 .break_ctl = gs_break_ctl,
1005 /*-------------------------------------------------------------------------*/
1007 static struct tty_driver *gs_tty_driver;
1009 static int __init
1010 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1012 struct gs_port *port;
1014 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1015 if (port == NULL)
1016 return -ENOMEM;
1018 spin_lock_init(&port->port_lock);
1019 init_waitqueue_head(&port->close_wait);
1020 init_waitqueue_head(&port->drain_wait);
1022 tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1024 INIT_LIST_HEAD(&port->read_pool);
1025 INIT_LIST_HEAD(&port->read_queue);
1026 INIT_LIST_HEAD(&port->write_pool);
1028 port->port_num = port_num;
1029 port->port_line_coding = *coding;
1031 ports[port_num].port = port;
1033 return 0;
1037 * gserial_setup - initialize TTY driver for one or more ports
1038 * @g: gadget to associate with these ports
1039 * @count: how many ports to support
1040 * Context: may sleep
1042 * The TTY stack needs to know in advance how many devices it should
1043 * plan to manage. Use this call to set up the ports you will be
1044 * exporting through USB. Later, connect them to functions based
1045 * on what configuration is activated by the USB host; and disconnect
1046 * them as appropriate.
1048 * An example would be a two-configuration device in which both
1049 * configurations expose port 0, but through different functions.
1050 * One configuration could even expose port 1 while the other
1051 * one doesn't.
1053 * Returns negative errno or zero.
1055 int __init gserial_setup(struct usb_gadget *g, unsigned count)
1057 unsigned i;
1058 struct usb_cdc_line_coding coding;
1059 int status;
1061 if (count == 0 || count > N_PORTS)
1062 return -EINVAL;
1064 gs_tty_driver = alloc_tty_driver(count);
1065 if (!gs_tty_driver)
1066 return -ENOMEM;
1068 gs_tty_driver->owner = THIS_MODULE;
1069 gs_tty_driver->driver_name = "g_serial";
1070 gs_tty_driver->name = PREFIX;
1071 /* uses dynamically assigned dev_t values */
1073 gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1074 gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1075 gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1076 gs_tty_driver->init_termios = tty_std_termios;
1078 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1079 * MS-Windows. Otherwise, most of these flags shouldn't affect
1080 * anything unless we were to actually hook up to a serial line.
1082 gs_tty_driver->init_termios.c_cflag =
1083 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1084 gs_tty_driver->init_termios.c_ispeed = 9600;
1085 gs_tty_driver->init_termios.c_ospeed = 9600;
1087 coding.dwDTERate = cpu_to_le32(9600);
1088 coding.bCharFormat = 8;
1089 coding.bParityType = USB_CDC_NO_PARITY;
1090 coding.bDataBits = USB_CDC_1_STOP_BITS;
1092 tty_set_operations(gs_tty_driver, &gs_tty_ops);
1094 /* make devices be openable */
1095 for (i = 0; i < count; i++) {
1096 mutex_init(&ports[i].lock);
1097 status = gs_port_alloc(i, &coding);
1098 if (status) {
1099 count = i;
1100 goto fail;
1103 n_ports = count;
1105 /* export the driver ... */
1106 status = tty_register_driver(gs_tty_driver);
1107 if (status) {
1108 pr_err("%s: cannot register, err %d\n",
1109 __func__, status);
1110 goto fail;
1113 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1114 for (i = 0; i < count; i++) {
1115 struct device *tty_dev;
1117 tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
1118 if (IS_ERR(tty_dev))
1119 pr_warning("%s: no classdev for port %d, err %ld\n",
1120 __func__, i, PTR_ERR(tty_dev));
1123 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1124 count, (count == 1) ? "" : "s");
1126 return status;
1127 fail:
1128 while (count--)
1129 kfree(ports[count].port);
1130 put_tty_driver(gs_tty_driver);
1131 gs_tty_driver = NULL;
1132 return status;
1135 static int gs_closed(struct gs_port *port)
1137 int cond;
1139 spin_lock_irq(&port->port_lock);
1140 cond = (port->open_count == 0) && !port->openclose;
1141 spin_unlock_irq(&port->port_lock);
1142 return cond;
1146 * gserial_cleanup - remove TTY-over-USB driver and devices
1147 * Context: may sleep
1149 * This is called to free all resources allocated by @gserial_setup().
1150 * Accordingly, it may need to wait until some open /dev/ files have
1151 * closed.
1153 * The caller must have issued @gserial_disconnect() for any ports
1154 * that had previously been connected, so that there is never any
1155 * I/O pending when it's called.
1157 void gserial_cleanup(void)
1159 unsigned i;
1160 struct gs_port *port;
1162 if (!gs_tty_driver)
1163 return;
1165 /* start sysfs and /dev/ttyGS* node removal */
1166 for (i = 0; i < n_ports; i++)
1167 tty_unregister_device(gs_tty_driver, i);
1169 for (i = 0; i < n_ports; i++) {
1170 /* prevent new opens */
1171 mutex_lock(&ports[i].lock);
1172 port = ports[i].port;
1173 ports[i].port = NULL;
1174 mutex_unlock(&ports[i].lock);
1176 tasklet_kill(&port->push);
1178 /* wait for old opens to finish */
1179 wait_event(port->close_wait, gs_closed(port));
1181 WARN_ON(port->port_usb != NULL);
1183 kfree(port);
1185 n_ports = 0;
1187 tty_unregister_driver(gs_tty_driver);
1188 put_tty_driver(gs_tty_driver);
1189 gs_tty_driver = NULL;
1191 pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1195 * gserial_connect - notify TTY I/O glue that USB link is active
1196 * @gser: the function, set up with endpoints and descriptors
1197 * @port_num: which port is active
1198 * Context: any (usually from irq)
1200 * This is called activate endpoints and let the TTY layer know that
1201 * the connection is active ... not unlike "carrier detect". It won't
1202 * necessarily start I/O queues; unless the TTY is held open by any
1203 * task, there would be no point. However, the endpoints will be
1204 * activated so the USB host can perform I/O, subject to basic USB
1205 * hardware flow control.
1207 * Caller needs to have set up the endpoints and USB function in @dev
1208 * before calling this, as well as the appropriate (speed-specific)
1209 * endpoint descriptors, and also have set up the TTY driver by calling
1210 * @gserial_setup().
1212 * Returns negative errno or zero.
1213 * On success, ep->driver_data will be overwritten.
1215 int gserial_connect(struct gserial *gser, u8 port_num)
1217 struct gs_port *port;
1218 unsigned long flags;
1219 int status;
1221 if (!gs_tty_driver || port_num >= n_ports)
1222 return -ENXIO;
1224 /* we "know" gserial_cleanup() hasn't been called */
1225 port = ports[port_num].port;
1227 /* activate the endpoints */
1228 status = usb_ep_enable(gser->in, gser->in_desc);
1229 if (status < 0)
1230 return status;
1231 gser->in->driver_data = port;
1233 status = usb_ep_enable(gser->out, gser->out_desc);
1234 if (status < 0)
1235 goto fail_out;
1236 gser->out->driver_data = port;
1238 /* then tell the tty glue that I/O can work */
1239 spin_lock_irqsave(&port->port_lock, flags);
1240 gser->ioport = port;
1241 port->port_usb = gser;
1243 /* REVISIT unclear how best to handle this state...
1244 * we don't really couple it with the Linux TTY.
1246 gser->port_line_coding = port->port_line_coding;
1248 /* REVISIT if waiting on "carrier detect", signal. */
1250 /* if it's already open, start I/O ... and notify the serial
1251 * protocol about open/close status (connect/disconnect).
1253 if (port->open_count) {
1254 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1255 gs_start_io(port);
1256 if (gser->connect)
1257 gser->connect(gser);
1258 } else {
1259 if (gser->disconnect)
1260 gser->disconnect(gser);
1263 spin_unlock_irqrestore(&port->port_lock, flags);
1265 return status;
1267 fail_out:
1268 usb_ep_disable(gser->in);
1269 gser->in->driver_data = NULL;
1270 return status;
1274 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1275 * @gser: the function, on which gserial_connect() was called
1276 * Context: any (usually from irq)
1278 * This is called to deactivate endpoints and let the TTY layer know
1279 * that the connection went inactive ... not unlike "hangup".
1281 * On return, the state is as if gserial_connect() had never been called;
1282 * there is no active USB I/O on these endpoints.
1284 void gserial_disconnect(struct gserial *gser)
1286 struct gs_port *port = gser->ioport;
1287 unsigned long flags;
1289 if (!port)
1290 return;
1292 /* tell the TTY glue not to do I/O here any more */
1293 spin_lock_irqsave(&port->port_lock, flags);
1295 /* REVISIT as above: how best to track this? */
1296 port->port_line_coding = gser->port_line_coding;
1298 port->port_usb = NULL;
1299 gser->ioport = NULL;
1300 if (port->open_count > 0 || port->openclose) {
1301 wake_up_interruptible(&port->drain_wait);
1302 if (port->port_tty)
1303 tty_hangup(port->port_tty);
1305 spin_unlock_irqrestore(&port->port_lock, flags);
1307 /* disable endpoints, aborting down any active I/O */
1308 usb_ep_disable(gser->out);
1309 gser->out->driver_data = NULL;
1311 usb_ep_disable(gser->in);
1312 gser->in->driver_data = NULL;
1314 /* finally, free any unused/unusable I/O buffers */
1315 spin_lock_irqsave(&port->port_lock, flags);
1316 if (port->open_count == 0 && !port->openclose)
1317 gs_buf_free(&port->port_write_buf);
1318 gs_free_requests(gser->out, &port->read_pool);
1319 gs_free_requests(gser->out, &port->read_queue);
1320 gs_free_requests(gser->in, &port->write_pool);
1321 spin_unlock_irqrestore(&port->port_lock, flags);