tizen 2.4 release
[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 /*
39  * This component encapsulates the TTY layer glue needed to provide basic
40  * "serial port" functionality through the USB gadget stack.  Each such
41  * port is exposed through a /dev/ttyGS* node.
42  *
43  * After initialization (gserial_setup), these TTY port devices stay
44  * available until they are removed (gserial_cleanup).  Each one may be
45  * connected to a USB function (gserial_connect), or disconnected (with
46  * gserial_disconnect) when the USB host issues a config change event.
47  * Data can only flow when the port is connected to the host.
48  *
49  * A given TTY port can be made available in multiple configurations.
50  * For example, each one might expose a ttyGS0 node which provides a
51  * login application.  In one case that might use CDC ACM interface 0,
52  * while another configuration might use interface 3 for that.  The
53  * work to handle that (including descriptor management) is not part
54  * of this component.
55  *
56  * Configurations may expose more than one TTY port.  For example, if
57  * ttyGS0 provides login service, then ttyGS1 might provide dialer access
58  * for a telephone or fax link.  And ttyGS2 might be something that just
59  * needs a simple byte stream interface for some messaging protocol that
60  * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
61  */
62
63 #define PREFIX  "ttyGS"
64
65 /*
66  * gserial is the lifecycle interface, used by USB functions
67  * gs_port is the I/O nexus, used by the tty driver
68  * tty_struct links to the tty/filesystem framework
69  *
70  * gserial <---> gs_port ... links will be null when the USB link is
71  * inactive; managed by gserial_{connect,disconnect}().  each gserial
72  * instance can wrap its own USB control protocol.
73  *      gserial->ioport == usb_ep->driver_data ... gs_port
74  *      gs_port->port_usb ... gserial
75  *
76  * gs_port <---> tty_struct ... links will be null when the TTY file
77  * isn't opened; managed by gs_open()/gs_close()
78  *      gserial->port_tty ... tty_struct
79  *      tty_struct->driver_data ... gserial
80  */
81
82 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
83  * next layer of buffering.  For TX that's a circular buffer; for RX
84  * consider it a NOP.  A third layer is provided by the TTY code.
85  */
86 #define QUEUE_SIZE              16
87 #define WRITE_BUF_SIZE          8192            /* TX only */
88
89 /* circular buffer */
90 struct gs_buf {
91         unsigned                buf_size;
92         char                    *buf_buf;
93         char                    *buf_get;
94         char                    *buf_put;
95 };
96
97 /*
98  * The port structure holds info for each port, one for each minor number
99  * (and thus for each /dev/ node).
100  */
101 struct gs_port {
102         spinlock_t              port_lock;      /* guard port_* access */
103
104         struct gserial          *port_usb;
105         //struct tty_struct     *port_tty;
106
107         unsigned                open_count;
108         bool                    openclose;      /* open/close in progress */
109         u8                      port_num;
110
111         wait_queue_head_t       close_wait;     /* wait for last close */
112
113         struct list_head        read_pool;
114         int read_started;
115         int read_allocated;
116         struct list_head        read_queue;
117         unsigned                n_read;
118         //struct tasklet_struct push;
119
120         struct list_head        write_pool;
121         int write_started;
122         int write_allocated;
123         struct gs_buf           port_write_buf;
124         wait_queue_head_t       drain_wait;     /* wait while writes drain */
125
126         /* REVISIT this state ... */
127         struct usb_cdc_line_coding port_line_coding;    /* 8-N-1 etc */
128 };
129
130 /* increase N_PORTS if you need more */
131 #define N_PORTS         4
132 static struct portmaster {
133         struct mutex    lock;                   /* protect open/close */
134         struct gs_port  *port;
135 } ports[N_PORTS];
136 static unsigned n_ports;
137
138 #define GS_CLOSE_TIMEOUT                15              /* seconds */
139
140
141 #ifdef VERBOSE_DEBUG
142 #define pr_vdebug(fmt, arg...) \
143         pr_debug(fmt, ##arg)
144 #else
145 #define pr_vdebug(fmt, arg...) \
146         ({ if (0) pr_debug(fmt, ##arg); })
147 #endif
148
149 /*-------------------------------------------------------------------------*/
150
151 /* Circular Buffer */
152
153 /*
154  * gs_buf_alloc
155  *
156  * Allocate a circular buffer and all associated memory.
157  */
158 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
159 {
160         gb->buf_buf = kmalloc(size, GFP_KERNEL);
161         if (gb->buf_buf == NULL)
162                 return -ENOMEM;
163
164         gb->buf_size = size;
165         gb->buf_put = gb->buf_buf;
166         gb->buf_get = gb->buf_buf;
167
168         return 0;
169 }
170
171 /*
172  * gs_buf_free
173  *
174  * Free the buffer and all associated memory.
175  */
176 static void gs_buf_free(struct gs_buf *gb)
177 {
178         kfree(gb->buf_buf);
179         gb->buf_buf = NULL;
180 }
181
182 /*
183  * gs_buf_clear
184  *
185  * Clear out all data in the circular buffer.
186  */
187 static void gs_buf_clear(struct gs_buf *gb)
188 {
189         gb->buf_get = gb->buf_put;
190         /* equivalent to a get of all data available */
191 }
192
193 /*
194  * gs_buf_data_avail
195  *
196  * Return the number of bytes of data written into the circular
197  * buffer.
198  */
199 static unsigned gs_buf_data_avail(struct gs_buf *gb)
200 {
201         return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
202 }
203
204 /*
205  * gs_buf_space_avail
206  *
207  * Return the number of bytes of space available in the circular
208  * buffer.
209  */
210 static unsigned gs_buf_space_avail(struct gs_buf *gb)
211 {
212         return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
213 }
214
215 /*
216  * gs_buf_put
217  *
218  * Copy data data from a user buffer and put it into the circular buffer.
219  * Restrict to the amount of space available.
220  *
221  * Return the number of bytes copied.
222  */
223 static unsigned
224 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
225 {
226         unsigned len;
227
228         len  = gs_buf_space_avail(gb);
229         if (count > len)
230                 count = len;
231
232         if (count == 0)
233                 return 0;
234
235         len = gb->buf_buf + gb->buf_size - gb->buf_put;
236         if (count > len) {
237                 memcpy(gb->buf_put, buf, len);
238                 memcpy(gb->buf_buf, buf+len, count - len);
239                 gb->buf_put = gb->buf_buf + count - len;
240         } else {
241                 memcpy(gb->buf_put, buf, count);
242                 if (count < len)
243                         gb->buf_put += count;
244                 else /* count == len */
245                         gb->buf_put = gb->buf_buf;
246         }
247
248         return count;
249 }
250
251 /*
252  * gs_buf_get
253  *
254  * Get data from the circular buffer and copy to the given buffer.
255  * Restrict to the amount of data available.
256  *
257  * Return the number of bytes copied.
258  */
259 static unsigned
260 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
261 {
262         unsigned len;
263
264         len = gs_buf_data_avail(gb);
265         if (count > len)
266                 count = len;
267
268         if (count == 0)
269                 return 0;
270
271         len = gb->buf_buf + gb->buf_size - gb->buf_get;
272         if (count > len) {
273                 memcpy(buf, gb->buf_get, len);
274                 memcpy(buf+len, gb->buf_buf, count - len);
275                 gb->buf_get = gb->buf_buf + count - len;
276         } else {
277                 memcpy(buf, gb->buf_get, count);
278                 if (count < len)
279                         gb->buf_get += count;
280                 else /* count == len */
281                         gb->buf_get = gb->buf_buf;
282         }
283
284         return count;
285 }
286
287 /*-------------------------------------------------------------------------*/
288
289 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
290
291 /*
292  * gs_alloc_req
293  *
294  * Allocate a usb_request and its buffer.  Returns a pointer to the
295  * usb_request or NULL if there is an error.
296  */
297 struct usb_request *
298 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
299 {
300         struct usb_request *req;
301
302         req = usb_ep_alloc_request(ep, kmalloc_flags);
303
304         if (req != NULL) {
305                 req->length = len;
306                 req->buf = kmalloc(len, kmalloc_flags);
307                 if (req->buf == NULL) {
308                         usb_ep_free_request(ep, req);
309                         return NULL;
310                 }
311         }
312
313         return req;
314 }
315
316 /*
317  * gs_free_req
318  *
319  * Free a usb_request and its buffer.
320  */
321 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
322 {
323         kfree(req->buf);
324         usb_ep_free_request(ep, req);
325 }
326
327 /*
328  * gs_send_packet
329  *
330  * If there is data to send, a packet is built in the given
331  * buffer and the size is returned.  If there is no data to
332  * send, 0 is returned.
333  *
334  * Called with port_lock held.
335  */
336 static unsigned
337 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
338 {
339         unsigned len;
340
341         len = gs_buf_data_avail(&port->port_write_buf);
342         if (len < size)
343                 size = len;
344         if (size != 0)
345                 size = gs_buf_get(&port->port_write_buf, packet, size);
346         return size;
347 }
348
349 /*
350  * gs_start_tx
351  *
352  * This function finds available write requests, calls
353  * gs_send_packet to fill these packets with data, and
354  * continues until either there are no more write requests
355  * available or no more data to send.  This function is
356  * run whenever data arrives or write requests are available.
357  *
358  * Context: caller owns port_lock; port_usb is non-null.
359  */
360 static int gs_start_tx(struct gs_port *port)
361 /*
362 __releases(&port->port_lock)
363 __acquires(&port->port_lock)
364 */
365 {
366         struct list_head        *pool = &port->write_pool;
367         struct usb_ep           *in = NULL;
368         int                     status = 0;
369         bool                    do_tty_wake = false;
370
371         if (!port->port_usb){
372                 return status;
373         }
374         in = port->port_usb->in;
375
376         while (!list_empty(pool)) {
377                 struct usb_request      *req;
378                 int                     len;
379
380                 if (port->write_started >= QUEUE_SIZE)
381                         break;
382
383                 req = list_entry(pool->next, struct usb_request, list);
384                 len = gs_send_packet(port, req->buf, in->maxpacket);
385                 if (len == 0) {
386                         wake_up_interruptible(&port->drain_wait);
387                         break;
388                 }
389                 do_tty_wake = true;
390
391                 req->length = len;
392                 list_del(&req->list);
393                 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
394
395                 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
396                                 port->port_num, len, *((u8 *)req->buf),
397                                 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
398
399                 /* Drop lock while we call out of driver; completions
400                  * could be issued while we do so.  Disconnection may
401                  * happen too; maybe immediately before we queue this!
402                  *
403                  * NOTE that we may keep sending data for a while after
404                  * the TTY closed (dev->ioport->port_tty is NULL).
405                  */
406                 spin_unlock(&port->port_lock);
407                 status = usb_ep_queue(in, req, GFP_ATOMIC);
408                 spin_lock(&port->port_lock);
409
410                 if (status) {
411                         pr_debug("%s: %s %s err %d\n",
412                                         __func__, "queue", in->name, status);
413                         list_add(&req->list, pool);
414                         break;
415                 }
416
417                 port->write_started++;
418
419                 /* abort immediately after disconnect */
420                 if (!port->port_usb){
421                         break;
422                 }
423         }
424
425         //if (do_tty_wake && port->port_tty)
426         //      tty_wakeup(port->port_tty);
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(const 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 recycle:
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, 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         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, 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         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         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         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         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         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 static int gs_closed(struct gs_port *port)
1457 {
1458         int cond;
1459
1460         spin_lock_irq(&port->port_lock);
1461         cond = (port->open_count == 0) && !port->openclose;
1462         spin_unlock_irq(&port->port_lock);
1463         return cond;
1464 }
1465
1466 /**
1467  * gserial_cleanup - remove TTY-over-USB driver and devices
1468  * Context: may sleep
1469  *
1470  * This is called to free all resources allocated by @gserial_setup().
1471  * Accordingly, it may need to wait until some open /dev/ files have
1472  * closed.
1473  *
1474  * The caller must have issued @gserial_disconnect() for any ports
1475  * that had previously been connected, so that there is never any
1476  * I/O pending when it's called.
1477  */
1478 void gserial_cleanup(void)
1479 {
1480         unsigned        i;
1481         struct gs_port  *port;
1482         
1483 #if 0
1484         if (!gs_tty_driver)
1485                 return;
1486
1487         /* start sysfs and /dev/ttyGS* node removal */
1488         for (i = 0; i < n_ports; i++)
1489                 tty_unregister_device(gs_tty_driver, i);
1490 #endif
1491         for (i = 0; i < n_ports; i++) {
1492                 /* prevent new opens */
1493                 mutex_lock(&ports[i].lock);
1494                 port = ports[i].port;
1495                 ports[i].port = NULL;
1496                 mutex_unlock(&ports[i].lock);
1497
1498 //              tasklet_kill(&port->push);
1499
1500                 /* wait for old opens to finish */
1501 //              wait_event(port->close_wait, gs_closed(port));
1502
1503                 //WARN_ON(port->port_usb != NULL);
1504
1505                 kfree(port);
1506         }
1507         n_ports = 0;
1508
1509 //      tty_unregister_driver(gs_tty_driver);
1510 //      put_tty_driver(gs_tty_driver);
1511 //      gs_tty_driver = NULL;
1512
1513         pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1514 }
1515
1516 /**
1517  * gserial_connect - notify TTY I/O glue that USB link is active
1518  * @gser: the function, set up with endpoints and descriptors
1519  * @port_num: which port is active
1520  * Context: any (usually from irq)
1521  *
1522  * This is called activate endpoints and let the TTY layer know that
1523  * the connection is active ... not unlike "carrier detect".  It won't
1524  * necessarily start I/O queues; unless the TTY is held open by any
1525  * task, there would be no point.  However, the endpoints will be
1526  * activated so the USB host can perform I/O, subject to basic USB
1527  * hardware flow control.
1528  *
1529  * Caller needs to have set up the endpoints and USB function in @dev
1530  * before calling this, as well as the appropriate (speed-specific)
1531  * endpoint descriptors, and also have set up the TTY driver by calling
1532  * @gserial_setup().
1533  *
1534  * Returns negative errno or zero.
1535  * On success, ep->driver_data will be overwritten.
1536  */
1537 int gserial_connect(struct gserial *gser, u8 port_num)
1538 {
1539         struct gs_port  *port;
1540         unsigned long   flags;
1541         int             status;
1542 #if 0
1543         if (!gs_tty_driver || port_num >= n_ports)
1544                 return -ENXIO;
1545 #else
1546         if (port_num >= n_ports)
1547                 return -ENXIO;
1548
1549 #endif
1550
1551         /* we "know" gserial_cleanup() hasn't been called */
1552         port = ports[port_num].port;
1553
1554         /* activate the endpoints */
1555         status = usb_ep_enable(gser->in, gser->in_desc);
1556         if (status < 0)
1557                 return status;
1558         gser->in->driver_data = port;
1559
1560         status = usb_ep_enable(gser->out, gser->out_desc);
1561         if (status < 0)
1562                 goto fail_out;
1563         gser->out->driver_data = port;
1564
1565         /* then tell the tty glue that I/O can work */
1566         spin_lock_irqsave(&port->port_lock, flags);
1567         gser->ioport = port;
1568         port->port_usb = gser;
1569
1570         /* REVISIT unclear how best to handle this state...
1571          * we don't really couple it with the Linux TTY.
1572          */
1573         gser->port_line_coding = port->port_line_coding;
1574
1575         /* REVISIT if waiting on "carrier detect", signal. */
1576
1577         /* if it's already open, start I/O ... and notify the serial
1578          * protocol about open/close status (connect/disconnect).
1579          */
1580         if (port->open_count) {
1581                 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1582                 gs_start_io(port);
1583                 if (gser->connect)
1584                         gser->connect(gser);
1585         } else {
1586                 if (gser->disconnect)
1587                         gser->disconnect(gser);
1588         }
1589
1590         spin_unlock_irqrestore(&port->port_lock, flags);
1591
1592         return status;
1593
1594 fail_out:
1595         usb_ep_disable(gser->in);
1596         gser->in->driver_data = NULL;
1597         return status;
1598 }
1599
1600 /**
1601  * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1602  * @gser: the function, on which gserial_connect() was called
1603  * Context: any (usually from irq)
1604  *
1605  * This is called to deactivate endpoints and let the TTY layer know
1606  * that the connection went inactive ... not unlike "hangup".
1607  *
1608  * On return, the state is as if gserial_connect() had never been called;
1609  * there is no active USB I/O on these endpoints.
1610  */
1611 void gserial_disconnect(struct gserial *gser)
1612 {
1613         struct gs_port  *port = gser->ioport;
1614         unsigned long   flags;
1615
1616         if (!port)
1617                 return;
1618
1619         /* tell the TTY glue not to do I/O here any more */
1620         spin_lock_irqsave(&port->port_lock, flags);
1621
1622         /* REVISIT as above: how best to track this? */
1623         port->port_line_coding = gser->port_line_coding;
1624
1625         port->port_usb = NULL;
1626         gser->ioport = NULL;
1627         if (port->open_count > 0 || port->openclose) {
1628                 wake_up_interruptible(&port->drain_wait);
1629                 //if (port->port_tty)
1630                 //      tty_hangup(port->port_tty);
1631         }
1632         spin_unlock_irqrestore(&port->port_lock, flags);
1633
1634         /* disable endpoints, aborting down any active I/O */
1635         usb_ep_disable(gser->out);
1636         gser->out->driver_data = NULL;
1637
1638         usb_ep_disable(gser->in);
1639         gser->in->driver_data = NULL;
1640
1641         /* finally, free any unused/unusable I/O buffers */
1642         spin_lock_irqsave(&port->port_lock, flags);
1643         if (port->open_count == 0 && !port->openclose)
1644                 gs_buf_free(&port->port_write_buf);
1645         gs_free_requests(gser->out, &port->read_pool, NULL);
1646         gs_free_requests(gser->out, &port->read_queue, NULL);
1647         gs_free_requests(gser->in, &port->write_pool, NULL);
1648
1649         port->read_allocated = port->read_started =
1650                 port->write_allocated = port->write_started = 0;
1651
1652         spin_unlock_irqrestore(&port->port_lock, flags);
1653 }
1654 void gs_reset_usb_param(void)
1655 {
1656         vcom_port = 0;
1657         usb_write_done = 0;
1658         usb_read_done = 0;
1659         usb_trans_status = 0;
1660         usb_serial_configed = 0;
1661         usb_port_open = 0;
1662 }