Merge branch 'drm-ttm-unmappable' into drm-core-next
[pandora-kernel.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; this is immediate with low_latency, and
540          * may trigger callbacks to this driver ... so drop the spinlock.
541          */
542         if (tty && do_push) {
543                 spin_unlock_irq(&port->port_lock);
544                 tty_flip_buffer_push(tty);
545                 wake_up_interruptible(&tty->read_wait);
546                 spin_lock_irq(&port->port_lock);
547
548                 /* tty may have been closed */
549                 tty = port->port_tty;
550         }
551
552
553         /* We want our data queue to become empty ASAP, keeping data
554          * in the tty and ldisc (not here).  If we couldn't push any
555          * this time around, there may be trouble unless there's an
556          * implicit tty_unthrottle() call on its way...
557          *
558          * REVISIT we should probably add a timer to keep the tasklet
559          * from starving ... but it's not clear that case ever happens.
560          */
561         if (!list_empty(queue) && tty) {
562                 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
563                         if (do_push)
564                                 tasklet_schedule(&port->push);
565                         else
566                                 pr_warning(PREFIX "%d: RX not scheduled?\n",
567                                         port->port_num);
568                 }
569         }
570
571         /* If we're still connected, refill the USB RX queue. */
572         if (!disconnect && port->port_usb)
573                 gs_start_rx(port);
574
575         spin_unlock_irq(&port->port_lock);
576 }
577
578 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
579 {
580         struct gs_port  *port = ep->driver_data;
581
582         /* Queue all received data until the tty layer is ready for it. */
583         spin_lock(&port->port_lock);
584         list_add_tail(&req->list, &port->read_queue);
585         tasklet_schedule(&port->push);
586         spin_unlock(&port->port_lock);
587 }
588
589 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
590 {
591         struct gs_port  *port = ep->driver_data;
592
593         spin_lock(&port->port_lock);
594         list_add(&req->list, &port->write_pool);
595
596         switch (req->status) {
597         default:
598                 /* presumably a transient fault */
599                 pr_warning("%s: unexpected %s status %d\n",
600                                 __func__, ep->name, req->status);
601                 /* FALL THROUGH */
602         case 0:
603                 /* normal completion */
604                 gs_start_tx(port);
605                 break;
606
607         case -ESHUTDOWN:
608                 /* disconnect */
609                 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
610                 break;
611         }
612
613         spin_unlock(&port->port_lock);
614 }
615
616 static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
617 {
618         struct usb_request      *req;
619
620         while (!list_empty(head)) {
621                 req = list_entry(head->next, struct usb_request, list);
622                 list_del(&req->list);
623                 gs_free_req(ep, req);
624         }
625 }
626
627 static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
628                 void (*fn)(struct usb_ep *, struct usb_request *))
629 {
630         int                     i;
631         struct usb_request      *req;
632
633         /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
634          * do quite that many this time, don't fail ... we just won't
635          * be as speedy as we might otherwise be.
636          */
637         for (i = 0; i < QUEUE_SIZE; i++) {
638                 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
639                 if (!req)
640                         return list_empty(head) ? -ENOMEM : 0;
641                 req->complete = fn;
642                 list_add_tail(&req->list, head);
643         }
644         return 0;
645 }
646
647 /**
648  * gs_start_io - start USB I/O streams
649  * @dev: encapsulates endpoints to use
650  * Context: holding port_lock; port_tty and port_usb are non-null
651  *
652  * We only start I/O when something is connected to both sides of
653  * this port.  If nothing is listening on the host side, we may
654  * be pointlessly filling up our TX buffers and FIFO.
655  */
656 static int gs_start_io(struct gs_port *port)
657 {
658         struct list_head        *head = &port->read_pool;
659         struct usb_ep           *ep = port->port_usb->out;
660         int                     status;
661         unsigned                started;
662
663         /* Allocate RX and TX I/O buffers.  We can't easily do this much
664          * earlier (with GFP_KERNEL) because the requests are coupled to
665          * endpoints, as are the packet sizes we'll be using.  Different
666          * configurations may use different endpoints with a given port;
667          * and high speed vs full speed changes packet sizes too.
668          */
669         status = gs_alloc_requests(ep, head, gs_read_complete);
670         if (status)
671                 return status;
672
673         status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
674                         gs_write_complete);
675         if (status) {
676                 gs_free_requests(ep, head);
677                 return status;
678         }
679
680         /* queue read requests */
681         port->n_read = 0;
682         started = gs_start_rx(port);
683
684         /* unblock any pending writes into our circular buffer */
685         if (started) {
686                 tty_wakeup(port->port_tty);
687         } else {
688                 gs_free_requests(ep, head);
689                 gs_free_requests(port->port_usb->in, &port->write_pool);
690                 status = -EIO;
691         }
692
693         return status;
694 }
695
696 /*-------------------------------------------------------------------------*/
697
698 /* TTY Driver */
699
700 /*
701  * gs_open sets up the link between a gs_port and its associated TTY.
702  * That link is broken *only* by TTY close(), and all driver methods
703  * know that.
704  */
705 static int gs_open(struct tty_struct *tty, struct file *file)
706 {
707         int             port_num = tty->index;
708         struct gs_port  *port;
709         int             status;
710
711         if (port_num < 0 || port_num >= n_ports)
712                 return -ENXIO;
713
714         do {
715                 mutex_lock(&ports[port_num].lock);
716                 port = ports[port_num].port;
717                 if (!port)
718                         status = -ENODEV;
719                 else {
720                         spin_lock_irq(&port->port_lock);
721
722                         /* already open?  Great. */
723                         if (port->open_count) {
724                                 status = 0;
725                                 port->open_count++;
726
727                         /* currently opening/closing? wait ... */
728                         } else if (port->openclose) {
729                                 status = -EBUSY;
730
731                         /* ... else we do the work */
732                         } else {
733                                 status = -EAGAIN;
734                                 port->openclose = true;
735                         }
736                         spin_unlock_irq(&port->port_lock);
737                 }
738                 mutex_unlock(&ports[port_num].lock);
739
740                 switch (status) {
741                 default:
742                         /* fully handled */
743                         return status;
744                 case -EAGAIN:
745                         /* must do the work */
746                         break;
747                 case -EBUSY:
748                         /* wait for EAGAIN task to finish */
749                         msleep(1);
750                         /* REVISIT could have a waitchannel here, if
751                          * concurrent open performance is important
752                          */
753                         break;
754                 }
755         } while (status != -EAGAIN);
756
757         /* Do the "real open" */
758         spin_lock_irq(&port->port_lock);
759
760         /* allocate circular buffer on first open */
761         if (port->port_write_buf.buf_buf == NULL) {
762
763                 spin_unlock_irq(&port->port_lock);
764                 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
765                 spin_lock_irq(&port->port_lock);
766
767                 if (status) {
768                         pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
769                                 port->port_num, tty, file);
770                         port->openclose = false;
771                         goto exit_unlock_port;
772                 }
773         }
774
775         /* REVISIT if REMOVED (ports[].port NULL), abort the open
776          * to let rmmod work faster (but this way isn't wrong).
777          */
778
779         /* REVISIT maybe wait for "carrier detect" */
780
781         tty->driver_data = port;
782         port->port_tty = tty;
783
784         port->open_count = 1;
785         port->openclose = false;
786
787         /* low_latency means ldiscs work in tasklet context, without
788          * needing a workqueue schedule ... easier to keep up.
789          */
790         tty->low_latency = 1;
791
792         /* if connected, start the I/O stream */
793         if (port->port_usb) {
794                 struct gserial  *gser = port->port_usb;
795
796                 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
797                 gs_start_io(port);
798
799                 if (gser->connect)
800                         gser->connect(gser);
801         }
802
803         pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
804
805         status = 0;
806
807 exit_unlock_port:
808         spin_unlock_irq(&port->port_lock);
809         return status;
810 }
811
812 static int gs_writes_finished(struct gs_port *p)
813 {
814         int cond;
815
816         /* return true on disconnect or empty buffer */
817         spin_lock_irq(&p->port_lock);
818         cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
819         spin_unlock_irq(&p->port_lock);
820
821         return cond;
822 }
823
824 static void gs_close(struct tty_struct *tty, struct file *file)
825 {
826         struct gs_port *port = tty->driver_data;
827         struct gserial  *gser;
828
829         spin_lock_irq(&port->port_lock);
830
831         if (port->open_count != 1) {
832                 if (port->open_count == 0)
833                         WARN_ON(1);
834                 else
835                         --port->open_count;
836                 goto exit;
837         }
838
839         pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
840
841         /* mark port as closing but in use; we can drop port lock
842          * and sleep if necessary
843          */
844         port->openclose = true;
845         port->open_count = 0;
846
847         gser = port->port_usb;
848         if (gser && gser->disconnect)
849                 gser->disconnect(gser);
850
851         /* wait for circular write buffer to drain, disconnect, or at
852          * most GS_CLOSE_TIMEOUT seconds; then discard the rest
853          */
854         if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
855                 spin_unlock_irq(&port->port_lock);
856                 wait_event_interruptible_timeout(port->drain_wait,
857                                         gs_writes_finished(port),
858                                         GS_CLOSE_TIMEOUT * HZ);
859                 spin_lock_irq(&port->port_lock);
860                 gser = port->port_usb;
861         }
862
863         /* Iff we're disconnected, there can be no I/O in flight so it's
864          * ok to free the circular buffer; else just scrub it.  And don't
865          * let the push tasklet fire again until we're re-opened.
866          */
867         if (gser == NULL)
868                 gs_buf_free(&port->port_write_buf);
869         else
870                 gs_buf_clear(&port->port_write_buf);
871
872         tty->driver_data = NULL;
873         port->port_tty = NULL;
874
875         port->openclose = false;
876
877         pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
878                         port->port_num, tty, file);
879
880         wake_up_interruptible(&port->close_wait);
881 exit:
882         spin_unlock_irq(&port->port_lock);
883 }
884
885 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
886 {
887         struct gs_port  *port = tty->driver_data;
888         unsigned long   flags;
889         int             status;
890
891         pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
892                         port->port_num, tty, count);
893
894         spin_lock_irqsave(&port->port_lock, flags);
895         if (count)
896                 count = gs_buf_put(&port->port_write_buf, buf, count);
897         /* treat count == 0 as flush_chars() */
898         if (port->port_usb)
899                 status = gs_start_tx(port);
900         spin_unlock_irqrestore(&port->port_lock, flags);
901
902         return count;
903 }
904
905 static int gs_put_char(struct tty_struct *tty, unsigned char ch)
906 {
907         struct gs_port  *port = tty->driver_data;
908         unsigned long   flags;
909         int             status;
910
911         pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
912                 port->port_num, tty, ch, __builtin_return_address(0));
913
914         spin_lock_irqsave(&port->port_lock, flags);
915         status = gs_buf_put(&port->port_write_buf, &ch, 1);
916         spin_unlock_irqrestore(&port->port_lock, flags);
917
918         return status;
919 }
920
921 static void gs_flush_chars(struct tty_struct *tty)
922 {
923         struct gs_port  *port = tty->driver_data;
924         unsigned long   flags;
925
926         pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
927
928         spin_lock_irqsave(&port->port_lock, flags);
929         if (port->port_usb)
930                 gs_start_tx(port);
931         spin_unlock_irqrestore(&port->port_lock, flags);
932 }
933
934 static int gs_write_room(struct tty_struct *tty)
935 {
936         struct gs_port  *port = tty->driver_data;
937         unsigned long   flags;
938         int             room = 0;
939
940         spin_lock_irqsave(&port->port_lock, flags);
941         if (port->port_usb)
942                 room = gs_buf_space_avail(&port->port_write_buf);
943         spin_unlock_irqrestore(&port->port_lock, flags);
944
945         pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
946                 port->port_num, tty, room);
947
948         return room;
949 }
950
951 static int gs_chars_in_buffer(struct tty_struct *tty)
952 {
953         struct gs_port  *port = tty->driver_data;
954         unsigned long   flags;
955         int             chars = 0;
956
957         spin_lock_irqsave(&port->port_lock, flags);
958         chars = gs_buf_data_avail(&port->port_write_buf);
959         spin_unlock_irqrestore(&port->port_lock, flags);
960
961         pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
962                 port->port_num, tty, chars);
963
964         return chars;
965 }
966
967 /* undo side effects of setting TTY_THROTTLED */
968 static void gs_unthrottle(struct tty_struct *tty)
969 {
970         struct gs_port          *port = tty->driver_data;
971         unsigned long           flags;
972
973         spin_lock_irqsave(&port->port_lock, flags);
974         if (port->port_usb) {
975                 /* Kickstart read queue processing.  We don't do xon/xoff,
976                  * rts/cts, or other handshaking with the host, but if the
977                  * read queue backs up enough we'll be NAKing OUT packets.
978                  */
979                 tasklet_schedule(&port->push);
980                 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
981         }
982         spin_unlock_irqrestore(&port->port_lock, flags);
983 }
984
985 static int gs_break_ctl(struct tty_struct *tty, int duration)
986 {
987         struct gs_port  *port = tty->driver_data;
988         int             status = 0;
989         struct gserial  *gser;
990
991         pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
992                         port->port_num, duration);
993
994         spin_lock_irq(&port->port_lock);
995         gser = port->port_usb;
996         if (gser && gser->send_break)
997                 status = gser->send_break(gser, duration);
998         spin_unlock_irq(&port->port_lock);
999
1000         return status;
1001 }
1002
1003 static const struct tty_operations gs_tty_ops = {
1004         .open =                 gs_open,
1005         .close =                gs_close,
1006         .write =                gs_write,
1007         .put_char =             gs_put_char,
1008         .flush_chars =          gs_flush_chars,
1009         .write_room =           gs_write_room,
1010         .chars_in_buffer =      gs_chars_in_buffer,
1011         .unthrottle =           gs_unthrottle,
1012         .break_ctl =            gs_break_ctl,
1013 };
1014
1015 /*-------------------------------------------------------------------------*/
1016
1017 static struct tty_driver *gs_tty_driver;
1018
1019 static int __init
1020 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1021 {
1022         struct gs_port  *port;
1023
1024         port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1025         if (port == NULL)
1026                 return -ENOMEM;
1027
1028         spin_lock_init(&port->port_lock);
1029         init_waitqueue_head(&port->close_wait);
1030         init_waitqueue_head(&port->drain_wait);
1031
1032         tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1033
1034         INIT_LIST_HEAD(&port->read_pool);
1035         INIT_LIST_HEAD(&port->read_queue);
1036         INIT_LIST_HEAD(&port->write_pool);
1037
1038         port->port_num = port_num;
1039         port->port_line_coding = *coding;
1040
1041         ports[port_num].port = port;
1042
1043         return 0;
1044 }
1045
1046 /**
1047  * gserial_setup - initialize TTY driver for one or more ports
1048  * @g: gadget to associate with these ports
1049  * @count: how many ports to support
1050  * Context: may sleep
1051  *
1052  * The TTY stack needs to know in advance how many devices it should
1053  * plan to manage.  Use this call to set up the ports you will be
1054  * exporting through USB.  Later, connect them to functions based
1055  * on what configuration is activated by the USB host; and disconnect
1056  * them as appropriate.
1057  *
1058  * An example would be a two-configuration device in which both
1059  * configurations expose port 0, but through different functions.
1060  * One configuration could even expose port 1 while the other
1061  * one doesn't.
1062  *
1063  * Returns negative errno or zero.
1064  */
1065 int __init gserial_setup(struct usb_gadget *g, unsigned count)
1066 {
1067         unsigned                        i;
1068         struct usb_cdc_line_coding      coding;
1069         int                             status;
1070
1071         if (count == 0 || count > N_PORTS)
1072                 return -EINVAL;
1073
1074         gs_tty_driver = alloc_tty_driver(count);
1075         if (!gs_tty_driver)
1076                 return -ENOMEM;
1077
1078         gs_tty_driver->owner = THIS_MODULE;
1079         gs_tty_driver->driver_name = "g_serial";
1080         gs_tty_driver->name = PREFIX;
1081         /* uses dynamically assigned dev_t values */
1082
1083         gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1084         gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1085         gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1086         gs_tty_driver->init_termios = tty_std_termios;
1087
1088         /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1089          * MS-Windows.  Otherwise, most of these flags shouldn't affect
1090          * anything unless we were to actually hook up to a serial line.
1091          */
1092         gs_tty_driver->init_termios.c_cflag =
1093                         B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1094         gs_tty_driver->init_termios.c_ispeed = 9600;
1095         gs_tty_driver->init_termios.c_ospeed = 9600;
1096
1097         coding.dwDTERate = cpu_to_le32(9600);
1098         coding.bCharFormat = 8;
1099         coding.bParityType = USB_CDC_NO_PARITY;
1100         coding.bDataBits = USB_CDC_1_STOP_BITS;
1101
1102         tty_set_operations(gs_tty_driver, &gs_tty_ops);
1103
1104         /* make devices be openable */
1105         for (i = 0; i < count; i++) {
1106                 mutex_init(&ports[i].lock);
1107                 status = gs_port_alloc(i, &coding);
1108                 if (status) {
1109                         count = i;
1110                         goto fail;
1111                 }
1112         }
1113         n_ports = count;
1114
1115         /* export the driver ... */
1116         status = tty_register_driver(gs_tty_driver);
1117         if (status) {
1118                 pr_err("%s: cannot register, err %d\n",
1119                                 __func__, status);
1120                 goto fail;
1121         }
1122
1123         /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1124         for (i = 0; i < count; i++) {
1125                 struct device   *tty_dev;
1126
1127                 tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
1128                 if (IS_ERR(tty_dev))
1129                         pr_warning("%s: no classdev for port %d, err %ld\n",
1130                                 __func__, i, PTR_ERR(tty_dev));
1131         }
1132
1133         pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1134                         count, (count == 1) ? "" : "s");
1135
1136         return status;
1137 fail:
1138         while (count--)
1139                 kfree(ports[count].port);
1140         put_tty_driver(gs_tty_driver);
1141         gs_tty_driver = NULL;
1142         return status;
1143 }
1144
1145 static int gs_closed(struct gs_port *port)
1146 {
1147         int cond;
1148
1149         spin_lock_irq(&port->port_lock);
1150         cond = (port->open_count == 0) && !port->openclose;
1151         spin_unlock_irq(&port->port_lock);
1152         return cond;
1153 }
1154
1155 /**
1156  * gserial_cleanup - remove TTY-over-USB driver and devices
1157  * Context: may sleep
1158  *
1159  * This is called to free all resources allocated by @gserial_setup().
1160  * Accordingly, it may need to wait until some open /dev/ files have
1161  * closed.
1162  *
1163  * The caller must have issued @gserial_disconnect() for any ports
1164  * that had previously been connected, so that there is never any
1165  * I/O pending when it's called.
1166  */
1167 void gserial_cleanup(void)
1168 {
1169         unsigned        i;
1170         struct gs_port  *port;
1171
1172         if (!gs_tty_driver)
1173                 return;
1174
1175         /* start sysfs and /dev/ttyGS* node removal */
1176         for (i = 0; i < n_ports; i++)
1177                 tty_unregister_device(gs_tty_driver, i);
1178
1179         for (i = 0; i < n_ports; i++) {
1180                 /* prevent new opens */
1181                 mutex_lock(&ports[i].lock);
1182                 port = ports[i].port;
1183                 ports[i].port = NULL;
1184                 mutex_unlock(&ports[i].lock);
1185
1186                 tasklet_kill(&port->push);
1187
1188                 /* wait for old opens to finish */
1189                 wait_event(port->close_wait, gs_closed(port));
1190
1191                 WARN_ON(port->port_usb != NULL);
1192
1193                 kfree(port);
1194         }
1195         n_ports = 0;
1196
1197         tty_unregister_driver(gs_tty_driver);
1198         gs_tty_driver = NULL;
1199
1200         pr_debug("%s: cleaned up ttyGS* support\n", __func__);
1201 }
1202
1203 /**
1204  * gserial_connect - notify TTY I/O glue that USB link is active
1205  * @gser: the function, set up with endpoints and descriptors
1206  * @port_num: which port is active
1207  * Context: any (usually from irq)
1208  *
1209  * This is called activate endpoints and let the TTY layer know that
1210  * the connection is active ... not unlike "carrier detect".  It won't
1211  * necessarily start I/O queues; unless the TTY is held open by any
1212  * task, there would be no point.  However, the endpoints will be
1213  * activated so the USB host can perform I/O, subject to basic USB
1214  * hardware flow control.
1215  *
1216  * Caller needs to have set up the endpoints and USB function in @dev
1217  * before calling this, as well as the appropriate (speed-specific)
1218  * endpoint descriptors, and also have set up the TTY driver by calling
1219  * @gserial_setup().
1220  *
1221  * Returns negative errno or zero.
1222  * On success, ep->driver_data will be overwritten.
1223  */
1224 int gserial_connect(struct gserial *gser, u8 port_num)
1225 {
1226         struct gs_port  *port;
1227         unsigned long   flags;
1228         int             status;
1229
1230         if (!gs_tty_driver || port_num >= n_ports)
1231                 return -ENXIO;
1232
1233         /* we "know" gserial_cleanup() hasn't been called */
1234         port = ports[port_num].port;
1235
1236         /* activate the endpoints */
1237         status = usb_ep_enable(gser->in, gser->in_desc);
1238         if (status < 0)
1239                 return status;
1240         gser->in->driver_data = port;
1241
1242         status = usb_ep_enable(gser->out, gser->out_desc);
1243         if (status < 0)
1244                 goto fail_out;
1245         gser->out->driver_data = port;
1246
1247         /* then tell the tty glue that I/O can work */
1248         spin_lock_irqsave(&port->port_lock, flags);
1249         gser->ioport = port;
1250         port->port_usb = gser;
1251
1252         /* REVISIT unclear how best to handle this state...
1253          * we don't really couple it with the Linux TTY.
1254          */
1255         gser->port_line_coding = port->port_line_coding;
1256
1257         /* REVISIT if waiting on "carrier detect", signal. */
1258
1259         /* if it's already open, start I/O ... and notify the serial
1260          * protocol about open/close status (connect/disconnect).
1261          */
1262         if (port->open_count) {
1263                 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1264                 gs_start_io(port);
1265                 if (gser->connect)
1266                         gser->connect(gser);
1267         } else {
1268                 if (gser->disconnect)
1269                         gser->disconnect(gser);
1270         }
1271
1272         spin_unlock_irqrestore(&port->port_lock, flags);
1273
1274         return status;
1275
1276 fail_out:
1277         usb_ep_disable(gser->in);
1278         gser->in->driver_data = NULL;
1279         return status;
1280 }
1281
1282 /**
1283  * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1284  * @gser: the function, on which gserial_connect() was called
1285  * Context: any (usually from irq)
1286  *
1287  * This is called to deactivate endpoints and let the TTY layer know
1288  * that the connection went inactive ... not unlike "hangup".
1289  *
1290  * On return, the state is as if gserial_connect() had never been called;
1291  * there is no active USB I/O on these endpoints.
1292  */
1293 void gserial_disconnect(struct gserial *gser)
1294 {
1295         struct gs_port  *port = gser->ioport;
1296         unsigned long   flags;
1297
1298         if (!port)
1299                 return;
1300
1301         /* tell the TTY glue not to do I/O here any more */
1302         spin_lock_irqsave(&port->port_lock, flags);
1303
1304         /* REVISIT as above: how best to track this? */
1305         port->port_line_coding = gser->port_line_coding;
1306
1307         port->port_usb = NULL;
1308         gser->ioport = NULL;
1309         if (port->open_count > 0 || port->openclose) {
1310                 wake_up_interruptible(&port->drain_wait);
1311                 if (port->port_tty)
1312                         tty_hangup(port->port_tty);
1313         }
1314         spin_unlock_irqrestore(&port->port_lock, flags);
1315
1316         /* disable endpoints, aborting down any active I/O */
1317         usb_ep_disable(gser->out);
1318         gser->out->driver_data = NULL;
1319
1320         usb_ep_disable(gser->in);
1321         gser->in->driver_data = NULL;
1322
1323         /* finally, free any unused/unusable I/O buffers */
1324         spin_lock_irqsave(&port->port_lock, flags);
1325         if (port->open_count == 0 && !port->openclose)
1326                 gs_buf_free(&port->port_write_buf);
1327         gs_free_requests(gser->out, &port->read_pool);
1328         gs_free_requests(gser->out, &port->read_queue);
1329         gs_free_requests(gser->in, &port->write_pool);
1330         spin_unlock_irqrestore(&port->port_lock, flags);
1331 }