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