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