u_serial.c 31 KB

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