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)
38 #ifndef __maybe_unused
39 #define __maybe_unused __attribute__((unused))
43 * This component encapsulates the TTY layer glue needed to provide basic
44 * "serial port" functionality through the USB gadget stack. Each such
45 * port is exposed through a /dev/ttyGS* node.
47 * After initialization (gserial_setup), these TTY port devices stay
48 * available until they are removed (gserial_cleanup). Each one may be
49 * connected to a USB function (gserial_connect), or disconnected (with
50 * gserial_disconnect) when the USB host issues a config change event.
51 * Data can only flow when the port is connected to the host.
53 * A given TTY port can be made available in multiple configurations.
54 * For example, each one might expose a ttyGS0 node which provides a
55 * login application. In one case that might use CDC ACM interface 0,
56 * while another configuration might use interface 3 for that. The
57 * work to handle that (including descriptor management) is not part
60 * Configurations may expose more than one TTY port. For example, if
61 * ttyGS0 provides login service, then ttyGS1 might provide dialer access
62 * for a telephone or fax link. And ttyGS2 might be something that just
63 * needs a simple byte stream interface for some messaging protocol that
64 * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
67 #define PREFIX "ttyGS"
70 * gserial is the lifecycle interface, used by USB functions
71 * gs_port is the I/O nexus, used by the tty driver
72 * tty_struct links to the tty/filesystem framework
74 * gserial <---> gs_port ... links will be null when the USB link is
75 * inactive; managed by gserial_{connect,disconnect}(). each gserial
76 * instance can wrap its own USB control protocol.
77 * gserial->ioport == usb_ep->driver_data ... gs_port
78 * gs_port->port_usb ... gserial
80 * gs_port <---> tty_struct ... links will be null when the TTY file
81 * isn't opened; managed by gs_open()/gs_close()
82 * gserial->port_tty ... tty_struct
83 * tty_struct->driver_data ... gserial
86 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
87 * next layer of buffering. For TX that's a circular buffer; for RX
88 * consider it a NOP. A third layer is provided by the TTY code.
91 #define WRITE_BUF_SIZE 8192 /* TX only */
102 * The port structure holds info for each port, one for each minor number
103 * (and thus for each /dev/ node).
106 spinlock_t port_lock; /* guard port_* access */
108 struct gserial *port_usb;
109 //struct tty_struct *port_tty;
112 bool openclose; /* open/close in progress */
115 wait_queue_head_t close_wait; /* wait for last close */
117 struct list_head read_pool;
120 struct list_head read_queue;
122 //struct tasklet_struct push;
124 struct list_head write_pool;
127 struct gs_buf port_write_buf;
128 wait_queue_head_t drain_wait; /* wait while writes drain */
130 /* REVISIT this state ... */
131 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
134 /* increase N_PORTS if you need more */
136 static struct portmaster {
137 struct mutex lock; /* protect open/close */
138 struct gs_port *port;
140 static unsigned n_ports;
142 #define GS_CLOSE_TIMEOUT 15 /* seconds */
146 #define pr_vdebug(fmt, arg...) \
149 #define pr_vdebug(fmt, arg...) \
150 ({ if (0) pr_debug(fmt, ##arg); })
153 /*-------------------------------------------------------------------------*/
155 /* Circular Buffer */
160 * Allocate a circular buffer and all associated memory.
162 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
164 gb->buf_buf = kmalloc(size, GFP_KERNEL);
165 if (gb->buf_buf == NULL)
169 gb->buf_put = gb->buf_buf;
170 gb->buf_get = gb->buf_buf;
178 * Free the buffer and all associated memory.
180 static void gs_buf_free(struct gs_buf *gb)
189 * Clear out all data in the circular buffer.
191 static void gs_buf_clear(struct gs_buf *gb)
193 gb->buf_get = gb->buf_put;
194 /* equivalent to a get of all data available */
200 * Return the number of bytes of data written into the circular
203 static unsigned gs_buf_data_avail(struct gs_buf *gb)
205 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
211 * Return the number of bytes of space available in the circular
214 static unsigned gs_buf_space_avail(struct gs_buf *gb)
216 return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
222 * Copy data data from a user buffer and put it into the circular buffer.
223 * Restrict to the amount of space available.
225 * Return the number of bytes copied.
228 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
232 len = gs_buf_space_avail(gb);
239 len = gb->buf_buf + gb->buf_size - gb->buf_put;
241 memcpy(gb->buf_put, buf, len);
242 memcpy(gb->buf_buf, buf+len, count - len);
243 gb->buf_put = gb->buf_buf + count - len;
245 memcpy(gb->buf_put, buf, count);
247 gb->buf_put += count;
248 else /* count == len */
249 gb->buf_put = gb->buf_buf;
258 * Get data from the circular buffer and copy to the given buffer.
259 * Restrict to the amount of data available.
261 * Return the number of bytes copied.
264 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
268 len = gs_buf_data_avail(gb);
275 len = gb->buf_buf + gb->buf_size - gb->buf_get;
277 memcpy(buf, gb->buf_get, len);
278 memcpy(buf+len, gb->buf_buf, count - len);
279 gb->buf_get = gb->buf_buf + count - len;
281 memcpy(buf, gb->buf_get, count);
283 gb->buf_get += count;
284 else /* count == len */
285 gb->buf_get = gb->buf_buf;
291 /*-------------------------------------------------------------------------*/
293 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
298 * Allocate a usb_request and its buffer. Returns a pointer to the
299 * usb_request or NULL if there is an error.
302 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
304 struct usb_request *req;
306 req = usb_ep_alloc_request(ep, kmalloc_flags);
310 req->buf = kmalloc(len, kmalloc_flags);
311 if (req->buf == NULL) {
312 usb_ep_free_request(ep, req);
323 * Free a usb_request and its buffer.
325 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
328 usb_ep_free_request(ep, req);
334 * If there is data to send, a packet is built in the given
335 * buffer and the size is returned. If there is no data to
336 * send, 0 is returned.
338 * Called with port_lock held.
341 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
345 len = gs_buf_data_avail(&port->port_write_buf);
349 size = gs_buf_get(&port->port_write_buf, packet, size);
356 * This function finds available write requests, calls
357 * gs_send_packet to fill these packets with data, and
358 * continues until either there are no more write requests
359 * available or no more data to send. This function is
360 * run whenever data arrives or write requests are available.
362 * Context: caller owns port_lock; port_usb is non-null.
364 static int gs_start_tx(struct gs_port *port)
366 __releases(&port->port_lock)
367 __acquires(&port->port_lock)
370 struct list_head *pool = &port->write_pool;
371 struct usb_ep *in = NULL;
374 if (!port->port_usb){
377 in = port->port_usb->in;
379 while (!list_empty(pool)) {
380 struct usb_request *req;
383 if (port->write_started >= QUEUE_SIZE)
386 req = list_entry(pool->next, struct usb_request, list);
387 len = gs_send_packet(port, req->buf, in->maxpacket);
389 wake_up_interruptible(&port->drain_wait);
394 list_del(&req->list);
395 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
397 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
398 port->port_num, len, *((u8 *)req->buf),
399 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
401 /* Drop lock while we call out of driver; completions
402 * could be issued while we do so. Disconnection may
403 * happen too; maybe immediately before we queue this!
405 * NOTE that we may keep sending data for a while after
406 * the TTY closed (dev->ioport->port_tty is NULL).
408 spin_unlock(&port->port_lock);
409 status = usb_ep_queue(in, req, GFP_ATOMIC);
410 spin_lock(&port->port_lock);
413 pr_debug("%s: %s %s err %d\n",
414 __func__, "queue", in->name, status);
415 list_add(&req->list, pool);
419 port->write_started++;
421 /* abort immediately after disconnect */
422 if (!port->port_usb){
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(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, (const char *)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 __maybe_unused 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, (const char *)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 __maybe_unused 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 __maybe_unused 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 __maybe_unused 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 __maybe_unused 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 __maybe_unused 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;
1457 static int gs_closed(struct gs_port *port)
1461 spin_lock_irq(&port->port_lock);
1462 cond = (port->open_count == 0) && !port->openclose;
1463 spin_unlock_irq(&port->port_lock);
1469 * gserial_cleanup - remove TTY-over-USB driver and devices
1470 * Context: may sleep
1472 * This is called to free all resources allocated by @gserial_setup().
1473 * Accordingly, it may need to wait until some open /dev/ files have
1476 * The caller must have issued @gserial_disconnect() for any ports
1477 * that had previously been connected, so that there is never any
1478 * I/O pending when it's called.
1480 void gserial_cleanup(void)
1483 struct gs_port *port;
1489 /* start sysfs and /dev/ttyGS* node removal */
1490 for (i = 0; i < n_ports; i++)
1491 tty_unregister_device(gs_tty_driver, i);
1493 for (i = 0; i < n_ports; i++) {
1494 /* prevent new opens */
1495 mutex_lock(&ports[i].lock);
1496 port = ports[i].port;
1497 ports[i].port = NULL;
1498 mutex_unlock(&ports[i].lock);
1500 // tasklet_kill(&port->push);
1503 /* wait for old opens to finish */
1504 wait_event(port->close_wait, gs_closed(port));
1507 //WARN_ON(port->port_usb != NULL);
1513 // tty_unregister_driver(gs_tty_driver);
1514 // put_tty_driver(gs_tty_driver);
1515 // gs_tty_driver = NULL;
1517 pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1521 * gserial_connect - notify TTY I/O glue that USB link is active
1522 * @gser: the function, set up with endpoints and descriptors
1523 * @port_num: which port is active
1524 * Context: any (usually from irq)
1526 * This is called activate endpoints and let the TTY layer know that
1527 * the connection is active ... not unlike "carrier detect". It won't
1528 * necessarily start I/O queues; unless the TTY is held open by any
1529 * task, there would be no point. However, the endpoints will be
1530 * activated so the USB host can perform I/O, subject to basic USB
1531 * hardware flow control.
1533 * Caller needs to have set up the endpoints and USB function in @dev
1534 * before calling this, as well as the appropriate (speed-specific)
1535 * endpoint descriptors, and also have set up the TTY driver by calling
1538 * Returns negative errno or zero.
1539 * On success, ep->driver_data will be overwritten.
1541 int gserial_connect(struct gserial *gser, u8 port_num)
1543 struct gs_port *port;
1544 __maybe_unused unsigned long flags;
1547 if (!gs_tty_driver || port_num >= n_ports)
1550 if (port_num >= n_ports)
1555 /* we "know" gserial_cleanup() hasn't been called */
1556 port = ports[port_num].port;
1558 /* activate the endpoints */
1559 status = usb_ep_enable(gser->in, gser->in_desc);
1562 gser->in->driver_data = port;
1564 status = usb_ep_enable(gser->out, gser->out_desc);
1567 gser->out->driver_data = port;
1569 /* then tell the tty glue that I/O can work */
1570 spin_lock_irqsave(&port->port_lock, flags);
1571 gser->ioport = port;
1572 port->port_usb = gser;
1574 /* REVISIT unclear how best to handle this state...
1575 * we don't really couple it with the Linux TTY.
1577 gser->port_line_coding = port->port_line_coding;
1579 /* REVISIT if waiting on "carrier detect", signal. */
1581 /* if it's already open, start I/O ... and notify the serial
1582 * protocol about open/close status (connect/disconnect).
1584 if (port->open_count) {
1585 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1588 gser->connect(gser);
1590 if (gser->disconnect)
1591 gser->disconnect(gser);
1594 spin_unlock_irqrestore(&port->port_lock, flags);
1599 usb_ep_disable(gser->in);
1600 gser->in->driver_data = NULL;
1605 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1606 * @gser: the function, on which gserial_connect() was called
1607 * Context: any (usually from irq)
1609 * This is called to deactivate endpoints and let the TTY layer know
1610 * that the connection went inactive ... not unlike "hangup".
1612 * On return, the state is as if gserial_connect() had never been called;
1613 * there is no active USB I/O on these endpoints.
1615 void gserial_disconnect(struct gserial *gser)
1617 struct gs_port *port = gser->ioport;
1618 __maybe_unused unsigned long flags;
1623 /* tell the TTY glue not to do I/O here any more */
1624 spin_lock_irqsave(&port->port_lock, flags);
1626 /* REVISIT as above: how best to track this? */
1627 port->port_line_coding = gser->port_line_coding;
1629 port->port_usb = NULL;
1630 gser->ioport = NULL;
1631 if (port->open_count > 0 || port->openclose) {
1632 wake_up_interruptible(&port->drain_wait);
1633 //if (port->port_tty)
1634 // tty_hangup(port->port_tty);
1636 spin_unlock_irqrestore(&port->port_lock, flags);
1638 /* disable endpoints, aborting down any active I/O */
1639 usb_ep_disable(gser->out);
1640 gser->out->driver_data = NULL;
1642 usb_ep_disable(gser->in);
1643 gser->in->driver_data = NULL;
1645 /* finally, free any unused/unusable I/O buffers */
1646 spin_lock_irqsave(&port->port_lock, flags);
1647 if (port->open_count == 0 && !port->openclose)
1648 gs_buf_free(&port->port_write_buf);
1649 gs_free_requests(gser->out, &port->read_pool, NULL);
1650 gs_free_requests(gser->out, &port->read_queue, NULL);
1651 gs_free_requests(gser->in, &port->write_pool, NULL);
1653 port->read_allocated = port->read_started =
1654 port->write_allocated = port->write_started = 0;
1656 spin_unlock_irqrestore(&port->port_lock, flags);
1658 void gs_reset_usb_param(void)
1663 usb_trans_status = 0;
1664 usb_serial_configed = 0;