u_serial.c 33 KB

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