u_serial.c 34 KB

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