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