usb: gadget: remove build warnings
[profile/mobile/platform/kernel/u-boot-tm1.git] / drivers / usb / gadget / u_serial.c
1 /*
2  * u_serial.c - utilities for USB gadget "serial port"/TTY support
3  *
4  * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
5  * Copyright (C) 2008 David Brownell
6  * Copyright (C) 2008 by Nokia Corporation
7  *
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)
12  *
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.
16  */
17
18 /* #define VERBOSE_DEBUG */
19
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>
28 #include <common.h>
29 #include <ubi_uboot.h>
30 #include <linux/mtd/compat.h>
31 #include <linux/list.h>
32
33 #include "u_serial.h"
34 #ifndef pr_warning
35 #define pr_warning(fmt, args...) printf(fmt, ##args)
36 #endif
37
38 #ifndef __maybe_unused
39 #define __maybe_unused          __attribute__((unused))
40 #endif
41
42 /*
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.
46  *
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.
52  *
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
58  * of this component.
59  *
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.
65  */
66
67 #define PREFIX  "ttyGS"
68
69 /*
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
73  *
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
79  *
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
84  */
85
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.
89  */
90 #define QUEUE_SIZE              16
91 #define WRITE_BUF_SIZE          8192            /* TX only */
92
93 /* circular buffer */
94 struct gs_buf {
95         unsigned                buf_size;
96         char                    *buf_buf;
97         char                    *buf_get;
98         char                    *buf_put;
99 };
100
101 /*
102  * The port structure holds info for each port, one for each minor number
103  * (and thus for each /dev/ node).
104  */
105 struct gs_port {
106         spinlock_t              port_lock;      /* guard port_* access */
107
108         struct gserial          *port_usb;
109         //struct tty_struct     *port_tty;
110
111         unsigned                open_count;
112         bool                    openclose;      /* open/close in progress */
113         u8                      port_num;
114
115         wait_queue_head_t       close_wait;     /* wait for last close */
116
117         struct list_head        read_pool;
118         int read_started;
119         int read_allocated;
120         struct list_head        read_queue;
121         unsigned                n_read;
122         //struct tasklet_struct push;
123
124         struct list_head        write_pool;
125         int write_started;
126         int write_allocated;
127         struct gs_buf           port_write_buf;
128         wait_queue_head_t       drain_wait;     /* wait while writes drain */
129
130         /* REVISIT this state ... */
131         struct usb_cdc_line_coding port_line_coding;    /* 8-N-1 etc */
132 };
133
134 /* increase N_PORTS if you need more */
135 #define N_PORTS         4
136 static struct portmaster {
137         struct mutex    lock;                   /* protect open/close */
138         struct gs_port  *port;
139 } ports[N_PORTS];
140 static unsigned n_ports;
141
142 #define GS_CLOSE_TIMEOUT                15              /* seconds */
143
144
145 #ifdef VERBOSE_DEBUG
146 #define pr_vdebug(fmt, arg...) \
147         pr_debug(fmt, ##arg)
148 #else
149 #define pr_vdebug(fmt, arg...) \
150         ({ if (0) pr_debug(fmt, ##arg); })
151 #endif
152
153 /*-------------------------------------------------------------------------*/
154
155 /* Circular Buffer */
156
157 /*
158  * gs_buf_alloc
159  *
160  * Allocate a circular buffer and all associated memory.
161  */
162 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
163 {
164         gb->buf_buf = kmalloc(size, GFP_KERNEL);
165         if (gb->buf_buf == NULL)
166                 return -ENOMEM;
167
168         gb->buf_size = size;
169         gb->buf_put = gb->buf_buf;
170         gb->buf_get = gb->buf_buf;
171
172         return 0;
173 }
174
175 /*
176  * gs_buf_free
177  *
178  * Free the buffer and all associated memory.
179  */
180 static void gs_buf_free(struct gs_buf *gb)
181 {
182         kfree(gb->buf_buf);
183         gb->buf_buf = NULL;
184 }
185
186 /*
187  * gs_buf_clear
188  *
189  * Clear out all data in the circular buffer.
190  */
191 static void gs_buf_clear(struct gs_buf *gb)
192 {
193         gb->buf_get = gb->buf_put;
194         /* equivalent to a get of all data available */
195 }
196
197 /*
198  * gs_buf_data_avail
199  *
200  * Return the number of bytes of data written into the circular
201  * buffer.
202  */
203 static unsigned gs_buf_data_avail(struct gs_buf *gb)
204 {
205         return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
206 }
207
208 /*
209  * gs_buf_space_avail
210  *
211  * Return the number of bytes of space available in the circular
212  * buffer.
213  */
214 static unsigned gs_buf_space_avail(struct gs_buf *gb)
215 {
216         return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
217 }
218
219 /*
220  * gs_buf_put
221  *
222  * Copy data data from a user buffer and put it into the circular buffer.
223  * Restrict to the amount of space available.
224  *
225  * Return the number of bytes copied.
226  */
227 static unsigned
228 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
229 {
230         unsigned len;
231
232         len  = gs_buf_space_avail(gb);
233         if (count > len)
234                 count = len;
235
236         if (count == 0)
237                 return 0;
238
239         len = gb->buf_buf + gb->buf_size - gb->buf_put;
240         if (count > len) {
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;
244         } else {
245                 memcpy(gb->buf_put, buf, count);
246                 if (count < len)
247                         gb->buf_put += count;
248                 else /* count == len */
249                         gb->buf_put = gb->buf_buf;
250         }
251
252         return count;
253 }
254
255 /*
256  * gs_buf_get
257  *
258  * Get data from the circular buffer and copy to the given buffer.
259  * Restrict to the amount of data available.
260  *
261  * Return the number of bytes copied.
262  */
263 static unsigned
264 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
265 {
266         unsigned len;
267
268         len = gs_buf_data_avail(gb);
269         if (count > len)
270                 count = len;
271
272         if (count == 0)
273                 return 0;
274
275         len = gb->buf_buf + gb->buf_size - gb->buf_get;
276         if (count > len) {
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;
280         } else {
281                 memcpy(buf, gb->buf_get, count);
282                 if (count < len)
283                         gb->buf_get += count;
284                 else /* count == len */
285                         gb->buf_get = gb->buf_buf;
286         }
287
288         return count;
289 }
290
291 /*-------------------------------------------------------------------------*/
292
293 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
294
295 /*
296  * gs_alloc_req
297  *
298  * Allocate a usb_request and its buffer.  Returns a pointer to the
299  * usb_request or NULL if there is an error.
300  */
301 struct usb_request *
302 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
303 {
304         struct usb_request *req;
305
306         req = usb_ep_alloc_request(ep, kmalloc_flags);
307
308         if (req != NULL) {
309                 req->length = len;
310                 req->buf = kmalloc(len, kmalloc_flags);
311                 if (req->buf == NULL) {
312                         usb_ep_free_request(ep, req);
313                         return NULL;
314                 }
315         }
316
317         return req;
318 }
319
320 /*
321  * gs_free_req
322  *
323  * Free a usb_request and its buffer.
324  */
325 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
326 {
327         kfree(req->buf);
328         usb_ep_free_request(ep, req);
329 }
330
331 /*
332  * gs_send_packet
333  *
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.
337  *
338  * Called with port_lock held.
339  */
340 static unsigned
341 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
342 {
343         unsigned len;
344
345         len = gs_buf_data_avail(&port->port_write_buf);
346         if (len < size)
347                 size = len;
348         if (size != 0)
349                 size = gs_buf_get(&port->port_write_buf, packet, size);
350         return size;
351 }
352
353 /*
354  * gs_start_tx
355  *
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.
361  *
362  * Context: caller owns port_lock; port_usb is non-null.
363  */
364 static int gs_start_tx(struct gs_port *port)
365 /*
366 __releases(&port->port_lock)
367 __acquires(&port->port_lock)
368 */
369 {
370         struct list_head        *pool = &port->write_pool;
371         struct usb_ep           *in = NULL;
372         int                     status = 0;
373
374         if (!port->port_usb){
375                 return status;
376         }
377         in = port->port_usb->in;
378
379         while (!list_empty(pool)) {
380                 struct usb_request      *req;
381                 int                     len;
382
383                 if (port->write_started >= QUEUE_SIZE)
384                         break;
385
386                 req = list_entry(pool->next, struct usb_request, list);
387                 len = gs_send_packet(port, req->buf, in->maxpacket);
388                 if (len == 0) {
389                         wake_up_interruptible(&port->drain_wait);
390                         break;
391                 }
392
393                 req->length = len;
394                 list_del(&req->list);
395                 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
396
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));
400
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!
404                  *
405                  * NOTE that we may keep sending data for a while after
406                  * the TTY closed (dev->ioport->port_tty is NULL).
407                  */
408                 spin_unlock(&port->port_lock);
409                 status = usb_ep_queue(in, req, GFP_ATOMIC);
410                 spin_lock(&port->port_lock);
411
412                 if (status) {
413                         pr_debug("%s: %s %s err %d\n",
414                                         __func__, "queue", in->name, status);
415                         list_add(&req->list, pool);
416                         break;
417                 }
418
419                 port->write_started++;
420
421                 /* abort immediately after disconnect */
422                 if (!port->port_usb){
423                         break;
424                 }
425         }
426
427         return status;
428 }
429
430 /*
431  * Context: caller owns port_lock, and port_usb is set
432  */
433 static unsigned gs_start_rx(struct gs_port *port)
434 /*
435 __releases(&port->port_lock)
436 __acquires(&port->port_lock)
437 */
438 {
439         struct list_head        *pool = &port->read_pool;
440         struct usb_ep           *out = NULL;
441         if (!port->port_usb){
442                 return 0;
443         }
444     out = port->port_usb->out;
445         while (!list_empty(pool)) {
446                 struct usb_request      *req;
447                 int                     status;
448 #if 0
449                 struct tty_struct       *tty;
450
451                 /* no more rx if closed */
452                 tty = port->port_tty;
453                 if (!tty)
454                         break;
455 #endif
456                 if (port->read_started >= QUEUE_SIZE)
457                         break;
458
459                 req = list_entry(pool->next, struct usb_request, list);
460                 list_del(&req->list);
461                 req->length = out->maxpacket;
462
463                 /* drop lock while we call out; the controller driver
464                  * may need to call us back (e.g. for disconnect)
465                  */
466                 spin_unlock(&port->port_lock);
467                 status = usb_ep_queue(out, req, GFP_ATOMIC);
468                 spin_lock(&port->port_lock);
469
470                 if (status) {
471                         pr_debug("%s: %s %s err %d\n",
472                                         __func__, "queue", out->name, status);
473                         list_add(&req->list, pool);
474                         break;
475                 }
476                 port->read_started++;
477
478                 /* abort immediately after disconnect */
479                 if (!port->port_usb){
480                         break;
481                 }
482         }
483         return port->read_started;
484 }
485
486 /*
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.
490  *
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).
495  */
496  #if 0
497 static void gs_rx_push(unsigned long _port)
498 {
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;
504
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;
510
511                 req = list_first_entry(queue, struct usb_request, list);
512
513                 /* discard data if tty was closed */
514                 if (!tty)
515                         goto recycle;
516
517                 /* leave data queued if tty was rx throttled */
518                 if (test_bit(TTY_THROTTLED, &tty->flags))
519                         break;
520
521                 switch (req->status) {
522                 case -ESHUTDOWN:
523                         disconnect = true;
524                         pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
525                         break;
526
527                 default:
528                         /* presumably a transient fault */
529                         pr_warning(PREFIX "%d: unexpected RX status %d\n",
530                                         port->port_num, req->status);
531                         /* FALLTHROUGH */
532                 case 0:
533                         /* normal completion */
534                         break;
535                 }
536
537                 /* push data to (open) tty */
538                 if (req->actual) {
539                         char            *packet = req->buf;
540                         unsigned        size = req->actual;
541                         unsigned        n;
542                         int             count;
543
544                         /* we may have pushed part of this packet already... */
545                         n = port->n_read;
546                         if (n) {
547                                 packet += n;
548                                 size -= n;
549                         }
550
551                         count = tty_insert_flip_string(tty, packet, size);
552                         if (count)
553                                 do_push = true;
554                         if (count != 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",
558                                                 port->port_num,
559                                                 count, req->actual);
560                                 break;
561                         }
562                         port->n_read = 0;
563                 }
564 recycle:
565                 list_move(&req->list, &port->read_pool);
566                 port->read_started--;
567         }
568
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
571          */
572         if (tty && do_push) {
573                 tty_flip_buffer_push(tty);
574         }
575
576
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...
581          *
582          * REVISIT we should probably add a timer to keep the tasklet
583          * from starving ... but it's not clear that case ever happens.
584          */
585         if (!list_empty(queue) && tty) {
586                 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
587                         if (do_push)
588                                 tasklet_schedule(&port->push);
589                         else
590                                 pr_warning(PREFIX "%d: RX not scheduled?\n",
591                                         port->port_num);
592                 }
593         }
594
595         /* If we're still connected, refill the USB RX queue. */
596         if (!disconnect && port->port_usb)
597                 gs_start_rx(port);
598
599         spin_unlock_irq(&port->port_lock);
600 }
601  static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
602 {
603         struct gs_port  *port = ep->driver_data;
604
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);
610 }
611
612 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
613 {
614         struct gs_port  *port = ep->driver_data;
615
616         spin_lock(&port->port_lock);
617         list_add(&req->list, &port->write_pool);
618         port->write_started--;
619
620         switch (req->status) {
621         default:
622                 /* presumably a transient fault */
623                 printf("%s: unexpected %s status %d\n",
624                                 __func__, ep->name, req->status);
625                 /* FALL THROUGH */
626         case 0:
627                 /* normal completion */
628                 gs_start_tx(port);
629                 break;
630
631         case -ESHUTDOWN:
632                 /* disconnect */
633                 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
634                 break;
635         }
636
637         spin_unlock(&port->port_lock);
638 }
639  #else
640 int vcom_port = 0;
641 int usb_write_done;
642 int usb_read_done;
643 int usb_trans_status;
644 static int gs_start_io(struct gs_port *port);
645
646 int gs_open(void)
647 {
648         int status = 0;
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);
652                 if(status){
653                         printf("gs_open: gs_buf_alloc failed\n");
654                         return status;
655                 }
656         }
657         /* if connected, start the I/O stream */
658         if (port->port_usb) {
659                 struct gserial  *gser = port->port_usb;
660
661                 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
662                 gs_start_io(port);
663
664                 if (gser->connect)
665                         gser->connect(gser);
666         }
667
668         pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
669
670         status = 0;
671         return status;
672 }
673 void gs_close(void)
674 {
675         struct gs_port *port = ports[vcom_port].port;
676         struct gserial  *gser;
677
678         spin_lock_irq(&port->port_lock);
679
680         if (port->open_count != 1) {
681                 if (port->open_count == 0)
682                         ;
683                 else
684                         --port->open_count;
685                 goto exit;
686         }
687
688         pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
689
690         /* mark port as closing but in use; we can drop port lock
691          * and sleep if necessary
692          */
693         port->openclose = true;
694         port->open_count = 0;
695
696         gser = port->port_usb;
697         if (gser && gser->disconnect)
698                 gser->disconnect(gser);
699
700         /* wait for circular write buffer to drain, disconnect, or at
701          * most GS_CLOSE_TIMEOUT seconds; then discard the rest
702          */
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;
710         }
711
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.
715          */
716         if (gser == NULL)
717                 gs_buf_free(&port->port_write_buf);
718         else
719                 gs_buf_clear(&port->port_write_buf);
720
721         //tty->driver_data = NULL;
722         //port->port_tty = NULL;
723
724         port->openclose = false;
725
726         pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
727                         port->port_num, tty, file);
728
729         //wake_up_interruptible(&port->close_wait);
730 exit:
731         spin_unlock_irq(&port->port_lock);
732 }
733
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)
738 {
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;
743
744         if (!list_empty(queue)) {
745                 struct usb_request      *req;
746
747                 req = list_first_entry(queue, struct usb_request, list);
748                 switch (req->status) {
749                 case -ESHUTDOWN:
750                         disconnect = true;
751                         pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
752                         break;
753
754                 default:
755                         /* presumably a transient fault */
756                         printf(PREFIX "%d: unexpected RX status %d\n",
757                                         port->port_num, req->status);
758                         /* FALLTHROUGH */
759                 case 0:
760                         /* normal completion */
761                         break;
762                 }
763
764                 if (req->actual) {
765                         char            *packet = req->buf;
766                         unsigned        size = req->actual;
767                         unsigned        n;
768
769
770                         /* we may have pushed part of this packet already... */
771                         n = port->n_read;
772                         if (n) {
773                                 packet += n;
774                                 size -= n;
775                         }
776                         if(size)
777                                 do_push = true;
778                         if(*count >= size){
779                                 memcpy(buf, packet, size);
780                                 *count = size;
781                         }else{
782                                 memcpy(buf, packet, *count);
783                                 port->n_read += *count;
784                                 //break;
785                         }
786                         port->n_read = 0;
787                 }
788
789                 list_move(&req->list, &port->read_pool);
790                 port->read_started--;
791         }
792         /* If we're still connected, refill the USB RX queue. */
793         if (!disconnect && port->port_usb)
794                 gs_start_rx(port);
795
796         return do_push;
797                         
798 }
799 /*
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
803 */
804 int gs_write(const unsigned char *buf, int count)
805 {
806         struct gs_port  *port = ports[vcom_port].port;
807         if (count)
808                 count = gs_buf_put(&port->port_write_buf, (const char *)buf, count);
809         /* treat count == 0 as flush_chars() */
810         if (port->port_usb)
811                 usb_trans_status = gs_start_tx(port);
812         return count;
813 }
814
815 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
816 {
817         struct gs_port  *port = ep->driver_data;
818
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);
822         usb_read_done = 1;
823         usb_trans_status = req->status;
824         //tasklet_schedule(&port->push);
825         spin_unlock(&port->port_lock);
826 }
827
828 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
829 {
830         struct gs_port  *port = ep->driver_data;
831
832         spin_lock(&port->port_lock);
833         list_add(&req->list, &port->write_pool);
834         port->write_started--;
835
836         switch (req->status) {
837         default:
838                 /* presumably a transient fault */
839                 printf("%s: unexpected %s status %d\n",
840                                 __func__, ep->name, req->status);
841                 /* FALL THROUGH */
842         case 0:
843                 /* normal completion */
844                 gs_start_tx(port);
845                 break;
846
847         case -ESHUTDOWN:
848                 /* disconnect */
849                 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
850                 break;
851         }
852         
853         usb_write_done = 1;
854         usb_trans_status = req->status;
855
856         spin_unlock(&port->port_lock);
857 }
858 /*
859 wait the read or write done
860 direct: 1 for output, 0 for input
861 */
862 extern int usb_gadget_handle_interrupts(void);
863 void usb_wait_trans_done(int direct)
864 {
865         if(direct){
866                 while(!usb_write_done)
867                         usb_gadget_handle_interrupts();
868                  usb_write_done = 0;
869         }else{
870                 while(!usb_read_done)
871                         usb_gadget_handle_interrupts();
872                 usb_read_done = 0;
873         }
874 }
875 int usb_is_trans_done(int direct)
876 {
877         if(direct){
878                 if(!usb_write_done)
879                         usb_gadget_handle_interrupts();
880                 if(usb_write_done){
881             usb_write_done = 0;
882             return 1;
883         }
884         }else{
885                 if(!usb_read_done)
886                         usb_gadget_handle_interrupts();
887                 if(usb_read_done){
888             usb_read_done = 0;
889             return 1;
890         }
891         }
892     return 0;
893 }
894
895 extern int usb_serial_configed;
896 int usb_is_configured(void)
897 {
898         if(!usb_serial_configed)
899                 usb_gadget_handle_interrupts();
900
901         return usb_serial_configed;
902 }
903
904 extern int usb_port_open;
905 int usb_is_port_open(void)
906 {
907         if(!usb_port_open)
908                 usb_gadget_handle_interrupts();
909
910         return usb_port_open;
911 }
912 #endif
913
914 static void gs_free_requests(struct usb_ep *ep, struct list_head *head,
915                                                          int *allocated)
916 {
917         struct usb_request      *req;
918
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);
923                 if (allocated)
924                         (*allocated)--;
925         }
926 }
927
928 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
929                 void (*fn)(struct usb_ep *, struct usb_request *),
930                 int *allocated)
931 {
932         int                     i;
933         struct usb_request      *req;
934         int n = allocated ? QUEUE_SIZE - *allocated : QUEUE_SIZE;
935
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.
939          */
940         for (i = 0; i < n; i++) {
941                 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
942                 if (!req)
943                         return list_empty(head) ? -ENOMEM : 0;
944                 req->complete = fn;
945                 list_add_tail(&req->list, head);
946                 if (allocated)
947                         (*allocated)++;
948         }
949         return 0;
950 }
951
952 /**
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
956  *
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.
960  */
961 static int gs_start_io(struct gs_port *port)
962 {
963         struct list_head        *head = &port->read_pool;
964         struct usb_ep           *ep = port->port_usb->out;
965         int                     status;
966         unsigned                started;
967
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.
973          */
974         status = gs_alloc_requests(ep, head, gs_read_complete,
975                 &port->read_allocated);
976         if (status)
977                 return status;
978
979         status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
980                         gs_write_complete, &port->write_allocated);
981         if (status) {
982                 gs_free_requests(ep, head, &port->read_allocated);
983                 return status;
984         }
985
986         /* queue read requests */
987         port->n_read = 0;
988         started = gs_start_rx(port);
989
990         /* unblock any pending writes into our circular buffer */
991         if (started) {
992                 //tty_wakeup(port->port_tty);
993         } else {
994                 gs_free_requests(ep, head, &port->read_allocated);
995                 gs_free_requests(port->port_usb->in, &port->write_pool,
996                         &port->write_allocated);
997                 status = -EIO;
998         }
999
1000         return status;
1001 }
1002
1003 /*-------------------------------------------------------------------------*/
1004
1005 /* TTY Driver */
1006
1007 /*
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
1010  * know that.
1011  */
1012  #if 0
1013 static int gs_open(struct tty_struct *tty, struct file *file)
1014 {
1015         int             port_num = tty->index;
1016         struct gs_port  *port;
1017         int             status;
1018
1019         if (port_num < 0 || port_num >= n_ports)
1020                 return -ENXIO;
1021
1022         do {
1023                 mutex_lock(&ports[port_num].lock);
1024                 port = ports[port_num].port;
1025                 if (!port)
1026                         status = -ENODEV;
1027                 else {
1028                         spin_lock_irq(&port->port_lock);
1029
1030                         /* already open?  Great. */
1031                         if (port->open_count) {
1032                                 status = 0;
1033                                 port->open_count++;
1034
1035                         /* currently opening/closing? wait ... */
1036                         } else if (port->openclose) {
1037                                 status = -EBUSY;
1038
1039                         /* ... else we do the work */
1040                         } else {
1041                                 status = -EAGAIN;
1042                                 port->openclose = true;
1043                         }
1044                         spin_unlock_irq(&port->port_lock);
1045                 }
1046                 mutex_unlock(&ports[port_num].lock);
1047
1048                 switch (status) {
1049                 default:
1050                         /* fully handled */
1051                         return status;
1052                 case -EAGAIN:
1053                         /* must do the work */
1054                         break;
1055                 case -EBUSY:
1056                         /* wait for EAGAIN task to finish */
1057                         msleep(1);
1058                         /* REVISIT could have a waitchannel here, if
1059                          * concurrent open performance is important
1060                          */
1061                         break;
1062                 }
1063         } while (status != -EAGAIN);
1064
1065         /* Do the "real open" */
1066         spin_lock_irq(&port->port_lock);
1067
1068         /* allocate circular buffer on first open */
1069         if (port->port_write_buf.buf_buf == NULL) {
1070
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);
1074
1075                 if (status) {
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;
1080                 }
1081         }
1082
1083         /* REVISIT if REMOVED (ports[].port NULL), abort the open
1084          * to let rmmod work faster (but this way isn't wrong).
1085          */
1086
1087         /* REVISIT maybe wait for "carrier detect" */
1088
1089         tty->driver_data = port;
1090         port->port_tty = tty;
1091
1092         port->open_count = 1;
1093         port->openclose = false;
1094
1095         /* if connected, start the I/O stream */
1096         if (port->port_usb) {
1097                 struct gserial  *gser = port->port_usb;
1098
1099                 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
1100                 gs_start_io(port);
1101
1102                 if (gser->connect)
1103                         gser->connect(gser);
1104         }
1105
1106         pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
1107
1108         status = 0;
1109
1110 exit_unlock_port:
1111         spin_unlock_irq(&port->port_lock);
1112         return status;
1113 }
1114
1115 static int gs_writes_finished(struct gs_port *p)
1116 {
1117         int cond;
1118
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);
1123
1124         return cond;
1125 }
1126
1127 static void gs_close(struct tty_struct *tty, struct file *file)
1128 {
1129         struct gs_port *port = tty->driver_data;
1130         struct gserial  *gser;
1131
1132         spin_lock_irq(&port->port_lock);
1133
1134         if (port->open_count != 1) {
1135                 if (port->open_count == 0)
1136                         WARN_ON(1);
1137                 else
1138                         --port->open_count;
1139                 goto exit;
1140         }
1141
1142         pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
1143
1144         /* mark port as closing but in use; we can drop port lock
1145          * and sleep if necessary
1146          */
1147         port->openclose = true;
1148         port->open_count = 0;
1149
1150         gser = port->port_usb;
1151         if (gser && gser->disconnect)
1152                 gser->disconnect(gser);
1153
1154         /* wait for circular write buffer to drain, disconnect, or at
1155          * most GS_CLOSE_TIMEOUT seconds; then discard the rest
1156          */
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;
1164         }
1165
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.
1169          */
1170         if (gser == NULL)
1171                 gs_buf_free(&port->port_write_buf);
1172         else
1173                 gs_buf_clear(&port->port_write_buf);
1174
1175         tty->driver_data = NULL;
1176         port->port_tty = NULL;
1177
1178         port->openclose = false;
1179
1180         pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
1181                         port->port_num, tty, file);
1182
1183         wake_up_interruptible(&port->close_wait);
1184 exit:
1185         spin_unlock_irq(&port->port_lock);
1186 }
1187
1188 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
1189 {
1190         struct gs_port  *port = tty->driver_data;
1191         __maybe_unused unsigned long    flags;
1192         int             status;
1193
1194         pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
1195                         port->port_num, tty, count);
1196
1197         spin_lock_irqsave(&port->port_lock, flags);
1198         if (count)
1199                 count = gs_buf_put(&port->port_write_buf, (const char *)buf, count);
1200         /* treat count == 0 as flush_chars() */
1201         if (port->port_usb)
1202                 status = gs_start_tx(port);
1203         spin_unlock_irqrestore(&port->port_lock, flags);
1204
1205         return count;
1206 }
1207
1208 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
1209 {
1210         struct gs_port  *port = tty->driver_data;
1211         __maybe_unused unsigned long    flags;
1212         int             status;
1213
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));
1216
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);
1220
1221         return status;
1222 }
1223
1224 static void gs_flush_chars(struct tty_struct *tty)
1225 {
1226         struct gs_port  *port = tty->driver_data;
1227         __maybe_unused unsigned long    flags;
1228
1229         pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
1230
1231         spin_lock_irqsave(&port->port_lock, flags);
1232         if (port->port_usb)
1233                 gs_start_tx(port);
1234         spin_unlock_irqrestore(&port->port_lock, flags);
1235 }
1236
1237 static int gs_write_room(struct tty_struct *tty)
1238 {
1239         struct gs_port  *port = tty->driver_data;
1240         __maybe_unused unsigned long    flags;
1241         int             room = 0;
1242
1243         spin_lock_irqsave(&port->port_lock, flags);
1244         if (port->port_usb)
1245                 room = gs_buf_space_avail(&port->port_write_buf);
1246         spin_unlock_irqrestore(&port->port_lock, flags);
1247
1248         pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
1249                 port->port_num, tty, room);
1250
1251         return room;
1252 }
1253
1254 static int gs_chars_in_buffer(struct tty_struct *tty)
1255 {
1256         struct gs_port  *port = tty->driver_data;
1257         __maybe_unused unsigned long    flags;
1258         int             chars = 0;
1259
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);
1263
1264         pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
1265                 port->port_num, tty, chars);
1266
1267         return chars;
1268 }
1269
1270 /* undo side effects of setting TTY_THROTTLED */
1271 static void gs_unthrottle(struct tty_struct *tty)
1272 {
1273         struct gs_port          *port = tty->driver_data;
1274         __maybe_unused unsigned long    flags;
1275
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.
1281                  */
1282                 tasklet_schedule(&port->push);
1283                 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
1284         }
1285         spin_unlock_irqrestore(&port->port_lock, flags);
1286 }
1287
1288 static int gs_break_ctl(struct tty_struct *tty, int duration)
1289 {
1290         struct gs_port  *port = tty->driver_data;
1291         int             status = 0;
1292         struct gserial  *gser;
1293
1294         pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
1295                         port->port_num, duration);
1296
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);
1302
1303         return status;
1304 }
1305
1306 static const struct tty_operations gs_tty_ops = {
1307         .open =                 gs_open,
1308         .close =                gs_close,
1309         .write =                gs_write,
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,
1316 };
1317 #endif
1318
1319 /*-------------------------------------------------------------------------*/
1320
1321 //static struct tty_driver *gs_tty_driver;
1322
1323 static int __init
1324 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1325 {
1326         struct gs_port  *port;
1327
1328         port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1329         if (port == NULL)
1330                 return -ENOMEM;
1331
1332         spin_lock_init(&port->port_lock);
1333         init_waitqueue_head(&port->close_wait);
1334         init_waitqueue_head(&port->drain_wait);
1335
1336         //tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1337
1338         INIT_LIST_HEAD(&port->read_pool);
1339         INIT_LIST_HEAD(&port->read_queue);
1340         INIT_LIST_HEAD(&port->write_pool);
1341
1342         port->port_num = port_num;
1343         port->port_line_coding = *coding;
1344
1345         ports[port_num].port = port;
1346
1347         return 0;
1348 }
1349
1350 /**
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
1355  *
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.
1361  *
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
1365  * one doesn't.
1366  *
1367  * Returns negative errno or zero.
1368  */
1369 int __init gserial_setup(struct usb_gadget *g, unsigned count)
1370 {
1371         unsigned                        i;
1372         struct usb_cdc_line_coding      coding;
1373         int                             status =0;
1374
1375         if (count == 0 || count > N_PORTS)
1376                 return -EINVAL;
1377
1378 #if 0
1379         gs_tty_driver = alloc_tty_driver(count);
1380         if (!gs_tty_driver)
1381                 return -ENOMEM;
1382
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 */
1387
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;
1392
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.
1396          */
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;
1401
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;
1406
1407         tty_set_operations(gs_tty_driver, &gs_tty_ops);
1408 #endif
1409
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);
1415                 if (status) {
1416                         count = i;
1417                         goto fail;
1418                 }
1419         }
1420         n_ports = count;
1421
1422         /* export the driver ... */
1423 #if 0
1424         status = tty_register_driver(gs_tty_driver);
1425         if (status) {
1426                 pr_err("%s: cannot register, err %d\n",
1427                                 __func__, status);
1428                 goto fail;
1429         }
1430
1431
1432         /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1433         for (i = 0; i < count; i++) {
1434                 struct device   *tty_dev;
1435
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));
1440         }
1441
1442         pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1443                         count, (count == 1) ? "" : "s");
1444
1445 #endif
1446         return status;
1447 fail:
1448         while (count--)
1449                 kfree(ports[count].port);
1450         //put_tty_driver(gs_tty_driver);
1451         //gs_tty_driver = NULL;
1452
1453         return status;
1454 }
1455
1456 #if 0
1457 static int gs_closed(struct gs_port *port)
1458 {
1459         int cond;
1460
1461         spin_lock_irq(&port->port_lock);
1462         cond = (port->open_count == 0) && !port->openclose;
1463         spin_unlock_irq(&port->port_lock);
1464         return cond;
1465 }
1466 #endif
1467
1468 /**
1469  * gserial_cleanup - remove TTY-over-USB driver and devices
1470  * Context: may sleep
1471  *
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
1474  * closed.
1475  *
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.
1479  */
1480 void gserial_cleanup(void)
1481 {
1482         unsigned        i;
1483         struct gs_port  *port;
1484         
1485 #if 0
1486         if (!gs_tty_driver)
1487                 return;
1488
1489         /* start sysfs and /dev/ttyGS* node removal */
1490         for (i = 0; i < n_ports; i++)
1491                 tty_unregister_device(gs_tty_driver, i);
1492 #endif
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);
1499
1500 //              tasklet_kill(&port->push);
1501
1502 #if 0
1503                 /* wait for old opens to finish */
1504                 wait_event(port->close_wait, gs_closed(port));
1505 #endif
1506
1507                 //WARN_ON(port->port_usb != NULL);
1508
1509                 kfree(port);
1510         }
1511         n_ports = 0;
1512
1513 //      tty_unregister_driver(gs_tty_driver);
1514 //      put_tty_driver(gs_tty_driver);
1515 //      gs_tty_driver = NULL;
1516
1517         pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1518 }
1519
1520 /**
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)
1525  *
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.
1532  *
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
1536  * @gserial_setup().
1537  *
1538  * Returns negative errno or zero.
1539  * On success, ep->driver_data will be overwritten.
1540  */
1541 int gserial_connect(struct gserial *gser, u8 port_num)
1542 {
1543         struct gs_port  *port;
1544         __maybe_unused unsigned long    flags;
1545         int             status;
1546 #if 0
1547         if (!gs_tty_driver || port_num >= n_ports)
1548                 return -ENXIO;
1549 #else
1550         if (port_num >= n_ports)
1551                 return -ENXIO;
1552
1553 #endif
1554
1555         /* we "know" gserial_cleanup() hasn't been called */
1556         port = ports[port_num].port;
1557
1558         /* activate the endpoints */
1559         status = usb_ep_enable(gser->in, gser->in_desc);
1560         if (status < 0)
1561                 return status;
1562         gser->in->driver_data = port;
1563
1564         status = usb_ep_enable(gser->out, gser->out_desc);
1565         if (status < 0)
1566                 goto fail_out;
1567         gser->out->driver_data = port;
1568
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;
1573
1574         /* REVISIT unclear how best to handle this state...
1575          * we don't really couple it with the Linux TTY.
1576          */
1577         gser->port_line_coding = port->port_line_coding;
1578
1579         /* REVISIT if waiting on "carrier detect", signal. */
1580
1581         /* if it's already open, start I/O ... and notify the serial
1582          * protocol about open/close status (connect/disconnect).
1583          */
1584         if (port->open_count) {
1585                 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1586                 gs_start_io(port);
1587                 if (gser->connect)
1588                         gser->connect(gser);
1589         } else {
1590                 if (gser->disconnect)
1591                         gser->disconnect(gser);
1592         }
1593
1594         spin_unlock_irqrestore(&port->port_lock, flags);
1595
1596         return status;
1597
1598 fail_out:
1599         usb_ep_disable(gser->in);
1600         gser->in->driver_data = NULL;
1601         return status;
1602 }
1603
1604 /**
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)
1608  *
1609  * This is called to deactivate endpoints and let the TTY layer know
1610  * that the connection went inactive ... not unlike "hangup".
1611  *
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.
1614  */
1615 void gserial_disconnect(struct gserial *gser)
1616 {
1617         struct gs_port  *port = gser->ioport;
1618         __maybe_unused unsigned long    flags;
1619
1620         if (!port)
1621                 return;
1622
1623         /* tell the TTY glue not to do I/O here any more */
1624         spin_lock_irqsave(&port->port_lock, flags);
1625
1626         /* REVISIT as above: how best to track this? */
1627         port->port_line_coding = gser->port_line_coding;
1628
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);
1635         }
1636         spin_unlock_irqrestore(&port->port_lock, flags);
1637
1638         /* disable endpoints, aborting down any active I/O */
1639         usb_ep_disable(gser->out);
1640         gser->out->driver_data = NULL;
1641
1642         usb_ep_disable(gser->in);
1643         gser->in->driver_data = NULL;
1644
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);
1652
1653         port->read_allocated = port->read_started =
1654                 port->write_allocated = port->write_started = 0;
1655
1656         spin_unlock_irqrestore(&port->port_lock, flags);
1657 }
1658 void gs_reset_usb_param(void)
1659 {
1660         vcom_port = 0;
1661         usb_write_done = 0;
1662         usb_read_done = 0;
1663         usb_trans_status = 0;
1664         usb_serial_configed = 0;
1665         usb_port_open = 0;
1666 }