u_serial.c 33 KB

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