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 <ubi_uboot.h>
30 #include <linux/mtd/compat.h>
31 #include <linux/list.h>
35 #define pr_warning(fmt, args...) printf(fmt, ##args)
39 * This component encapsulates the TTY layer glue needed to provide basic
40 * "serial port" functionality through the USB gadget stack. Each such
41 * port is exposed through a /dev/ttyGS* node.
43 * After initialization (gserial_setup), these TTY port devices stay
44 * available until they are removed (gserial_cleanup). Each one may be
45 * connected to a USB function (gserial_connect), or disconnected (with
46 * gserial_disconnect) when the USB host issues a config change event.
47 * Data can only flow when the port is connected to the host.
49 * A given TTY port can be made available in multiple configurations.
50 * For example, each one might expose a ttyGS0 node which provides a
51 * login application. In one case that might use CDC ACM interface 0,
52 * while another configuration might use interface 3 for that. The
53 * work to handle that (including descriptor management) is not part
56 * Configurations may expose more than one TTY port. For example, if
57 * ttyGS0 provides login service, then ttyGS1 might provide dialer access
58 * for a telephone or fax link. And ttyGS2 might be something that just
59 * needs a simple byte stream interface for some messaging protocol that
60 * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
63 #define PREFIX "ttyGS"
66 * gserial is the lifecycle interface, used by USB functions
67 * gs_port is the I/O nexus, used by the tty driver
68 * tty_struct links to the tty/filesystem framework
70 * gserial <---> gs_port ... links will be null when the USB link is
71 * inactive; managed by gserial_{connect,disconnect}(). each gserial
72 * instance can wrap its own USB control protocol.
73 * gserial->ioport == usb_ep->driver_data ... gs_port
74 * gs_port->port_usb ... gserial
76 * gs_port <---> tty_struct ... links will be null when the TTY file
77 * isn't opened; managed by gs_open()/gs_close()
78 * gserial->port_tty ... tty_struct
79 * tty_struct->driver_data ... gserial
82 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
83 * next layer of buffering. For TX that's a circular buffer; for RX
84 * consider it a NOP. A third layer is provided by the TTY code.
87 #define WRITE_BUF_SIZE 8192 /* TX only */
98 * The port structure holds info for each port, one for each minor number
99 * (and thus for each /dev/ node).
102 spinlock_t port_lock; /* guard port_* access */
104 struct gserial *port_usb;
105 //struct tty_struct *port_tty;
108 bool openclose; /* open/close in progress */
111 wait_queue_head_t close_wait; /* wait for last close */
113 struct list_head read_pool;
116 struct list_head read_queue;
118 //struct tasklet_struct push;
120 struct list_head write_pool;
123 struct gs_buf port_write_buf;
124 wait_queue_head_t drain_wait; /* wait while writes drain */
126 /* REVISIT this state ... */
127 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
130 /* increase N_PORTS if you need more */
132 static struct portmaster {
133 struct mutex lock; /* protect open/close */
134 struct gs_port *port;
136 static unsigned n_ports;
138 #define GS_CLOSE_TIMEOUT 15 /* seconds */
142 #define pr_vdebug(fmt, arg...) \
145 #define pr_vdebug(fmt, arg...) \
146 ({ if (0) pr_debug(fmt, ##arg); })
149 /*-------------------------------------------------------------------------*/
151 /* Circular Buffer */
156 * Allocate a circular buffer and all associated memory.
158 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
160 gb->buf_buf = kmalloc(size, GFP_KERNEL);
161 if (gb->buf_buf == NULL)
165 gb->buf_put = gb->buf_buf;
166 gb->buf_get = gb->buf_buf;
174 * Free the buffer and all associated memory.
176 static void gs_buf_free(struct gs_buf *gb)
185 * Clear out all data in the circular buffer.
187 static void gs_buf_clear(struct gs_buf *gb)
189 gb->buf_get = gb->buf_put;
190 /* equivalent to a get of all data available */
196 * Return the number of bytes of data written into the circular
199 static unsigned gs_buf_data_avail(struct gs_buf *gb)
201 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
207 * Return the number of bytes of space available in the circular
210 static unsigned gs_buf_space_avail(struct gs_buf *gb)
212 return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
218 * Copy data data from a user buffer and put it into the circular buffer.
219 * Restrict to the amount of space available.
221 * Return the number of bytes copied.
224 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
228 len = gs_buf_space_avail(gb);
235 len = gb->buf_buf + gb->buf_size - gb->buf_put;
237 memcpy(gb->buf_put, buf, len);
238 memcpy(gb->buf_buf, buf+len, count - len);
239 gb->buf_put = gb->buf_buf + count - len;
241 memcpy(gb->buf_put, buf, count);
243 gb->buf_put += count;
244 else /* count == len */
245 gb->buf_put = gb->buf_buf;
254 * Get data from the circular buffer and copy to the given buffer.
255 * Restrict to the amount of data available.
257 * Return the number of bytes copied.
260 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
264 len = gs_buf_data_avail(gb);
271 len = gb->buf_buf + gb->buf_size - gb->buf_get;
273 memcpy(buf, gb->buf_get, len);
274 memcpy(buf+len, gb->buf_buf, count - len);
275 gb->buf_get = gb->buf_buf + count - len;
277 memcpy(buf, gb->buf_get, count);
279 gb->buf_get += count;
280 else /* count == len */
281 gb->buf_get = gb->buf_buf;
287 /*-------------------------------------------------------------------------*/
289 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
294 * Allocate a usb_request and its buffer. Returns a pointer to the
295 * usb_request or NULL if there is an error.
298 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
300 struct usb_request *req;
302 req = usb_ep_alloc_request(ep, kmalloc_flags);
306 req->buf = kmalloc(len, kmalloc_flags);
307 if (req->buf == NULL) {
308 usb_ep_free_request(ep, req);
319 * Free a usb_request and its buffer.
321 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
324 usb_ep_free_request(ep, req);
330 * If there is data to send, a packet is built in the given
331 * buffer and the size is returned. If there is no data to
332 * send, 0 is returned.
334 * Called with port_lock held.
337 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
341 len = gs_buf_data_avail(&port->port_write_buf);
345 size = gs_buf_get(&port->port_write_buf, packet, size);
352 * This function finds available write requests, calls
353 * gs_send_packet to fill these packets with data, and
354 * continues until either there are no more write requests
355 * available or no more data to send. This function is
356 * run whenever data arrives or write requests are available.
358 * Context: caller owns port_lock; port_usb is non-null.
360 static int gs_start_tx(struct gs_port *port)
362 __releases(&port->port_lock)
363 __acquires(&port->port_lock)
366 struct list_head *pool = &port->write_pool;
367 struct usb_ep *in = NULL;
369 bool do_tty_wake = false;
371 if (!port->port_usb){
374 in = port->port_usb->in;
376 while (!list_empty(pool)) {
377 struct usb_request *req;
380 if (port->write_started >= QUEUE_SIZE)
383 req = list_entry(pool->next, struct usb_request, list);
384 len = gs_send_packet(port, req->buf, in->maxpacket);
386 wake_up_interruptible(&port->drain_wait);
392 list_del(&req->list);
393 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
395 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
396 port->port_num, len, *((u8 *)req->buf),
397 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
399 /* Drop lock while we call out of driver; completions
400 * could be issued while we do so. Disconnection may
401 * happen too; maybe immediately before we queue this!
403 * NOTE that we may keep sending data for a while after
404 * the TTY closed (dev->ioport->port_tty is NULL).
406 spin_unlock(&port->port_lock);
407 status = usb_ep_queue(in, req, GFP_ATOMIC);
408 spin_lock(&port->port_lock);
411 pr_debug("%s: %s %s err %d\n",
412 __func__, "queue", in->name, status);
413 list_add(&req->list, pool);
417 port->write_started++;
419 /* abort immediately after disconnect */
420 if (!port->port_usb){
425 //if (do_tty_wake && port->port_tty)
426 // tty_wakeup(port->port_tty);
431 * Context: caller owns port_lock, and port_usb is set
433 static unsigned gs_start_rx(struct gs_port *port)
435 __releases(&port->port_lock)
436 __acquires(&port->port_lock)
439 struct list_head *pool = &port->read_pool;
440 struct usb_ep *out = NULL;
441 if (!port->port_usb){
444 out = port->port_usb->out;
445 while (!list_empty(pool)) {
446 struct usb_request *req;
449 struct tty_struct *tty;
451 /* no more rx if closed */
452 tty = port->port_tty;
456 if (port->read_started >= QUEUE_SIZE)
459 req = list_entry(pool->next, struct usb_request, list);
460 list_del(&req->list);
461 req->length = out->maxpacket;
463 /* drop lock while we call out; the controller driver
464 * may need to call us back (e.g. for disconnect)
466 spin_unlock(&port->port_lock);
467 status = usb_ep_queue(out, req, GFP_ATOMIC);
468 spin_lock(&port->port_lock);
471 pr_debug("%s: %s %s err %d\n",
472 __func__, "queue", out->name, status);
473 list_add(&req->list, pool);
476 port->read_started++;
478 /* abort immediately after disconnect */
479 if (!port->port_usb){
483 return port->read_started;
487 * RX tasklet takes data out of the RX queue and hands it up to the TTY
488 * layer until it refuses to take any more data (or is throttled back).
489 * Then it issues reads for any further data.
491 * If the RX queue becomes full enough that no usb_request is queued,
492 * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
493 * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
494 * can be buffered before the TTY layer's buffers (currently 64 KB).
497 static void gs_rx_push(unsigned long _port)
499 struct gs_port *port = (void *)_port;
500 //struct tty_struct *tty;
501 struct list_head *queue = &port->read_queue;
502 bool disconnect = false;
503 bool do_push = false;
505 /* hand any queued data to the tty */
506 spin_lock_irq(&port->port_lock);
507 tty = port->port_tty;
508 while (!list_empty(queue)) {
509 struct usb_request *req;
511 req = list_first_entry(queue, struct usb_request, list);
513 /* discard data if tty was closed */
517 /* leave data queued if tty was rx throttled */
518 if (test_bit(TTY_THROTTLED, &tty->flags))
521 switch (req->status) {
524 pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
528 /* presumably a transient fault */
529 pr_warning(PREFIX "%d: unexpected RX status %d\n",
530 port->port_num, req->status);
533 /* normal completion */
537 /* push data to (open) tty */
539 char *packet = req->buf;
540 unsigned size = req->actual;
544 /* we may have pushed part of this packet already... */
551 count = tty_insert_flip_string(tty, packet, size);
555 /* stop pushing; TTY layer can't handle more */
556 port->n_read += count;
557 pr_vdebug(PREFIX "%d: rx block %d/%d\n",
565 list_move(&req->list, &port->read_pool);
566 port->read_started--;
569 /* Push from tty to ldisc; without low_latency set this is handled by
570 * a workqueue, so we won't get callbacks and can hold port_lock
572 if (tty && do_push) {
573 tty_flip_buffer_push(tty);
577 /* We want our data queue to become empty ASAP, keeping data
578 * in the tty and ldisc (not here). If we couldn't push any
579 * this time around, there may be trouble unless there's an
580 * implicit tty_unthrottle() call on its way...
582 * REVISIT we should probably add a timer to keep the tasklet
583 * from starving ... but it's not clear that case ever happens.
585 if (!list_empty(queue) && tty) {
586 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
588 tasklet_schedule(&port->push);
590 pr_warning(PREFIX "%d: RX not scheduled?\n",
595 /* If we're still connected, refill the USB RX queue. */
596 if (!disconnect && port->port_usb)
599 spin_unlock_irq(&port->port_lock);
601 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
603 struct gs_port *port = ep->driver_data;
605 /* Queue all received data until the tty layer is ready for it. */
606 spin_lock(&port->port_lock);
607 list_add_tail(&req->list, &port->read_queue);
608 //tasklet_schedule(&port->push);
609 spin_unlock(&port->port_lock);
612 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
614 struct gs_port *port = ep->driver_data;
616 spin_lock(&port->port_lock);
617 list_add(&req->list, &port->write_pool);
618 port->write_started--;
620 switch (req->status) {
622 /* presumably a transient fault */
623 printf("%s: unexpected %s status %d\n",
624 __func__, ep->name, req->status);
627 /* normal completion */
633 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
637 spin_unlock(&port->port_lock);
643 int usb_trans_status;
644 static int gs_start_io(struct gs_port *port);
649 struct gs_port *port = ports[vcom_port].port;
650 if (port->port_write_buf.buf_buf == NULL) {
651 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
653 printf("gs_open: gs_buf_alloc failed\n");
657 /* if connected, start the I/O stream */
658 if (port->port_usb) {
659 struct gserial *gser = port->port_usb;
661 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
668 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
675 struct gs_port *port = ports[vcom_port].port;
676 struct gserial *gser;
678 spin_lock_irq(&port->port_lock);
680 if (port->open_count != 1) {
681 if (port->open_count == 0)
688 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
690 /* mark port as closing but in use; we can drop port lock
691 * and sleep if necessary
693 port->openclose = true;
694 port->open_count = 0;
696 gser = port->port_usb;
697 if (gser && gser->disconnect)
698 gser->disconnect(gser);
700 /* wait for circular write buffer to drain, disconnect, or at
701 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
703 if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
704 spin_unlock_irq(&port->port_lock);
705 // waitV_event_interruptible_timeout(port->drain_wait,
706 // gs_writes_finished(port),
707 // GS_CLOSE_TIMEOUT * HZ);
708 spin_lock_irq(&port->port_lock);
709 gser = port->port_usb;
712 /* Iff we're disconnected, there can be no I/O in flight so it's
713 * ok to free the circular buffer; else just scrub it. And don't
714 * let the push tasklet fire again until we're re-opened.
717 gs_buf_free(&port->port_write_buf);
719 gs_buf_clear(&port->port_write_buf);
721 //tty->driver_data = NULL;
722 //port->port_tty = NULL;
724 port->openclose = false;
726 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
727 port->port_num, tty, file);
729 //wake_up_interruptible(&port->close_wait);
731 spin_unlock_irq(&port->port_lock);
734 //buf: the buf address where data put
735 //*count: read length wanted, when return store actually read count
736 //return: weather read really done
737 int gs_read(const unsigned char *buf, int *count)
739 struct gs_port *port = ports[vcom_port].port;
740 struct list_head *queue = &port->read_queue;
741 bool disconnect = false;
742 bool do_push = false;
744 if (!list_empty(queue)) {
745 struct usb_request *req;
747 req = list_first_entry(queue, struct usb_request, list);
748 switch (req->status) {
751 pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
755 /* presumably a transient fault */
756 printf(PREFIX "%d: unexpected RX status %d\n",
757 port->port_num, req->status);
760 /* normal completion */
765 char *packet = req->buf;
766 unsigned size = req->actual;
770 /* we may have pushed part of this packet already... */
779 memcpy(buf, packet, size);
782 memcpy(buf, packet, *count);
783 port->n_read += *count;
789 list_move(&req->list, &port->read_pool);
790 port->read_started--;
792 /* If we're still connected, refill the USB RX queue. */
793 if (!disconnect && port->port_usb)
800 buf: date buffer address which store the data want send
801 count: the data count stored in buf
802 return: the data send count
804 int gs_write(const unsigned char *buf, int count)
806 struct gs_port *port = ports[vcom_port].port;
808 count = gs_buf_put(&port->port_write_buf, buf, count);
809 /* treat count == 0 as flush_chars() */
811 usb_trans_status = gs_start_tx(port);
815 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
817 struct gs_port *port = ep->driver_data;
819 /* Queue all received data until the tty layer is ready for it. */
820 spin_lock(&port->port_lock);
821 list_add_tail(&req->list, &port->read_queue);
823 usb_trans_status = req->status;
824 //tasklet_schedule(&port->push);
825 spin_unlock(&port->port_lock);
828 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
830 struct gs_port *port = ep->driver_data;
832 spin_lock(&port->port_lock);
833 list_add(&req->list, &port->write_pool);
834 port->write_started--;
836 switch (req->status) {
838 /* presumably a transient fault */
839 printf("%s: unexpected %s status %d\n",
840 __func__, ep->name, req->status);
843 /* normal completion */
849 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
854 usb_trans_status = req->status;
856 spin_unlock(&port->port_lock);
859 wait the read or write done
860 direct: 1 for output, 0 for input
862 extern int usb_gadget_handle_interrupts(void);
863 void usb_wait_trans_done(int direct)
866 while(!usb_write_done)
867 usb_gadget_handle_interrupts();
870 while(!usb_read_done)
871 usb_gadget_handle_interrupts();
875 int usb_is_trans_done(int direct)
879 usb_gadget_handle_interrupts();
886 usb_gadget_handle_interrupts();
895 extern int usb_serial_configed;
896 int usb_is_configured(void)
898 if(!usb_serial_configed)
899 usb_gadget_handle_interrupts();
901 return usb_serial_configed;
904 extern int usb_port_open;
905 int usb_is_port_open(void)
908 usb_gadget_handle_interrupts();
910 return usb_port_open;
914 static void gs_free_requests(struct usb_ep *ep, struct list_head *head,
917 struct usb_request *req;
919 while (!list_empty(head)) {
920 req = list_entry(head->next, struct usb_request, list);
921 list_del(&req->list);
922 gs_free_req(ep, req);
928 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
929 void (*fn)(struct usb_ep *, struct usb_request *),
933 struct usb_request *req;
934 int n = allocated ? QUEUE_SIZE - *allocated : QUEUE_SIZE;
936 /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
937 * do quite that many this time, don't fail ... we just won't
938 * be as speedy as we might otherwise be.
940 for (i = 0; i < n; i++) {
941 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
943 return list_empty(head) ? -ENOMEM : 0;
945 list_add_tail(&req->list, head);
953 * gs_start_io - start USB I/O streams
954 * @dev: encapsulates endpoints to use
955 * Context: holding port_lock; port_tty and port_usb are non-null
957 * We only start I/O when something is connected to both sides of
958 * this port. If nothing is listening on the host side, we may
959 * be pointlessly filling up our TX buffers and FIFO.
961 static int gs_start_io(struct gs_port *port)
963 struct list_head *head = &port->read_pool;
964 struct usb_ep *ep = port->port_usb->out;
968 /* Allocate RX and TX I/O buffers. We can't easily do this much
969 * earlier (with GFP_KERNEL) because the requests are coupled to
970 * endpoints, as are the packet sizes we'll be using. Different
971 * configurations may use different endpoints with a given port;
972 * and high speed vs full speed changes packet sizes too.
974 status = gs_alloc_requests(ep, head, gs_read_complete,
975 &port->read_allocated);
979 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
980 gs_write_complete, &port->write_allocated);
982 gs_free_requests(ep, head, &port->read_allocated);
986 /* queue read requests */
988 started = gs_start_rx(port);
990 /* unblock any pending writes into our circular buffer */
992 //tty_wakeup(port->port_tty);
994 gs_free_requests(ep, head, &port->read_allocated);
995 gs_free_requests(port->port_usb->in, &port->write_pool,
996 &port->write_allocated);
1003 /*-------------------------------------------------------------------------*/
1008 * gs_open sets up the link between a gs_port and its associated TTY.
1009 * That link is broken *only* by TTY close(), and all driver methods
1013 static int gs_open(struct tty_struct *tty, struct file *file)
1015 int port_num = tty->index;
1016 struct gs_port *port;
1019 if (port_num < 0 || port_num >= n_ports)
1023 mutex_lock(&ports[port_num].lock);
1024 port = ports[port_num].port;
1028 spin_lock_irq(&port->port_lock);
1030 /* already open? Great. */
1031 if (port->open_count) {
1035 /* currently opening/closing? wait ... */
1036 } else if (port->openclose) {
1039 /* ... else we do the work */
1042 port->openclose = true;
1044 spin_unlock_irq(&port->port_lock);
1046 mutex_unlock(&ports[port_num].lock);
1053 /* must do the work */
1056 /* wait for EAGAIN task to finish */
1058 /* REVISIT could have a waitchannel here, if
1059 * concurrent open performance is important
1063 } while (status != -EAGAIN);
1065 /* Do the "real open" */
1066 spin_lock_irq(&port->port_lock);
1068 /* allocate circular buffer on first open */
1069 if (port->port_write_buf.buf_buf == NULL) {
1071 spin_unlock_irq(&port->port_lock);
1072 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
1073 spin_lock_irq(&port->port_lock);
1076 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
1077 port->port_num, tty, file);
1078 port->openclose = false;
1079 goto exit_unlock_port;
1083 /* REVISIT if REMOVED (ports[].port NULL), abort the open
1084 * to let rmmod work faster (but this way isn't wrong).
1087 /* REVISIT maybe wait for "carrier detect" */
1089 tty->driver_data = port;
1090 port->port_tty = tty;
1092 port->open_count = 1;
1093 port->openclose = false;
1095 /* if connected, start the I/O stream */
1096 if (port->port_usb) {
1097 struct gserial *gser = port->port_usb;
1099 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
1103 gser->connect(gser);
1106 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
1111 spin_unlock_irq(&port->port_lock);
1115 static int gs_writes_finished(struct gs_port *p)
1119 /* return true on disconnect or empty buffer */
1120 spin_lock_irq(&p->port_lock);
1121 cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
1122 spin_unlock_irq(&p->port_lock);
1127 static void gs_close(struct tty_struct *tty, struct file *file)
1129 struct gs_port *port = tty->driver_data;
1130 struct gserial *gser;
1132 spin_lock_irq(&port->port_lock);
1134 if (port->open_count != 1) {
1135 if (port->open_count == 0)
1142 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
1144 /* mark port as closing but in use; we can drop port lock
1145 * and sleep if necessary
1147 port->openclose = true;
1148 port->open_count = 0;
1150 gser = port->port_usb;
1151 if (gser && gser->disconnect)
1152 gser->disconnect(gser);
1154 /* wait for circular write buffer to drain, disconnect, or at
1155 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
1157 if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
1158 spin_unlock_irq(&port->port_lock);
1159 wait_event_interruptible_timeout(port->drain_wait,
1160 gs_writes_finished(port),
1161 GS_CLOSE_TIMEOUT * HZ);
1162 spin_lock_irq(&port->port_lock);
1163 gser = port->port_usb;
1166 /* Iff we're disconnected, there can be no I/O in flight so it's
1167 * ok to free the circular buffer; else just scrub it. And don't
1168 * let the push tasklet fire again until we're re-opened.
1171 gs_buf_free(&port->port_write_buf);
1173 gs_buf_clear(&port->port_write_buf);
1175 tty->driver_data = NULL;
1176 port->port_tty = NULL;
1178 port->openclose = false;
1180 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
1181 port->port_num, tty, file);
1183 wake_up_interruptible(&port->close_wait);
1185 spin_unlock_irq(&port->port_lock);
1188 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
1190 struct gs_port *port = tty->driver_data;
1191 unsigned long flags;
1194 pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
1195 port->port_num, tty, count);
1197 spin_lock_irqsave(&port->port_lock, flags);
1199 count = gs_buf_put(&port->port_write_buf, buf, count);
1200 /* treat count == 0 as flush_chars() */
1202 status = gs_start_tx(port);
1203 spin_unlock_irqrestore(&port->port_lock, flags);
1208 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
1210 struct gs_port *port = tty->driver_data;
1211 unsigned long flags;
1214 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
1215 port->port_num, tty, ch, __builtin_return_address(0));
1217 spin_lock_irqsave(&port->port_lock, flags);
1218 status = gs_buf_put(&port->port_write_buf, &ch, 1);
1219 spin_unlock_irqrestore(&port->port_lock, flags);
1224 static void gs_flush_chars(struct tty_struct *tty)
1226 struct gs_port *port = tty->driver_data;
1227 unsigned long flags;
1229 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
1231 spin_lock_irqsave(&port->port_lock, flags);
1234 spin_unlock_irqrestore(&port->port_lock, flags);
1237 static int gs_write_room(struct tty_struct *tty)
1239 struct gs_port *port = tty->driver_data;
1240 unsigned long flags;
1243 spin_lock_irqsave(&port->port_lock, flags);
1245 room = gs_buf_space_avail(&port->port_write_buf);
1246 spin_unlock_irqrestore(&port->port_lock, flags);
1248 pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
1249 port->port_num, tty, room);
1254 static int gs_chars_in_buffer(struct tty_struct *tty)
1256 struct gs_port *port = tty->driver_data;
1257 unsigned long flags;
1260 spin_lock_irqsave(&port->port_lock, flags);
1261 chars = gs_buf_data_avail(&port->port_write_buf);
1262 spin_unlock_irqrestore(&port->port_lock, flags);
1264 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
1265 port->port_num, tty, chars);
1270 /* undo side effects of setting TTY_THROTTLED */
1271 static void gs_unthrottle(struct tty_struct *tty)
1273 struct gs_port *port = tty->driver_data;
1274 unsigned long flags;
1276 spin_lock_irqsave(&port->port_lock, flags);
1277 if (port->port_usb) {
1278 /* Kickstart read queue processing. We don't do xon/xoff,
1279 * rts/cts, or other handshaking with the host, but if the
1280 * read queue backs up enough we'll be NAKing OUT packets.
1282 tasklet_schedule(&port->push);
1283 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
1285 spin_unlock_irqrestore(&port->port_lock, flags);
1288 static int gs_break_ctl(struct tty_struct *tty, int duration)
1290 struct gs_port *port = tty->driver_data;
1292 struct gserial *gser;
1294 pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
1295 port->port_num, duration);
1297 spin_lock_irq(&port->port_lock);
1298 gser = port->port_usb;
1299 if (gser && gser->send_break)
1300 status = gser->send_break(gser, duration);
1301 spin_unlock_irq(&port->port_lock);
1306 static const struct tty_operations gs_tty_ops = {
1310 .put_char = gs_put_char,
1311 .flush_chars = gs_flush_chars,
1312 .write_room = gs_write_room,
1313 .chars_in_buffer = gs_chars_in_buffer,
1314 .unthrottle = gs_unthrottle,
1315 .break_ctl = gs_break_ctl,
1319 /*-------------------------------------------------------------------------*/
1321 //static struct tty_driver *gs_tty_driver;
1324 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1326 struct gs_port *port;
1328 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1332 spin_lock_init(&port->port_lock);
1333 init_waitqueue_head(&port->close_wait);
1334 init_waitqueue_head(&port->drain_wait);
1336 //tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1338 INIT_LIST_HEAD(&port->read_pool);
1339 INIT_LIST_HEAD(&port->read_queue);
1340 INIT_LIST_HEAD(&port->write_pool);
1342 port->port_num = port_num;
1343 port->port_line_coding = *coding;
1345 ports[port_num].port = port;
1351 * gserial_setup - initialize TTY driver for one or more ports
1352 * @g: gadget to associate with these ports
1353 * @count: how many ports to support
1354 * Context: may sleep
1356 * The TTY stack needs to know in advance how many devices it should
1357 * plan to manage. Use this call to set up the ports you will be
1358 * exporting through USB. Later, connect them to functions based
1359 * on what configuration is activated by the USB host; and disconnect
1360 * them as appropriate.
1362 * An example would be a two-configuration device in which both
1363 * configurations expose port 0, but through different functions.
1364 * One configuration could even expose port 1 while the other
1367 * Returns negative errno or zero.
1369 int __init gserial_setup(struct usb_gadget *g, unsigned count)
1372 struct usb_cdc_line_coding coding;
1375 if (count == 0 || count > N_PORTS)
1379 gs_tty_driver = alloc_tty_driver(count);
1383 gs_tty_driver->owner = THIS_MODULE;
1384 gs_tty_driver->driver_name = "g_serial";
1385 gs_tty_driver->name = PREFIX;
1386 /* uses dynamically assigned dev_t values */
1388 gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1389 gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1390 gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1391 gs_tty_driver->init_termios = tty_std_termios;
1393 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1394 * MS-Windows. Otherwise, most of these flags shouldn't affect
1395 * anything unless we were to actually hook up to a serial line.
1397 gs_tty_driver->init_termios.c_cflag =
1398 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1399 gs_tty_driver->init_termios.c_ispeed = 9600;
1400 gs_tty_driver->init_termios.c_ospeed = 9600;
1402 coding.dwDTERate = cpu_to_le32(9600);
1403 coding.bCharFormat = 8;
1404 coding.bParityType = USB_CDC_NO_PARITY;
1405 coding.bDataBits = USB_CDC_1_STOP_BITS;
1407 tty_set_operations(gs_tty_driver, &gs_tty_ops);
1410 memset(&coding,0,sizeof(struct usb_cdc_line_coding));
1411 /* make devices be openable */
1412 for (i = 0; i < count; i++) {
1413 mutex_init(&ports[i].lock);
1414 status = gs_port_alloc(i, &coding);
1422 /* export the driver ... */
1424 status = tty_register_driver(gs_tty_driver);
1426 pr_err("%s: cannot register, err %d\n",
1432 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1433 for (i = 0; i < count; i++) {
1434 struct device *tty_dev;
1436 tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
1437 if (IS_ERR(tty_dev))
1438 pr_warning("%s: no classdev for port %d, err %ld\n",
1439 __func__, i, PTR_ERR(tty_dev));
1442 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1443 count, (count == 1) ? "" : "s");
1449 kfree(ports[count].port);
1450 //put_tty_driver(gs_tty_driver);
1451 //gs_tty_driver = NULL;
1456 static int gs_closed(struct gs_port *port)
1460 spin_lock_irq(&port->port_lock);
1461 cond = (port->open_count == 0) && !port->openclose;
1462 spin_unlock_irq(&port->port_lock);
1467 * gserial_cleanup - remove TTY-over-USB driver and devices
1468 * Context: may sleep
1470 * This is called to free all resources allocated by @gserial_setup().
1471 * Accordingly, it may need to wait until some open /dev/ files have
1474 * The caller must have issued @gserial_disconnect() for any ports
1475 * that had previously been connected, so that there is never any
1476 * I/O pending when it's called.
1478 void gserial_cleanup(void)
1481 struct gs_port *port;
1487 /* start sysfs and /dev/ttyGS* node removal */
1488 for (i = 0; i < n_ports; i++)
1489 tty_unregister_device(gs_tty_driver, i);
1491 for (i = 0; i < n_ports; i++) {
1492 /* prevent new opens */
1493 mutex_lock(&ports[i].lock);
1494 port = ports[i].port;
1495 ports[i].port = NULL;
1496 mutex_unlock(&ports[i].lock);
1498 // tasklet_kill(&port->push);
1500 /* wait for old opens to finish */
1501 // wait_event(port->close_wait, gs_closed(port));
1503 //WARN_ON(port->port_usb != NULL);
1509 // tty_unregister_driver(gs_tty_driver);
1510 // put_tty_driver(gs_tty_driver);
1511 // gs_tty_driver = NULL;
1513 pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1517 * gserial_connect - notify TTY I/O glue that USB link is active
1518 * @gser: the function, set up with endpoints and descriptors
1519 * @port_num: which port is active
1520 * Context: any (usually from irq)
1522 * This is called activate endpoints and let the TTY layer know that
1523 * the connection is active ... not unlike "carrier detect". It won't
1524 * necessarily start I/O queues; unless the TTY is held open by any
1525 * task, there would be no point. However, the endpoints will be
1526 * activated so the USB host can perform I/O, subject to basic USB
1527 * hardware flow control.
1529 * Caller needs to have set up the endpoints and USB function in @dev
1530 * before calling this, as well as the appropriate (speed-specific)
1531 * endpoint descriptors, and also have set up the TTY driver by calling
1534 * Returns negative errno or zero.
1535 * On success, ep->driver_data will be overwritten.
1537 int gserial_connect(struct gserial *gser, u8 port_num)
1539 struct gs_port *port;
1540 unsigned long flags;
1543 if (!gs_tty_driver || port_num >= n_ports)
1546 if (port_num >= n_ports)
1551 /* we "know" gserial_cleanup() hasn't been called */
1552 port = ports[port_num].port;
1554 /* activate the endpoints */
1555 status = usb_ep_enable(gser->in, gser->in_desc);
1558 gser->in->driver_data = port;
1560 status = usb_ep_enable(gser->out, gser->out_desc);
1563 gser->out->driver_data = port;
1565 /* then tell the tty glue that I/O can work */
1566 spin_lock_irqsave(&port->port_lock, flags);
1567 gser->ioport = port;
1568 port->port_usb = gser;
1570 /* REVISIT unclear how best to handle this state...
1571 * we don't really couple it with the Linux TTY.
1573 gser->port_line_coding = port->port_line_coding;
1575 /* REVISIT if waiting on "carrier detect", signal. */
1577 /* if it's already open, start I/O ... and notify the serial
1578 * protocol about open/close status (connect/disconnect).
1580 if (port->open_count) {
1581 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1584 gser->connect(gser);
1586 if (gser->disconnect)
1587 gser->disconnect(gser);
1590 spin_unlock_irqrestore(&port->port_lock, flags);
1595 usb_ep_disable(gser->in);
1596 gser->in->driver_data = NULL;
1601 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1602 * @gser: the function, on which gserial_connect() was called
1603 * Context: any (usually from irq)
1605 * This is called to deactivate endpoints and let the TTY layer know
1606 * that the connection went inactive ... not unlike "hangup".
1608 * On return, the state is as if gserial_connect() had never been called;
1609 * there is no active USB I/O on these endpoints.
1611 void gserial_disconnect(struct gserial *gser)
1613 struct gs_port *port = gser->ioport;
1614 unsigned long flags;
1619 /* tell the TTY glue not to do I/O here any more */
1620 spin_lock_irqsave(&port->port_lock, flags);
1622 /* REVISIT as above: how best to track this? */
1623 port->port_line_coding = gser->port_line_coding;
1625 port->port_usb = NULL;
1626 gser->ioport = NULL;
1627 if (port->open_count > 0 || port->openclose) {
1628 wake_up_interruptible(&port->drain_wait);
1629 //if (port->port_tty)
1630 // tty_hangup(port->port_tty);
1632 spin_unlock_irqrestore(&port->port_lock, flags);
1634 /* disable endpoints, aborting down any active I/O */
1635 usb_ep_disable(gser->out);
1636 gser->out->driver_data = NULL;
1638 usb_ep_disable(gser->in);
1639 gser->in->driver_data = NULL;
1641 /* finally, free any unused/unusable I/O buffers */
1642 spin_lock_irqsave(&port->port_lock, flags);
1643 if (port->open_count == 0 && !port->openclose)
1644 gs_buf_free(&port->port_write_buf);
1645 gs_free_requests(gser->out, &port->read_pool, NULL);
1646 gs_free_requests(gser->out, &port->read_queue, NULL);
1647 gs_free_requests(gser->in, &port->write_pool, NULL);
1649 port->read_allocated = port->read_started =
1650 port->write_allocated = port->write_started = 0;
1652 spin_unlock_irqrestore(&port->port_lock, flags);
1654 void gs_reset_usb_param(void)
1659 usb_trans_status = 0;
1660 usb_serial_configed = 0;