USB: g_serial: fix tty cleanup on unload
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / drivers / usb / gadget / u_serial.c
blob3e8dcb5455e3a4912f7bc0fc525b69c524cade7f
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>
26 #include <linux/slab.h>
28 #include "u_serial.h"
32 * This component encapsulates the TTY layer glue needed to provide basic
33 * "serial port" functionality through the USB gadget stack. Each such
34 * port is exposed through a /dev/ttyGS* node.
36 * After initialization (gserial_setup), these TTY port devices stay
37 * available until they are removed (gserial_cleanup). Each one may be
38 * connected to a USB function (gserial_connect), or disconnected (with
39 * gserial_disconnect) when the USB host issues a config change event.
40 * Data can only flow when the port is connected to the host.
42 * A given TTY port can be made available in multiple configurations.
43 * For example, each one might expose a ttyGS0 node which provides a
44 * login application. In one case that might use CDC ACM interface 0,
45 * while another configuration might use interface 3 for that. The
46 * work to handle that (including descriptor management) is not part
47 * of this component.
49 * Configurations may expose more than one TTY port. For example, if
50 * ttyGS0 provides login service, then ttyGS1 might provide dialer access
51 * for a telephone or fax link. And ttyGS2 might be something that just
52 * needs a simple byte stream interface for some messaging protocol that
53 * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
56 #define PREFIX "ttyGS"
59 * gserial is the lifecycle interface, used by USB functions
60 * gs_port is the I/O nexus, used by the tty driver
61 * tty_struct links to the tty/filesystem framework
63 * gserial <---> gs_port ... links will be null when the USB link is
64 * inactive; managed by gserial_{connect,disconnect}(). each gserial
65 * instance can wrap its own USB control protocol.
66 * gserial->ioport == usb_ep->driver_data ... gs_port
67 * gs_port->port_usb ... gserial
69 * gs_port <---> tty_struct ... links will be null when the TTY file
70 * isn't opened; managed by gs_open()/gs_close()
71 * gserial->port_tty ... tty_struct
72 * tty_struct->driver_data ... gserial
75 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
76 * next layer of buffering. For TX that's a circular buffer; for RX
77 * consider it a NOP. A third layer is provided by the TTY code.
79 #define QUEUE_SIZE 16
80 #define WRITE_BUF_SIZE 8192 /* TX only */
82 /* circular buffer */
83 struct gs_buf {
84 unsigned buf_size;
85 char *buf_buf;
86 char *buf_get;
87 char *buf_put;
91 * The port structure holds info for each port, one for each minor number
92 * (and thus for each /dev/ node).
94 struct gs_port {
95 spinlock_t port_lock; /* guard port_* access */
97 struct gserial *port_usb;
98 struct tty_struct *port_tty;
100 unsigned open_count;
101 bool openclose; /* open/close in progress */
102 u8 port_num;
104 wait_queue_head_t close_wait; /* wait for last close */
106 struct list_head read_pool;
107 struct list_head read_queue;
108 unsigned n_read;
109 struct tasklet_struct push;
111 struct list_head write_pool;
112 struct gs_buf port_write_buf;
113 wait_queue_head_t drain_wait; /* wait while writes drain */
115 /* REVISIT this state ... */
116 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
119 /* increase N_PORTS if you need more */
120 #define N_PORTS 4
121 static struct portmaster {
122 struct mutex lock; /* protect open/close */
123 struct gs_port *port;
124 } ports[N_PORTS];
125 static unsigned n_ports;
127 #define GS_CLOSE_TIMEOUT 15 /* seconds */
131 #ifdef VERBOSE_DEBUG
132 #define pr_vdebug(fmt, arg...) \
133 pr_debug(fmt, ##arg)
134 #else
135 #define pr_vdebug(fmt, arg...) \
136 ({ if (0) pr_debug(fmt, ##arg); })
137 #endif
139 /*-------------------------------------------------------------------------*/
141 /* Circular Buffer */
144 * gs_buf_alloc
146 * Allocate a circular buffer and all associated memory.
148 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
150 gb->buf_buf = kmalloc(size, GFP_KERNEL);
151 if (gb->buf_buf == NULL)
152 return -ENOMEM;
154 gb->buf_size = size;
155 gb->buf_put = gb->buf_buf;
156 gb->buf_get = gb->buf_buf;
158 return 0;
162 * gs_buf_free
164 * Free the buffer and all associated memory.
166 static void gs_buf_free(struct gs_buf *gb)
168 kfree(gb->buf_buf);
169 gb->buf_buf = NULL;
173 * gs_buf_clear
175 * Clear out all data in the circular buffer.
177 static void gs_buf_clear(struct gs_buf *gb)
179 gb->buf_get = gb->buf_put;
180 /* equivalent to a get of all data available */
184 * gs_buf_data_avail
186 * Return the number of bytes of data written into the circular
187 * buffer.
189 static unsigned gs_buf_data_avail(struct gs_buf *gb)
191 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
195 * gs_buf_space_avail
197 * Return the number of bytes of space available in the circular
198 * buffer.
200 static unsigned gs_buf_space_avail(struct gs_buf *gb)
202 return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
206 * gs_buf_put
208 * Copy data data from a user buffer and put it into the circular buffer.
209 * Restrict to the amount of space available.
211 * Return the number of bytes copied.
213 static unsigned
214 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
216 unsigned len;
218 len = gs_buf_space_avail(gb);
219 if (count > len)
220 count = len;
222 if (count == 0)
223 return 0;
225 len = gb->buf_buf + gb->buf_size - gb->buf_put;
226 if (count > len) {
227 memcpy(gb->buf_put, buf, len);
228 memcpy(gb->buf_buf, buf+len, count - len);
229 gb->buf_put = gb->buf_buf + count - len;
230 } else {
231 memcpy(gb->buf_put, buf, count);
232 if (count < len)
233 gb->buf_put += count;
234 else /* count == len */
235 gb->buf_put = gb->buf_buf;
238 return count;
242 * gs_buf_get
244 * Get data from the circular buffer and copy to the given buffer.
245 * Restrict to the amount of data available.
247 * Return the number of bytes copied.
249 static unsigned
250 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
252 unsigned len;
254 len = gs_buf_data_avail(gb);
255 if (count > len)
256 count = len;
258 if (count == 0)
259 return 0;
261 len = gb->buf_buf + gb->buf_size - gb->buf_get;
262 if (count > len) {
263 memcpy(buf, gb->buf_get, len);
264 memcpy(buf+len, gb->buf_buf, count - len);
265 gb->buf_get = gb->buf_buf + count - len;
266 } else {
267 memcpy(buf, gb->buf_get, count);
268 if (count < len)
269 gb->buf_get += count;
270 else /* count == len */
271 gb->buf_get = gb->buf_buf;
274 return count;
277 /*-------------------------------------------------------------------------*/
279 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
282 * gs_alloc_req
284 * Allocate a usb_request and its buffer. Returns a pointer to the
285 * usb_request or NULL if there is an error.
287 struct usb_request *
288 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
290 struct usb_request *req;
292 req = usb_ep_alloc_request(ep, kmalloc_flags);
294 if (req != NULL) {
295 req->length = len;
296 req->buf = kmalloc(len, kmalloc_flags);
297 if (req->buf == NULL) {
298 usb_ep_free_request(ep, req);
299 return NULL;
303 return req;
307 * gs_free_req
309 * Free a usb_request and its buffer.
311 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
313 kfree(req->buf);
314 usb_ep_free_request(ep, req);
318 * gs_send_packet
320 * If there is data to send, a packet is built in the given
321 * buffer and the size is returned. If there is no data to
322 * send, 0 is returned.
324 * Called with port_lock held.
326 static unsigned
327 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
329 unsigned len;
331 len = gs_buf_data_avail(&port->port_write_buf);
332 if (len < size)
333 size = len;
334 if (size != 0)
335 size = gs_buf_get(&port->port_write_buf, packet, size);
336 return size;
340 * gs_start_tx
342 * This function finds available write requests, calls
343 * gs_send_packet to fill these packets with data, and
344 * continues until either there are no more write requests
345 * available or no more data to send. This function is
346 * run whenever data arrives or write requests are available.
348 * Context: caller owns port_lock; port_usb is non-null.
350 static int gs_start_tx(struct gs_port *port)
352 __releases(&port->port_lock)
353 __acquires(&port->port_lock)
356 struct list_head *pool = &port->write_pool;
357 struct usb_ep *in = port->port_usb->in;
358 int status = 0;
359 bool do_tty_wake = false;
361 while (!list_empty(pool)) {
362 struct usb_request *req;
363 int len;
365 req = list_entry(pool->next, struct usb_request, list);
366 len = gs_send_packet(port, req->buf, in->maxpacket);
367 if (len == 0) {
368 wake_up_interruptible(&port->drain_wait);
369 break;
371 do_tty_wake = true;
373 req->length = len;
374 list_del(&req->list);
375 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
377 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
378 port->port_num, len, *((u8 *)req->buf),
379 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
381 /* Drop lock while we call out of driver; completions
382 * could be issued while we do so. Disconnection may
383 * happen too; maybe immediately before we queue this!
385 * NOTE that we may keep sending data for a while after
386 * the TTY closed (dev->ioport->port_tty is NULL).
388 spin_unlock(&port->port_lock);
389 status = usb_ep_queue(in, req, GFP_ATOMIC);
390 spin_lock(&port->port_lock);
392 if (status) {
393 pr_debug("%s: %s %s err %d\n",
394 __func__, "queue", in->name, status);
395 list_add(&req->list, pool);
396 break;
399 /* abort immediately after disconnect */
400 if (!port->port_usb)
401 break;
404 if (do_tty_wake && port->port_tty)
405 tty_wakeup(port->port_tty);
406 return status;
410 * Context: caller owns port_lock, and port_usb is set
412 static unsigned gs_start_rx(struct gs_port *port)
414 __releases(&port->port_lock)
415 __acquires(&port->port_lock)
418 struct list_head *pool = &port->read_pool;
419 struct usb_ep *out = port->port_usb->out;
420 unsigned started = 0;
422 while (!list_empty(pool)) {
423 struct usb_request *req;
424 int status;
425 struct tty_struct *tty;
427 /* no more rx if closed */
428 tty = port->port_tty;
429 if (!tty)
430 break;
432 req = list_entry(pool->next, struct usb_request, list);
433 list_del(&req->list);
434 req->length = out->maxpacket;
436 /* drop lock while we call out; the controller driver
437 * may need to call us back (e.g. for disconnect)
439 spin_unlock(&port->port_lock);
440 status = usb_ep_queue(out, req, GFP_ATOMIC);
441 spin_lock(&port->port_lock);
443 if (status) {
444 pr_debug("%s: %s %s err %d\n",
445 __func__, "queue", out->name, status);
446 list_add(&req->list, pool);
447 break;
449 started++;
451 /* abort immediately after disconnect */
452 if (!port->port_usb)
453 break;
455 return started;
459 * RX tasklet takes data out of the RX queue and hands it up to the TTY
460 * layer until it refuses to take any more data (or is throttled back).
461 * Then it issues reads for any further data.
463 * If the RX queue becomes full enough that no usb_request is queued,
464 * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
465 * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
466 * can be buffered before the TTY layer's buffers (currently 64 KB).
468 static void gs_rx_push(unsigned long _port)
470 struct gs_port *port = (void *)_port;
471 struct tty_struct *tty;
472 struct list_head *queue = &port->read_queue;
473 bool disconnect = false;
474 bool do_push = false;
476 /* hand any queued data to the tty */
477 spin_lock_irq(&port->port_lock);
478 tty = port->port_tty;
479 while (!list_empty(queue)) {
480 struct usb_request *req;
482 req = list_first_entry(queue, struct usb_request, list);
484 /* discard data if tty was closed */
485 if (!tty)
486 goto recycle;
488 /* leave data queued if tty was rx throttled */
489 if (test_bit(TTY_THROTTLED, &tty->flags))
490 break;
492 switch (req->status) {
493 case -ESHUTDOWN:
494 disconnect = true;
495 pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
496 break;
498 default:
499 /* presumably a transient fault */
500 pr_warning(PREFIX "%d: unexpected RX status %d\n",
501 port->port_num, req->status);
502 /* FALLTHROUGH */
503 case 0:
504 /* normal completion */
505 break;
508 /* push data to (open) tty */
509 if (req->actual) {
510 char *packet = req->buf;
511 unsigned size = req->actual;
512 unsigned n;
513 int count;
515 /* we may have pushed part of this packet already... */
516 n = port->n_read;
517 if (n) {
518 packet += n;
519 size -= n;
522 count = tty_insert_flip_string(tty, packet, size);
523 if (count)
524 do_push = true;
525 if (count != size) {
526 /* stop pushing; TTY layer can't handle more */
527 port->n_read += count;
528 pr_vdebug(PREFIX "%d: rx block %d/%d\n",
529 port->port_num,
530 count, req->actual);
531 break;
533 port->n_read = 0;
535 recycle:
536 list_move(&req->list, &port->read_pool);
539 /* Push from tty to ldisc; without low_latency set this is handled by
540 * a workqueue, so we won't get callbacks and can hold port_lock
542 if (tty && do_push) {
543 tty_flip_buffer_push(tty);
547 /* We want our data queue to become empty ASAP, keeping data
548 * in the tty and ldisc (not here). If we couldn't push any
549 * this time around, there may be trouble unless there's an
550 * implicit tty_unthrottle() call on its way...
552 * REVISIT we should probably add a timer to keep the tasklet
553 * from starving ... but it's not clear that case ever happens.
555 if (!list_empty(queue) && tty) {
556 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
557 if (do_push)
558 tasklet_schedule(&port->push);
559 else
560 pr_warning(PREFIX "%d: RX not scheduled?\n",
561 port->port_num);
565 /* If we're still connected, refill the USB RX queue. */
566 if (!disconnect && port->port_usb)
567 gs_start_rx(port);
569 spin_unlock_irq(&port->port_lock);
572 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
574 struct gs_port *port = ep->driver_data;
576 /* Queue all received data until the tty layer is ready for it. */
577 spin_lock(&port->port_lock);
578 list_add_tail(&req->list, &port->read_queue);
579 tasklet_schedule(&port->push);
580 spin_unlock(&port->port_lock);
583 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
585 struct gs_port *port = ep->driver_data;
587 spin_lock(&port->port_lock);
588 list_add(&req->list, &port->write_pool);
590 switch (req->status) {
591 default:
592 /* presumably a transient fault */
593 pr_warning("%s: unexpected %s status %d\n",
594 __func__, ep->name, req->status);
595 /* FALL THROUGH */
596 case 0:
597 /* normal completion */
598 gs_start_tx(port);
599 break;
601 case -ESHUTDOWN:
602 /* disconnect */
603 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
604 break;
607 spin_unlock(&port->port_lock);
610 static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
612 struct usb_request *req;
614 while (!list_empty(head)) {
615 req = list_entry(head->next, struct usb_request, list);
616 list_del(&req->list);
617 gs_free_req(ep, req);
621 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
622 void (*fn)(struct usb_ep *, struct usb_request *))
624 int i;
625 struct usb_request *req;
627 /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
628 * do quite that many this time, don't fail ... we just won't
629 * be as speedy as we might otherwise be.
631 for (i = 0; i < QUEUE_SIZE; i++) {
632 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
633 if (!req)
634 return list_empty(head) ? -ENOMEM : 0;
635 req->complete = fn;
636 list_add_tail(&req->list, head);
638 return 0;
642 * gs_start_io - start USB I/O streams
643 * @dev: encapsulates endpoints to use
644 * Context: holding port_lock; port_tty and port_usb are non-null
646 * We only start I/O when something is connected to both sides of
647 * this port. If nothing is listening on the host side, we may
648 * be pointlessly filling up our TX buffers and FIFO.
650 static int gs_start_io(struct gs_port *port)
652 struct list_head *head = &port->read_pool;
653 struct usb_ep *ep = port->port_usb->out;
654 int status;
655 unsigned started;
657 /* Allocate RX and TX I/O buffers. We can't easily do this much
658 * earlier (with GFP_KERNEL) because the requests are coupled to
659 * endpoints, as are the packet sizes we'll be using. Different
660 * configurations may use different endpoints with a given port;
661 * and high speed vs full speed changes packet sizes too.
663 status = gs_alloc_requests(ep, head, gs_read_complete);
664 if (status)
665 return status;
667 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
668 gs_write_complete);
669 if (status) {
670 gs_free_requests(ep, head);
671 return status;
674 /* queue read requests */
675 port->n_read = 0;
676 started = gs_start_rx(port);
678 /* unblock any pending writes into our circular buffer */
679 if (started) {
680 tty_wakeup(port->port_tty);
681 } else {
682 gs_free_requests(ep, head);
683 gs_free_requests(port->port_usb->in, &port->write_pool);
684 status = -EIO;
687 return status;
690 /*-------------------------------------------------------------------------*/
692 /* TTY Driver */
695 * gs_open sets up the link between a gs_port and its associated TTY.
696 * That link is broken *only* by TTY close(), and all driver methods
697 * know that.
699 static int gs_open(struct tty_struct *tty, struct file *file)
701 int port_num = tty->index;
702 struct gs_port *port;
703 int status;
705 if (port_num < 0 || port_num >= n_ports)
706 return -ENXIO;
708 do {
709 mutex_lock(&ports[port_num].lock);
710 port = ports[port_num].port;
711 if (!port)
712 status = -ENODEV;
713 else {
714 spin_lock_irq(&port->port_lock);
716 /* already open? Great. */
717 if (port->open_count) {
718 status = 0;
719 port->open_count++;
721 /* currently opening/closing? wait ... */
722 } else if (port->openclose) {
723 status = -EBUSY;
725 /* ... else we do the work */
726 } else {
727 status = -EAGAIN;
728 port->openclose = true;
730 spin_unlock_irq(&port->port_lock);
732 mutex_unlock(&ports[port_num].lock);
734 switch (status) {
735 default:
736 /* fully handled */
737 return status;
738 case -EAGAIN:
739 /* must do the work */
740 break;
741 case -EBUSY:
742 /* wait for EAGAIN task to finish */
743 msleep(1);
744 /* REVISIT could have a waitchannel here, if
745 * concurrent open performance is important
747 break;
749 } while (status != -EAGAIN);
751 /* Do the "real open" */
752 spin_lock_irq(&port->port_lock);
754 /* allocate circular buffer on first open */
755 if (port->port_write_buf.buf_buf == NULL) {
757 spin_unlock_irq(&port->port_lock);
758 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
759 spin_lock_irq(&port->port_lock);
761 if (status) {
762 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
763 port->port_num, tty, file);
764 port->openclose = false;
765 goto exit_unlock_port;
769 /* REVISIT if REMOVED (ports[].port NULL), abort the open
770 * to let rmmod work faster (but this way isn't wrong).
773 /* REVISIT maybe wait for "carrier detect" */
775 tty->driver_data = port;
776 port->port_tty = tty;
778 port->open_count = 1;
779 port->openclose = false;
781 /* if connected, start the I/O stream */
782 if (port->port_usb) {
783 struct gserial *gser = port->port_usb;
785 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
786 gs_start_io(port);
788 if (gser->connect)
789 gser->connect(gser);
792 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
794 status = 0;
796 exit_unlock_port:
797 spin_unlock_irq(&port->port_lock);
798 return status;
801 static int gs_writes_finished(struct gs_port *p)
803 int cond;
805 /* return true on disconnect or empty buffer */
806 spin_lock_irq(&p->port_lock);
807 cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
808 spin_unlock_irq(&p->port_lock);
810 return cond;
813 static void gs_close(struct tty_struct *tty, struct file *file)
815 struct gs_port *port = tty->driver_data;
816 struct gserial *gser;
818 spin_lock_irq(&port->port_lock);
820 if (port->open_count != 1) {
821 if (port->open_count == 0)
822 WARN_ON(1);
823 else
824 --port->open_count;
825 goto exit;
828 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
830 /* mark port as closing but in use; we can drop port lock
831 * and sleep if necessary
833 port->openclose = true;
834 port->open_count = 0;
836 gser = port->port_usb;
837 if (gser && gser->disconnect)
838 gser->disconnect(gser);
840 /* wait for circular write buffer to drain, disconnect, or at
841 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
843 if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
844 spin_unlock_irq(&port->port_lock);
845 wait_event_interruptible_timeout(port->drain_wait,
846 gs_writes_finished(port),
847 GS_CLOSE_TIMEOUT * HZ);
848 spin_lock_irq(&port->port_lock);
849 gser = port->port_usb;
852 /* Iff we're disconnected, there can be no I/O in flight so it's
853 * ok to free the circular buffer; else just scrub it. And don't
854 * let the push tasklet fire again until we're re-opened.
856 if (gser == NULL)
857 gs_buf_free(&port->port_write_buf);
858 else
859 gs_buf_clear(&port->port_write_buf);
861 tty->driver_data = NULL;
862 port->port_tty = NULL;
864 port->openclose = false;
866 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
867 port->port_num, tty, file);
869 wake_up_interruptible(&port->close_wait);
870 exit:
871 spin_unlock_irq(&port->port_lock);
874 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
876 struct gs_port *port = tty->driver_data;
877 unsigned long flags;
878 int status;
880 pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
881 port->port_num, tty, count);
883 spin_lock_irqsave(&port->port_lock, flags);
884 if (count)
885 count = gs_buf_put(&port->port_write_buf, buf, count);
886 /* treat count == 0 as flush_chars() */
887 if (port->port_usb)
888 status = gs_start_tx(port);
889 spin_unlock_irqrestore(&port->port_lock, flags);
891 return count;
894 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
896 struct gs_port *port = tty->driver_data;
897 unsigned long flags;
898 int status;
900 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
901 port->port_num, tty, ch, __builtin_return_address(0));
903 spin_lock_irqsave(&port->port_lock, flags);
904 status = gs_buf_put(&port->port_write_buf, &ch, 1);
905 spin_unlock_irqrestore(&port->port_lock, flags);
907 return status;
910 static void gs_flush_chars(struct tty_struct *tty)
912 struct gs_port *port = tty->driver_data;
913 unsigned long flags;
915 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
917 spin_lock_irqsave(&port->port_lock, flags);
918 if (port->port_usb)
919 gs_start_tx(port);
920 spin_unlock_irqrestore(&port->port_lock, flags);
923 static int gs_write_room(struct tty_struct *tty)
925 struct gs_port *port = tty->driver_data;
926 unsigned long flags;
927 int room = 0;
929 spin_lock_irqsave(&port->port_lock, flags);
930 if (port->port_usb)
931 room = gs_buf_space_avail(&port->port_write_buf);
932 spin_unlock_irqrestore(&port->port_lock, flags);
934 pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
935 port->port_num, tty, room);
937 return room;
940 static int gs_chars_in_buffer(struct tty_struct *tty)
942 struct gs_port *port = tty->driver_data;
943 unsigned long flags;
944 int chars = 0;
946 spin_lock_irqsave(&port->port_lock, flags);
947 chars = gs_buf_data_avail(&port->port_write_buf);
948 spin_unlock_irqrestore(&port->port_lock, flags);
950 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
951 port->port_num, tty, chars);
953 return chars;
956 /* undo side effects of setting TTY_THROTTLED */
957 static void gs_unthrottle(struct tty_struct *tty)
959 struct gs_port *port = tty->driver_data;
960 unsigned long flags;
962 spin_lock_irqsave(&port->port_lock, flags);
963 if (port->port_usb) {
964 /* Kickstart read queue processing. We don't do xon/xoff,
965 * rts/cts, or other handshaking with the host, but if the
966 * read queue backs up enough we'll be NAKing OUT packets.
968 tasklet_schedule(&port->push);
969 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
971 spin_unlock_irqrestore(&port->port_lock, flags);
974 static int gs_break_ctl(struct tty_struct *tty, int duration)
976 struct gs_port *port = tty->driver_data;
977 int status = 0;
978 struct gserial *gser;
980 pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
981 port->port_num, duration);
983 spin_lock_irq(&port->port_lock);
984 gser = port->port_usb;
985 if (gser && gser->send_break)
986 status = gser->send_break(gser, duration);
987 spin_unlock_irq(&port->port_lock);
989 return status;
992 static const struct tty_operations gs_tty_ops = {
993 .open = gs_open,
994 .close = gs_close,
995 .write = gs_write,
996 .put_char = gs_put_char,
997 .flush_chars = gs_flush_chars,
998 .write_room = gs_write_room,
999 .chars_in_buffer = gs_chars_in_buffer,
1000 .unthrottle = gs_unthrottle,
1001 .break_ctl = gs_break_ctl,
1004 /*-------------------------------------------------------------------------*/
1006 static struct tty_driver *gs_tty_driver;
1008 static int __init
1009 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1011 struct gs_port *port;
1013 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1014 if (port == NULL)
1015 return -ENOMEM;
1017 spin_lock_init(&port->port_lock);
1018 init_waitqueue_head(&port->close_wait);
1019 init_waitqueue_head(&port->drain_wait);
1021 tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1023 INIT_LIST_HEAD(&port->read_pool);
1024 INIT_LIST_HEAD(&port->read_queue);
1025 INIT_LIST_HEAD(&port->write_pool);
1027 port->port_num = port_num;
1028 port->port_line_coding = *coding;
1030 ports[port_num].port = port;
1032 return 0;
1036 * gserial_setup - initialize TTY driver for one or more ports
1037 * @g: gadget to associate with these ports
1038 * @count: how many ports to support
1039 * Context: may sleep
1041 * The TTY stack needs to know in advance how many devices it should
1042 * plan to manage. Use this call to set up the ports you will be
1043 * exporting through USB. Later, connect them to functions based
1044 * on what configuration is activated by the USB host; and disconnect
1045 * them as appropriate.
1047 * An example would be a two-configuration device in which both
1048 * configurations expose port 0, but through different functions.
1049 * One configuration could even expose port 1 while the other
1050 * one doesn't.
1052 * Returns negative errno or zero.
1054 int __init gserial_setup(struct usb_gadget *g, unsigned count)
1056 unsigned i;
1057 struct usb_cdc_line_coding coding;
1058 int status;
1060 if (count == 0 || count > N_PORTS)
1061 return -EINVAL;
1063 gs_tty_driver = alloc_tty_driver(count);
1064 if (!gs_tty_driver)
1065 return -ENOMEM;
1067 gs_tty_driver->owner = THIS_MODULE;
1068 gs_tty_driver->driver_name = "g_serial";
1069 gs_tty_driver->name = PREFIX;
1070 /* uses dynamically assigned dev_t values */
1072 gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1073 gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1074 gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1075 gs_tty_driver->init_termios = tty_std_termios;
1077 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1078 * MS-Windows. Otherwise, most of these flags shouldn't affect
1079 * anything unless we were to actually hook up to a serial line.
1081 gs_tty_driver->init_termios.c_cflag =
1082 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1083 gs_tty_driver->init_termios.c_ispeed = 9600;
1084 gs_tty_driver->init_termios.c_ospeed = 9600;
1086 coding.dwDTERate = cpu_to_le32(9600);
1087 coding.bCharFormat = 8;
1088 coding.bParityType = USB_CDC_NO_PARITY;
1089 coding.bDataBits = USB_CDC_1_STOP_BITS;
1091 tty_set_operations(gs_tty_driver, &gs_tty_ops);
1093 /* make devices be openable */
1094 for (i = 0; i < count; i++) {
1095 mutex_init(&ports[i].lock);
1096 status = gs_port_alloc(i, &coding);
1097 if (status) {
1098 count = i;
1099 goto fail;
1102 n_ports = count;
1104 /* export the driver ... */
1105 status = tty_register_driver(gs_tty_driver);
1106 if (status) {
1107 pr_err("%s: cannot register, err %d\n",
1108 __func__, status);
1109 goto fail;
1112 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1113 for (i = 0; i < count; i++) {
1114 struct device *tty_dev;
1116 tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
1117 if (IS_ERR(tty_dev))
1118 pr_warning("%s: no classdev for port %d, err %ld\n",
1119 __func__, i, PTR_ERR(tty_dev));
1122 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1123 count, (count == 1) ? "" : "s");
1125 return status;
1126 fail:
1127 while (count--)
1128 kfree(ports[count].port);
1129 put_tty_driver(gs_tty_driver);
1130 gs_tty_driver = NULL;
1131 return status;
1134 static int gs_closed(struct gs_port *port)
1136 int cond;
1138 spin_lock_irq(&port->port_lock);
1139 cond = (port->open_count == 0) && !port->openclose;
1140 spin_unlock_irq(&port->port_lock);
1141 return cond;
1145 * gserial_cleanup - remove TTY-over-USB driver and devices
1146 * Context: may sleep
1148 * This is called to free all resources allocated by @gserial_setup().
1149 * Accordingly, it may need to wait until some open /dev/ files have
1150 * closed.
1152 * The caller must have issued @gserial_disconnect() for any ports
1153 * that had previously been connected, so that there is never any
1154 * I/O pending when it's called.
1156 void gserial_cleanup(void)
1158 unsigned i;
1159 struct gs_port *port;
1161 if (!gs_tty_driver)
1162 return;
1164 /* start sysfs and /dev/ttyGS* node removal */
1165 for (i = 0; i < n_ports; i++)
1166 tty_unregister_device(gs_tty_driver, i);
1168 for (i = 0; i < n_ports; i++) {
1169 /* prevent new opens */
1170 mutex_lock(&ports[i].lock);
1171 port = ports[i].port;
1172 ports[i].port = NULL;
1173 mutex_unlock(&ports[i].lock);
1175 tasklet_kill(&port->push);
1177 /* wait for old opens to finish */
1178 wait_event(port->close_wait, gs_closed(port));
1180 WARN_ON(port->port_usb != NULL);
1182 kfree(port);
1184 n_ports = 0;
1186 tty_unregister_driver(gs_tty_driver);
1187 put_tty_driver(gs_tty_driver);
1188 gs_tty_driver = NULL;
1190 pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1194 * gserial_connect - notify TTY I/O glue that USB link is active
1195 * @gser: the function, set up with endpoints and descriptors
1196 * @port_num: which port is active
1197 * Context: any (usually from irq)
1199 * This is called activate endpoints and let the TTY layer know that
1200 * the connection is active ... not unlike "carrier detect". It won't
1201 * necessarily start I/O queues; unless the TTY is held open by any
1202 * task, there would be no point. However, the endpoints will be
1203 * activated so the USB host can perform I/O, subject to basic USB
1204 * hardware flow control.
1206 * Caller needs to have set up the endpoints and USB function in @dev
1207 * before calling this, as well as the appropriate (speed-specific)
1208 * endpoint descriptors, and also have set up the TTY driver by calling
1209 * @gserial_setup().
1211 * Returns negative errno or zero.
1212 * On success, ep->driver_data will be overwritten.
1214 int gserial_connect(struct gserial *gser, u8 port_num)
1216 struct gs_port *port;
1217 unsigned long flags;
1218 int status;
1220 if (!gs_tty_driver || port_num >= n_ports)
1221 return -ENXIO;
1223 /* we "know" gserial_cleanup() hasn't been called */
1224 port = ports[port_num].port;
1226 /* activate the endpoints */
1227 status = usb_ep_enable(gser->in, gser->in_desc);
1228 if (status < 0)
1229 return status;
1230 gser->in->driver_data = port;
1232 status = usb_ep_enable(gser->out, gser->out_desc);
1233 if (status < 0)
1234 goto fail_out;
1235 gser->out->driver_data = port;
1237 /* then tell the tty glue that I/O can work */
1238 spin_lock_irqsave(&port->port_lock, flags);
1239 gser->ioport = port;
1240 port->port_usb = gser;
1242 /* REVISIT unclear how best to handle this state...
1243 * we don't really couple it with the Linux TTY.
1245 gser->port_line_coding = port->port_line_coding;
1247 /* REVISIT if waiting on "carrier detect", signal. */
1249 /* if it's already open, start I/O ... and notify the serial
1250 * protocol about open/close status (connect/disconnect).
1252 if (port->open_count) {
1253 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1254 gs_start_io(port);
1255 if (gser->connect)
1256 gser->connect(gser);
1257 } else {
1258 if (gser->disconnect)
1259 gser->disconnect(gser);
1262 spin_unlock_irqrestore(&port->port_lock, flags);
1264 return status;
1266 fail_out:
1267 usb_ep_disable(gser->in);
1268 gser->in->driver_data = NULL;
1269 return status;
1273 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1274 * @gser: the function, on which gserial_connect() was called
1275 * Context: any (usually from irq)
1277 * This is called to deactivate endpoints and let the TTY layer know
1278 * that the connection went inactive ... not unlike "hangup".
1280 * On return, the state is as if gserial_connect() had never been called;
1281 * there is no active USB I/O on these endpoints.
1283 void gserial_disconnect(struct gserial *gser)
1285 struct gs_port *port = gser->ioport;
1286 unsigned long flags;
1288 if (!port)
1289 return;
1291 /* tell the TTY glue not to do I/O here any more */
1292 spin_lock_irqsave(&port->port_lock, flags);
1294 /* REVISIT as above: how best to track this? */
1295 port->port_line_coding = gser->port_line_coding;
1297 port->port_usb = NULL;
1298 gser->ioport = NULL;
1299 if (port->open_count > 0 || port->openclose) {
1300 wake_up_interruptible(&port->drain_wait);
1301 if (port->port_tty)
1302 tty_hangup(port->port_tty);
1304 spin_unlock_irqrestore(&port->port_lock, flags);
1306 /* disable endpoints, aborting down any active I/O */
1307 usb_ep_disable(gser->out);
1308 gser->out->driver_data = NULL;
1310 usb_ep_disable(gser->in);
1311 gser->in->driver_data = NULL;
1313 /* finally, free any unused/unusable I/O buffers */
1314 spin_lock_irqsave(&port->port_lock, flags);
1315 if (port->open_count == 0 && !port->openclose)
1316 gs_buf_free(&port->port_write_buf);
1317 gs_free_requests(gser->out, &port->read_pool);
1318 gs_free_requests(gser->out, &port->read_queue);
1319 gs_free_requests(gser->in, &port->write_pool);
1320 spin_unlock_irqrestore(&port->port_lock, flags);