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