upload tizen1.0 source
[kernel/linux-2.6.36.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
29 #include "u_serial.h"
30
31
32 /*
33  * This component encapsulates the TTY layer glue needed to provide basic
34  * "serial port" functionality through the USB gadget stack.  Each such
35  * port is exposed through a /dev/ttyGS* node.
36  *
37  * After initialization (gserial_setup), these TTY port devices stay
38  * available until they are removed (gserial_cleanup).  Each one may be
39  * connected to a USB function (gserial_connect), or disconnected (with
40  * gserial_disconnect) when the USB host issues a config change event.
41  * Data can only flow when the port is connected to the host.
42  *
43  * A given TTY port can be made available in multiple configurations.
44  * For example, each one might expose a ttyGS0 node which provides a
45  * login application.  In one case that might use CDC ACM interface 0,
46  * while another configuration might use interface 3 for that.  The
47  * work to handle that (including descriptor management) is not part
48  * of this component.
49  *
50  * Configurations may expose more than one TTY port.  For example, if
51  * ttyGS0 provides login service, then ttyGS1 might provide dialer access
52  * for a telephone or fax link.  And ttyGS2 might be something that just
53  * needs a simple byte stream interface for some messaging protocol that
54  * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
55  */
56
57 #define PREFIX  "ttyGS"
58
59 /*
60  * gserial is the lifecycle interface, used by USB functions
61  * gs_port is the I/O nexus, used by the tty driver
62  * tty_struct links to the tty/filesystem framework
63  *
64  * gserial <---> gs_port ... links will be null when the USB link is
65  * inactive; managed by gserial_{connect,disconnect}().  each gserial
66  * instance can wrap its own USB control protocol.
67  *      gserial->ioport == usb_ep->driver_data ... gs_port
68  *      gs_port->port_usb ... gserial
69  *
70  * gs_port <---> tty_struct ... links will be null when the TTY file
71  * isn't opened; managed by gs_open()/gs_close()
72  *      gserial->port_tty ... tty_struct
73  *      tty_struct->driver_data ... gserial
74  */
75
76 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
77  * next layer of buffering.  For TX that's a circular buffer; for RX
78  * consider it a NOP.  A third layer is provided by the TTY code.
79  */
80 #define QUEUE_SIZE              16
81 #define WRITE_BUF_SIZE          8192            /* TX only */
82
83 /* circular buffer */
84 struct gs_buf {
85         unsigned                buf_size;
86         char                    *buf_buf;
87         char                    *buf_get;
88         char                    *buf_put;
89 };
90
91 /*
92  * The port structure holds info for each port, one for each minor number
93  * (and thus for each /dev/ node).
94  */
95 struct gs_port {
96         spinlock_t              port_lock;      /* guard port_* access */
97
98         struct gserial          *port_usb;
99         struct tty_struct       *port_tty;
100
101         unsigned                open_count;
102         bool                    openclose;      /* open/close in progress */
103         u8                      port_num;
104
105         wait_queue_head_t       close_wait;     /* wait for last close */
106
107         struct list_head        read_pool;
108         struct list_head        read_queue;
109         unsigned                n_read;
110         struct tasklet_struct   push;
111
112         struct list_head        write_pool;
113         struct gs_buf           port_write_buf;
114         wait_queue_head_t       drain_wait;     /* wait while writes drain */
115
116         /* REVISIT this state ... */
117         struct usb_cdc_line_coding port_line_coding;    /* 8-N-1 etc */
118 };
119
120 /* increase N_PORTS if you need more */
121 #define N_PORTS         4
122 static struct portmaster {
123         struct mutex    lock;                   /* protect open/close */
124         struct gs_port  *port;
125 } ports[N_PORTS];
126 static unsigned n_ports;
127
128 #define GS_CLOSE_TIMEOUT                15              /* seconds */
129
130
131
132 #ifdef VERBOSE_DEBUG
133 #define pr_vdebug(fmt, arg...) \
134         pr_debug(fmt, ##arg)
135 #else
136 #define pr_vdebug(fmt, arg...) \
137         ({ if (0) pr_debug(fmt, ##arg); })
138 #endif
139
140 /*-------------------------------------------------------------------------*/
141
142 /* Circular Buffer */
143
144 /*
145  * gs_buf_alloc
146  *
147  * Allocate a circular buffer and all associated memory.
148  */
149 static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
150 {
151         gb->buf_buf = kmalloc(size, GFP_KERNEL);
152         if (gb->buf_buf == NULL)
153                 return -ENOMEM;
154
155         gb->buf_size = size;
156         gb->buf_put = gb->buf_buf;
157         gb->buf_get = gb->buf_buf;
158
159         return 0;
160 }
161
162 /*
163  * gs_buf_free
164  *
165  * Free the buffer and all associated memory.
166  */
167 static void gs_buf_free(struct gs_buf *gb)
168 {
169         kfree(gb->buf_buf);
170         gb->buf_buf = NULL;
171 }
172
173 /*
174  * gs_buf_clear
175  *
176  * Clear out all data in the circular buffer.
177  */
178 static void gs_buf_clear(struct gs_buf *gb)
179 {
180         gb->buf_get = gb->buf_put;
181         /* equivalent to a get of all data available */
182 }
183
184 /*
185  * gs_buf_data_avail
186  *
187  * Return the number of bytes of data written into the circular
188  * buffer.
189  */
190 static unsigned gs_buf_data_avail(struct gs_buf *gb)
191 {
192         return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
193 }
194
195 /*
196  * gs_buf_space_avail
197  *
198  * Return the number of bytes of space available in the circular
199  * buffer.
200  */
201 static unsigned gs_buf_space_avail(struct gs_buf *gb)
202 {
203         return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
204 }
205
206 /*
207  * gs_buf_put
208  *
209  * Copy data data from a user buffer and put it into the circular buffer.
210  * Restrict to the amount of space available.
211  *
212  * Return the number of bytes copied.
213  */
214 static unsigned
215 gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
216 {
217         unsigned len;
218
219         len  = gs_buf_space_avail(gb);
220         if (count > len)
221                 count = len;
222
223         if (count == 0)
224                 return 0;
225
226         len = gb->buf_buf + gb->buf_size - gb->buf_put;
227         if (count > len) {
228                 memcpy(gb->buf_put, buf, len);
229                 memcpy(gb->buf_buf, buf+len, count - len);
230                 gb->buf_put = gb->buf_buf + count - len;
231         } else {
232                 memcpy(gb->buf_put, buf, count);
233                 if (count < len)
234                         gb->buf_put += count;
235                 else /* count == len */
236                         gb->buf_put = gb->buf_buf;
237         }
238
239         return count;
240 }
241
242 /*
243  * gs_buf_get
244  *
245  * Get data from the circular buffer and copy to the given buffer.
246  * Restrict to the amount of data available.
247  *
248  * Return the number of bytes copied.
249  */
250 static unsigned
251 gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
252 {
253         unsigned len;
254
255         len = gs_buf_data_avail(gb);
256         if (count > len)
257                 count = len;
258
259         if (count == 0)
260                 return 0;
261
262         len = gb->buf_buf + gb->buf_size - gb->buf_get;
263         if (count > len) {
264                 memcpy(buf, gb->buf_get, len);
265                 memcpy(buf+len, gb->buf_buf, count - len);
266                 gb->buf_get = gb->buf_buf + count - len;
267         } else {
268                 memcpy(buf, gb->buf_get, count);
269                 if (count < len)
270                         gb->buf_get += count;
271                 else /* count == len */
272                         gb->buf_get = gb->buf_buf;
273         }
274
275         return count;
276 }
277
278 /*-------------------------------------------------------------------------*/
279
280 /* I/O glue between TTY (upper) and USB function (lower) driver layers */
281
282 /*
283  * gs_alloc_req
284  *
285  * Allocate a usb_request and its buffer.  Returns a pointer to the
286  * usb_request or NULL if there is an error.
287  */
288 struct usb_request *
289 gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
290 {
291         struct usb_request *req;
292
293         req = usb_ep_alloc_request(ep, kmalloc_flags);
294
295         if (req != NULL) {
296                 req->length = len;
297                 req->buf = kmalloc(len, kmalloc_flags);
298                 if (req->buf == NULL) {
299                         usb_ep_free_request(ep, req);
300                         return NULL;
301                 }
302         }
303
304         return req;
305 }
306
307 /*
308  * gs_free_req
309  *
310  * Free a usb_request and its buffer.
311  */
312 void gs_free_req(struct usb_ep *ep, struct usb_request *req)
313 {
314         kfree(req->buf);
315         usb_ep_free_request(ep, req);
316 }
317
318 /*
319  * gs_send_packet
320  *
321  * If there is data to send, a packet is built in the given
322  * buffer and the size is returned.  If there is no data to
323  * send, 0 is returned.
324  *
325  * Called with port_lock held.
326  */
327 static unsigned
328 gs_send_packet(struct gs_port *port, char *packet, unsigned size)
329 {
330         unsigned len;
331
332         len = gs_buf_data_avail(&port->port_write_buf);
333         if (len < size)
334                 size = len;
335         if (size != 0)
336                 size = gs_buf_get(&port->port_write_buf, packet, size);
337         return size;
338 }
339
340 /*
341  * gs_start_tx
342  *
343  * This function finds available write requests, calls
344  * gs_send_packet to fill these packets with data, and
345  * continues until either there are no more write requests
346  * available or no more data to send.  This function is
347  * run whenever data arrives or write requests are available.
348  *
349  * Context: caller owns port_lock; port_usb is non-null.
350  */
351 static int gs_start_tx(struct gs_port *port)
352 /*
353 __releases(&port->port_lock)
354 __acquires(&port->port_lock)
355 */
356 {
357         struct list_head        *pool = &port->write_pool;
358         struct usb_ep           *in = port->port_usb->in;
359         int                     status = 0;
360         bool                    do_tty_wake = false;
361
362         while (!list_empty(pool)) {
363                 struct usb_request      *req;
364                 int                     len;
365
366                 req = list_entry(pool->next, struct usb_request, list);
367                 len = gs_send_packet(port, req->buf, in->maxpacket);
368                 if (len == 0) {
369                         wake_up_interruptible(&port->drain_wait);
370                         break;
371                 }
372                 do_tty_wake = true;
373
374                 req->length = len;
375                 list_del(&req->list);
376                 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
377
378                 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
379                                 port->port_num, len, *((u8 *)req->buf),
380                                 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
381
382                 /* Drop lock while we call out of driver; completions
383                  * could be issued while we do so.  Disconnection may
384                  * happen too; maybe immediately before we queue this!
385                  *
386                  * NOTE that we may keep sending data for a while after
387                  * the TTY closed (dev->ioport->port_tty is NULL).
388                  */
389                 spin_unlock(&port->port_lock);
390                 status = usb_ep_queue(in, req, GFP_ATOMIC);
391                 spin_lock(&port->port_lock);
392
393                 if (status) {
394                         pr_debug("%s: %s %s err %d\n",
395                                         __func__, "queue", in->name, status);
396                         list_add(&req->list, pool);
397                         break;
398                 }
399
400                 /* abort immediately after disconnect */
401                 if (!port->port_usb)
402                         break;
403         }
404
405         if (do_tty_wake && port->port_tty)
406                 tty_wakeup(port->port_tty);
407         return status;
408 }
409
410 /*
411  * Context: caller owns port_lock, and port_usb is set
412  */
413 static unsigned gs_start_rx(struct gs_port *port)
414 /*
415 __releases(&port->port_lock)
416 __acquires(&port->port_lock)
417 */
418 {
419         struct list_head        *pool = &port->read_pool;
420         struct usb_ep           *out = port->port_usb->out;
421         unsigned                started = 0;
422
423         while (!list_empty(pool)) {
424                 struct usb_request      *req;
425                 int                     status;
426                 struct tty_struct       *tty;
427
428                 /* no more rx if closed */
429                 tty = port->port_tty;
430                 if (!tty)
431                         break;
432
433                 req = list_entry(pool->next, struct usb_request, list);
434                 list_del(&req->list);
435                 req->length = out->maxpacket;
436
437                 /* drop lock while we call out; the controller driver
438                  * may need to call us back (e.g. for disconnect)
439                  */
440                 spin_unlock(&port->port_lock);
441                 status = usb_ep_queue(out, req, GFP_ATOMIC);
442                 spin_lock(&port->port_lock);
443
444                 if (status) {
445                         pr_debug("%s: %s %s err %d\n",
446                                         __func__, "queue", out->name, status);
447                         list_add(&req->list, pool);
448                         break;
449                 }
450                 started++;
451
452                 /* abort immediately after disconnect */
453                 if (!port->port_usb)
454                         break;
455         }
456         return started;
457 }
458
459 /*
460  * RX tasklet takes data out of the RX queue and hands it up to the TTY
461  * layer until it refuses to take any more data (or is throttled back).
462  * Then it issues reads for any further data.
463  *
464  * If the RX queue becomes full enough that no usb_request is queued,
465  * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
466  * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
467  * can be buffered before the TTY layer's buffers (currently 64 KB).
468  */
469 static void gs_rx_push(unsigned long _port)
470 {
471         struct gs_port          *port = (void *)_port;
472         struct tty_struct       *tty;
473         struct list_head        *queue = &port->read_queue;
474         bool                    disconnect = false;
475         bool                    do_push = false;
476
477         /* hand any queued data to the tty */
478         spin_lock_irq(&port->port_lock);
479         tty = port->port_tty;
480         while (!list_empty(queue)) {
481                 struct usb_request      *req;
482
483                 req = list_first_entry(queue, struct usb_request, list);
484
485                 /* discard data if tty was closed */
486                 if (!tty)
487                         goto recycle;
488
489                 /* leave data queued if tty was rx throttled */
490                 if (test_bit(TTY_THROTTLED, &tty->flags))
491                         break;
492
493                 switch (req->status) {
494                 case -ESHUTDOWN:
495                         disconnect = true;
496                         pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
497                         break;
498
499                 default:
500                         /* presumably a transient fault */
501                         pr_warning(PREFIX "%d: unexpected RX status %d\n",
502                                         port->port_num, req->status);
503                         /* FALLTHROUGH */
504                 case 0:
505                         /* normal completion */
506                         break;
507                 }
508
509                 /* push data to (open) tty */
510                 if (req->actual) {
511                         char            *packet = req->buf;
512                         unsigned        size = req->actual;
513                         unsigned        n;
514                         int             count;
515
516                         /* we may have pushed part of this packet already... */
517                         n = port->n_read;
518                         if (n) {
519                                 packet += n;
520                                 size -= n;
521                         }
522
523                         count = tty_insert_flip_string(tty, packet, size);
524                         if (count)
525                                 do_push = true;
526                         if (count != size) {
527                                 /* stop pushing; TTY layer can't handle more */
528                                 port->n_read += count;
529                                 pr_vdebug(PREFIX "%d: rx block %d/%d\n",
530                                                 port->port_num,
531                                                 count, req->actual);
532                                 break;
533                         }
534                         port->n_read = 0;
535                 }
536 recycle:
537                 list_move(&req->list, &port->read_pool);
538         }
539
540         /* Push from tty to ldisc; without low_latency set this is handled by
541          * a workqueue, so we won't get callbacks and can hold port_lock
542          */
543         if (tty && do_push) {
544                 tty_flip_buffer_push(tty);
545         }
546
547
548         /* We want our data queue to become empty ASAP, keeping data
549          * in the tty and ldisc (not here).  If we couldn't push any
550          * this time around, there may be trouble unless there's an
551          * implicit tty_unthrottle() call on its way...
552          *
553          * REVISIT we should probably add a timer to keep the tasklet
554          * from starving ... but it's not clear that case ever happens.
555          */
556         if (!list_empty(queue) && tty) {
557                 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
558                         if (do_push)
559                                 tasklet_schedule(&port->push);
560                         else
561                                 pr_warning(PREFIX "%d: RX not scheduled?\n",
562                                         port->port_num);
563                 }
564         }
565
566         /* If we're still connected, refill the USB RX queue. */
567         if (!disconnect && port->port_usb)
568                 gs_start_rx(port);
569
570         spin_unlock_irq(&port->port_lock);
571 }
572
573 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
574 {
575         struct gs_port  *port = ep->driver_data;
576
577         /* Queue all received data until the tty layer is ready for it. */
578         spin_lock(&port->port_lock);
579         list_add_tail(&req->list, &port->read_queue);
580         tasklet_schedule(&port->push);
581         spin_unlock(&port->port_lock);
582 }
583
584 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
585 {
586         struct gs_port  *port = ep->driver_data;
587
588         spin_lock(&port->port_lock);
589         list_add(&req->list, &port->write_pool);
590
591         switch (req->status) {
592         default:
593                 /* presumably a transient fault */
594                 pr_warning("%s: unexpected %s status %d\n",
595                                 __func__, ep->name, req->status);
596                 /* FALL THROUGH */
597         case 0:
598                 /* normal completion */
599                 gs_start_tx(port);
600                 break;
601
602         case -ESHUTDOWN:
603                 /* disconnect */
604                 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
605                 break;
606         }
607
608         spin_unlock(&port->port_lock);
609 }
610
611 static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
612 {
613         struct usb_request      *req;
614
615         while (!list_empty(head)) {
616                 req = list_entry(head->next, struct usb_request, list);
617                 list_del(&req->list);
618                 gs_free_req(ep, req);
619         }
620 }
621
622 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
623                 void (*fn)(struct usb_ep *, struct usb_request *))
624 {
625         int                     i;
626         struct usb_request      *req;
627
628         /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
629          * do quite that many this time, don't fail ... we just won't
630          * be as speedy as we might otherwise be.
631          */
632         for (i = 0; i < QUEUE_SIZE; i++) {
633                 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
634                 if (!req)
635                         return list_empty(head) ? -ENOMEM : 0;
636                 req->complete = fn;
637                 list_add_tail(&req->list, head);
638         }
639         return 0;
640 }
641
642 /**
643  * gs_start_io - start USB I/O streams
644  * @dev: encapsulates endpoints to use
645  * Context: holding port_lock; port_tty and port_usb are non-null
646  *
647  * We only start I/O when something is connected to both sides of
648  * this port.  If nothing is listening on the host side, we may
649  * be pointlessly filling up our TX buffers and FIFO.
650  */
651 static int gs_start_io(struct gs_port *port)
652 {
653         struct list_head        *head = &port->read_pool;
654         struct usb_ep           *ep = port->port_usb->out;
655         int                     status;
656         unsigned                started;
657
658         /* Allocate RX and TX I/O buffers.  We can't easily do this much
659          * earlier (with GFP_KERNEL) because the requests are coupled to
660          * endpoints, as are the packet sizes we'll be using.  Different
661          * configurations may use different endpoints with a given port;
662          * and high speed vs full speed changes packet sizes too.
663          */
664         status = gs_alloc_requests(ep, head, gs_read_complete);
665         if (status)
666                 return status;
667
668         status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
669                         gs_write_complete);
670         if (status) {
671                 gs_free_requests(ep, head);
672                 return status;
673         }
674
675         /* queue read requests */
676         port->n_read = 0;
677         started = gs_start_rx(port);
678
679         /* unblock any pending writes into our circular buffer */
680         if (started) {
681                 tty_wakeup(port->port_tty);
682         } else {
683                 gs_free_requests(ep, head);
684                 gs_free_requests(port->port_usb->in, &port->write_pool);
685                 status = -EIO;
686         }
687
688         return status;
689 }
690
691 /*-------------------------------------------------------------------------*/
692
693 /* TTY Driver */
694
695 /*
696  * gs_open sets up the link between a gs_port and its associated TTY.
697  * That link is broken *only* by TTY close(), and all driver methods
698  * know that.
699  */
700 static int gs_open(struct tty_struct *tty, struct file *file)
701 {
702         int             port_num = tty->index;
703         struct gs_port  *port;
704         int             status;
705
706         if (port_num < 0 || port_num >= n_ports)
707                 return -ENXIO;
708
709         do {
710                 mutex_lock(&ports[port_num].lock);
711                 port = ports[port_num].port;
712                 if (!port)
713                         status = -ENODEV;
714                 else {
715                         spin_lock_irq(&port->port_lock);
716
717                         /* already open?  Great. */
718                         if (port->open_count) {
719                                 status = 0;
720                                 port->open_count++;
721
722                         /* currently opening/closing? wait ... */
723                         } else if (port->openclose) {
724                                 status = -EBUSY;
725
726                         /* ... else we do the work */
727                         } else {
728                                 status = -EAGAIN;
729                                 port->openclose = true;
730                         }
731                         spin_unlock_irq(&port->port_lock);
732                 }
733                 mutex_unlock(&ports[port_num].lock);
734
735                 switch (status) {
736                 default:
737                         /* fully handled */
738                         return status;
739                 case -EAGAIN:
740                         /* must do the work */
741                         break;
742                 case -EBUSY:
743                         /* wait for EAGAIN task to finish */
744                         msleep(1);
745                         /* REVISIT could have a waitchannel here, if
746                          * concurrent open performance is important
747                          */
748                         break;
749                 }
750         } while (status != -EAGAIN);
751
752         /* Do the "real open" */
753         spin_lock_irq(&port->port_lock);
754
755         /* allocate circular buffer on first open */
756         if (port->port_write_buf.buf_buf == NULL) {
757
758                 spin_unlock_irq(&port->port_lock);
759                 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
760                 spin_lock_irq(&port->port_lock);
761
762                 if (status) {
763                         pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
764                                 port->port_num, tty, file);
765                         port->openclose = false;
766                         goto exit_unlock_port;
767                 }
768         }
769
770         /* REVISIT if REMOVED (ports[].port NULL), abort the open
771          * to let rmmod work faster (but this way isn't wrong).
772          */
773
774         /* REVISIT maybe wait for "carrier detect" */
775
776         tty->driver_data = port;
777         port->port_tty = tty;
778
779         port->open_count = 1;
780         port->openclose = false;
781
782         /* if connected, start the I/O stream */
783         if (port->port_usb) {
784                 struct gserial  *gser = port->port_usb;
785
786                 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
787                 gs_start_io(port);
788
789                 if (gser->connect)
790                         gser->connect(gser);
791         }
792
793         pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
794
795         status = 0;
796
797 exit_unlock_port:
798         spin_unlock_irq(&port->port_lock);
799         return status;
800 }
801
802 static int gs_writes_finished(struct gs_port *p)
803 {
804         int cond;
805
806         /* return true on disconnect or empty buffer */
807         spin_lock_irq(&p->port_lock);
808         cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
809         spin_unlock_irq(&p->port_lock);
810
811         return cond;
812 }
813
814 static void gs_close(struct tty_struct *tty, struct file *file)
815 {
816         struct gs_port *port = tty->driver_data;
817         struct gserial  *gser;
818
819         spin_lock_irq(&port->port_lock);
820
821         if (port->open_count != 1) {
822                 if (port->open_count == 0)
823                         WARN_ON(1);
824                 else
825                         --port->open_count;
826                 goto exit;
827         }
828
829         pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
830
831         /* mark port as closing but in use; we can drop port lock
832          * and sleep if necessary
833          */
834         port->openclose = true;
835         port->open_count = 0;
836
837         gser = port->port_usb;
838         if (gser && gser->disconnect)
839                 gser->disconnect(gser);
840
841         /* wait for circular write buffer to drain, disconnect, or at
842          * most GS_CLOSE_TIMEOUT seconds; then discard the rest
843          */
844         if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
845                 spin_unlock_irq(&port->port_lock);
846                 wait_event_interruptible_timeout(port->drain_wait,
847                                         gs_writes_finished(port),
848                                         GS_CLOSE_TIMEOUT * HZ);
849                 spin_lock_irq(&port->port_lock);
850                 gser = port->port_usb;
851         }
852
853         /* Iff we're disconnected, there can be no I/O in flight so it's
854          * ok to free the circular buffer; else just scrub it.  And don't
855          * let the push tasklet fire again until we're re-opened.
856          */
857         if (gser == NULL)
858                 gs_buf_free(&port->port_write_buf);
859         else
860                 gs_buf_clear(&port->port_write_buf);
861
862         tty->driver_data = NULL;
863         port->port_tty = NULL;
864
865         port->openclose = false;
866
867         pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
868                         port->port_num, tty, file);
869
870         wake_up_interruptible(&port->close_wait);
871 exit:
872         spin_unlock_irq(&port->port_lock);
873 }
874
875 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
876 {
877         struct gs_port  *port = tty->driver_data;
878         unsigned long   flags;
879         int             status;
880
881         pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
882                         port->port_num, tty, count);
883
884         spin_lock_irqsave(&port->port_lock, flags);
885         if (count)
886                 count = gs_buf_put(&port->port_write_buf, buf, count);
887         /* treat count == 0 as flush_chars() */
888         if (port->port_usb)
889                 status = gs_start_tx(port);
890         spin_unlock_irqrestore(&port->port_lock, flags);
891
892         return count;
893 }
894
895 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
896 {
897         struct gs_port  *port = tty->driver_data;
898         unsigned long   flags;
899         int             status;
900
901         pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
902                 port->port_num, tty, ch, __builtin_return_address(0));
903
904         spin_lock_irqsave(&port->port_lock, flags);
905         status = gs_buf_put(&port->port_write_buf, &ch, 1);
906         spin_unlock_irqrestore(&port->port_lock, flags);
907
908         return status;
909 }
910
911 static void gs_flush_chars(struct tty_struct *tty)
912 {
913         struct gs_port  *port = tty->driver_data;
914         unsigned long   flags;
915
916         pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
917
918         spin_lock_irqsave(&port->port_lock, flags);
919         if (port->port_usb)
920                 gs_start_tx(port);
921         spin_unlock_irqrestore(&port->port_lock, flags);
922 }
923
924 static int gs_write_room(struct tty_struct *tty)
925 {
926         struct gs_port  *port = tty->driver_data;
927         unsigned long   flags;
928         int             room = 0;
929
930         spin_lock_irqsave(&port->port_lock, flags);
931         if (port->port_usb)
932                 room = gs_buf_space_avail(&port->port_write_buf);
933         spin_unlock_irqrestore(&port->port_lock, flags);
934
935         pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
936                 port->port_num, tty, room);
937
938         return room;
939 }
940
941 static int gs_chars_in_buffer(struct tty_struct *tty)
942 {
943         struct gs_port  *port = tty->driver_data;
944         unsigned long   flags;
945         int             chars = 0;
946
947         spin_lock_irqsave(&port->port_lock, flags);
948         chars = gs_buf_data_avail(&port->port_write_buf);
949         spin_unlock_irqrestore(&port->port_lock, flags);
950
951         pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
952                 port->port_num, tty, chars);
953
954         return chars;
955 }
956
957 /* undo side effects of setting TTY_THROTTLED */
958 static void gs_unthrottle(struct tty_struct *tty)
959 {
960         struct gs_port          *port = tty->driver_data;
961         unsigned long           flags;
962
963         spin_lock_irqsave(&port->port_lock, flags);
964         if (port->port_usb) {
965                 /* Kickstart read queue processing.  We don't do xon/xoff,
966                  * rts/cts, or other handshaking with the host, but if the
967                  * read queue backs up enough we'll be NAKing OUT packets.
968                  */
969                 tasklet_schedule(&port->push);
970                 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
971         }
972         spin_unlock_irqrestore(&port->port_lock, flags);
973 }
974
975 static int gs_break_ctl(struct tty_struct *tty, int duration)
976 {
977         struct gs_port  *port = tty->driver_data;
978         int             status = 0;
979         struct gserial  *gser;
980
981         pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
982                         port->port_num, duration);
983
984         spin_lock_irq(&port->port_lock);
985         gser = port->port_usb;
986         if (gser && gser->send_break)
987                 status = gser->send_break(gser, duration);
988         spin_unlock_irq(&port->port_lock);
989
990         return status;
991 }
992
993 static const struct tty_operations gs_tty_ops = {
994         .open =                 gs_open,
995         .close =                gs_close,
996         .write =                gs_write,
997         .put_char =             gs_put_char,
998         .flush_chars =          gs_flush_chars,
999         .write_room =           gs_write_room,
1000         .chars_in_buffer =      gs_chars_in_buffer,
1001         .unthrottle =           gs_unthrottle,
1002         .break_ctl =            gs_break_ctl,
1003 };
1004
1005 /*-------------------------------------------------------------------------*/
1006
1007 static struct tty_driver *gs_tty_driver;
1008
1009 static int __init
1010 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1011 {
1012         struct gs_port  *port;
1013
1014         port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1015         if (port == NULL)
1016                 return -ENOMEM;
1017
1018         spin_lock_init(&port->port_lock);
1019         init_waitqueue_head(&port->close_wait);
1020         init_waitqueue_head(&port->drain_wait);
1021
1022         tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1023
1024         INIT_LIST_HEAD(&port->read_pool);
1025         INIT_LIST_HEAD(&port->read_queue);
1026         INIT_LIST_HEAD(&port->write_pool);
1027
1028         port->port_num = port_num;
1029         port->port_line_coding = *coding;
1030
1031         ports[port_num].port = port;
1032
1033         return 0;
1034 }
1035
1036 /**
1037  * gserial_setup - initialize TTY driver for one or more ports
1038  * @g: gadget to associate with these ports
1039  * @count: how many ports to support
1040  * Context: may sleep
1041  *
1042  * The TTY stack needs to know in advance how many devices it should
1043  * plan to manage.  Use this call to set up the ports you will be
1044  * exporting through USB.  Later, connect them to functions based
1045  * on what configuration is activated by the USB host; and disconnect
1046  * them as appropriate.
1047  *
1048  * An example would be a two-configuration device in which both
1049  * configurations expose port 0, but through different functions.
1050  * One configuration could even expose port 1 while the other
1051  * one doesn't.
1052  *
1053  * Returns negative errno or zero.
1054  */
1055 int __init gserial_setup(struct usb_gadget *g, unsigned count)
1056 {
1057         unsigned                        i;
1058         struct usb_cdc_line_coding      coding;
1059         int                             status;
1060
1061         if (count == 0 || count > N_PORTS)
1062                 return -EINVAL;
1063
1064         gs_tty_driver = alloc_tty_driver(count);
1065         if (!gs_tty_driver)
1066                 return -ENOMEM;
1067
1068         gs_tty_driver->owner = THIS_MODULE;
1069         gs_tty_driver->driver_name = "g_serial";
1070         gs_tty_driver->name = PREFIX;
1071         /* uses dynamically assigned dev_t values */
1072
1073         gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1074         gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1075         gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1076         gs_tty_driver->init_termios = tty_std_termios;
1077
1078         /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1079          * MS-Windows.  Otherwise, most of these flags shouldn't affect
1080          * anything unless we were to actually hook up to a serial line.
1081          */
1082         gs_tty_driver->init_termios.c_cflag =
1083                         B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1084         gs_tty_driver->init_termios.c_ispeed = 9600;
1085         gs_tty_driver->init_termios.c_ospeed = 9600;
1086
1087         coding.dwDTERate = cpu_to_le32(9600);
1088         coding.bCharFormat = 8;
1089         coding.bParityType = USB_CDC_NO_PARITY;
1090         coding.bDataBits = USB_CDC_1_STOP_BITS;
1091
1092         tty_set_operations(gs_tty_driver, &gs_tty_ops);
1093
1094         /* make devices be openable */
1095         for (i = 0; i < count; i++) {
1096                 mutex_init(&ports[i].lock);
1097                 status = gs_port_alloc(i, &coding);
1098                 if (status) {
1099                         count = i;
1100                         goto fail;
1101                 }
1102         }
1103         n_ports = count;
1104
1105         /* export the driver ... */
1106         status = tty_register_driver(gs_tty_driver);
1107         if (status) {
1108                 pr_err("%s: cannot register, err %d\n",
1109                                 __func__, status);
1110                 goto fail;
1111         }
1112
1113         /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1114         for (i = 0; i < count; i++) {
1115                 struct device   *tty_dev;
1116
1117                 tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
1118                 if (IS_ERR(tty_dev))
1119                         pr_warning("%s: no classdev for port %d, err %ld\n",
1120                                 __func__, i, PTR_ERR(tty_dev));
1121         }
1122
1123         pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1124                         count, (count == 1) ? "" : "s");
1125
1126         return status;
1127 fail:
1128         while (count--)
1129                 kfree(ports[count].port);
1130         put_tty_driver(gs_tty_driver);
1131         gs_tty_driver = NULL;
1132         return status;
1133 }
1134
1135 static int gs_closed(struct gs_port *port)
1136 {
1137         int cond;
1138
1139         spin_lock_irq(&port->port_lock);
1140         cond = (port->open_count == 0) && !port->openclose;
1141         spin_unlock_irq(&port->port_lock);
1142         return cond;
1143 }
1144
1145 /**
1146  * gserial_cleanup - remove TTY-over-USB driver and devices
1147  * Context: may sleep
1148  *
1149  * This is called to free all resources allocated by @gserial_setup().
1150  * Accordingly, it may need to wait until some open /dev/ files have
1151  * closed.
1152  *
1153  * The caller must have issued @gserial_disconnect() for any ports
1154  * that had previously been connected, so that there is never any
1155  * I/O pending when it's called.
1156  */
1157 void gserial_cleanup(void)
1158 {
1159         unsigned        i;
1160         struct gs_port  *port;
1161
1162         if (!gs_tty_driver)
1163                 return;
1164
1165         /* start sysfs and /dev/ttyGS* node removal */
1166         for (i = 0; i < n_ports; i++)
1167                 tty_unregister_device(gs_tty_driver, i);
1168
1169         for (i = 0; i < n_ports; i++) {
1170                 /* prevent new opens */
1171                 mutex_lock(&ports[i].lock);
1172                 port = ports[i].port;
1173                 ports[i].port = NULL;
1174                 mutex_unlock(&ports[i].lock);
1175
1176                 tasklet_kill(&port->push);
1177
1178                 /* wait for old opens to finish */
1179                 wait_event(port->close_wait, gs_closed(port));
1180
1181                 WARN_ON(port->port_usb != NULL);
1182
1183                 kfree(port);
1184         }
1185         n_ports = 0;
1186
1187         tty_unregister_driver(gs_tty_driver);
1188         put_tty_driver(gs_tty_driver);
1189         gs_tty_driver = NULL;
1190
1191         pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1192 }
1193
1194 /**
1195  * gserial_connect - notify TTY I/O glue that USB link is active
1196  * @gser: the function, set up with endpoints and descriptors
1197  * @port_num: which port is active
1198  * Context: any (usually from irq)
1199  *
1200  * This is called activate endpoints and let the TTY layer know that
1201  * the connection is active ... not unlike "carrier detect".  It won't
1202  * necessarily start I/O queues; unless the TTY is held open by any
1203  * task, there would be no point.  However, the endpoints will be
1204  * activated so the USB host can perform I/O, subject to basic USB
1205  * hardware flow control.
1206  *
1207  * Caller needs to have set up the endpoints and USB function in @dev
1208  * before calling this, as well as the appropriate (speed-specific)
1209  * endpoint descriptors, and also have set up the TTY driver by calling
1210  * @gserial_setup().
1211  *
1212  * Returns negative errno or zero.
1213  * On success, ep->driver_data will be overwritten.
1214  */
1215 int gserial_connect(struct gserial *gser, u8 port_num)
1216 {
1217         struct gs_port  *port;
1218         unsigned long   flags;
1219         int             status;
1220
1221         if (!gs_tty_driver || port_num >= n_ports)
1222                 return -ENXIO;
1223
1224         /* we "know" gserial_cleanup() hasn't been called */
1225         port = ports[port_num].port;
1226
1227         /* activate the endpoints */
1228         status = usb_ep_enable(gser->in, gser->in_desc);
1229         if (status < 0)
1230                 return status;
1231         gser->in->driver_data = port;
1232
1233         status = usb_ep_enable(gser->out, gser->out_desc);
1234         if (status < 0)
1235                 goto fail_out;
1236         gser->out->driver_data = port;
1237
1238         /* then tell the tty glue that I/O can work */
1239         spin_lock_irqsave(&port->port_lock, flags);
1240         gser->ioport = port;
1241         port->port_usb = gser;
1242
1243         /* REVISIT unclear how best to handle this state...
1244          * we don't really couple it with the Linux TTY.
1245          */
1246         gser->port_line_coding = port->port_line_coding;
1247
1248         /* REVISIT if waiting on "carrier detect", signal. */
1249
1250         /* if it's already open, start I/O ... and notify the serial
1251          * protocol about open/close status (connect/disconnect).
1252          */
1253         if (port->open_count) {
1254                 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1255                 gs_start_io(port);
1256                 if (gser->connect)
1257                         gser->connect(gser);
1258         } else {
1259                 if (gser->disconnect)
1260                         gser->disconnect(gser);
1261         }
1262
1263         spin_unlock_irqrestore(&port->port_lock, flags);
1264
1265         return status;
1266
1267 fail_out:
1268         usb_ep_disable(gser->in);
1269         gser->in->driver_data = NULL;
1270         return status;
1271 }
1272
1273 /**
1274  * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1275  * @gser: the function, on which gserial_connect() was called
1276  * Context: any (usually from irq)
1277  *
1278  * This is called to deactivate endpoints and let the TTY layer know
1279  * that the connection went inactive ... not unlike "hangup".
1280  *
1281  * On return, the state is as if gserial_connect() had never been called;
1282  * there is no active USB I/O on these endpoints.
1283  */
1284 void gserial_disconnect(struct gserial *gser)
1285 {
1286         struct gs_port  *port = gser->ioport;
1287         unsigned long   flags;
1288
1289         if (!port)
1290                 return;
1291
1292         /* tell the TTY glue not to do I/O here any more */
1293         spin_lock_irqsave(&port->port_lock, flags);
1294
1295         /* REVISIT as above: how best to track this? */
1296         port->port_line_coding = gser->port_line_coding;
1297
1298         port->port_usb = NULL;
1299         gser->ioport = NULL;
1300         if (port->open_count > 0 || port->openclose) {
1301                 wake_up_interruptible(&port->drain_wait);
1302                 if (port->port_tty)
1303                         tty_hangup(port->port_tty);
1304         }
1305         spin_unlock_irqrestore(&port->port_lock, flags);
1306
1307         /* disable endpoints, aborting down any active I/O */
1308         usb_ep_disable(gser->out);
1309         gser->out->driver_data = NULL;
1310
1311         usb_ep_disable(gser->in);
1312         gser->in->driver_data = NULL;
1313
1314         /* finally, free any unused/unusable I/O buffers */
1315         spin_lock_irqsave(&port->port_lock, flags);
1316         if (port->open_count == 0 && !port->openclose)
1317                 gs_buf_free(&port->port_write_buf);
1318         gs_free_requests(gser->out, &port->read_pool);
1319         gs_free_requests(gser->out, &port->read_queue);
1320         gs_free_requests(gser->in, &port->write_pool);
1321         spin_unlock_irqrestore(&port->port_lock, flags);
1322 }