u_serial.c 33 KB

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