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