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