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