u_serial.c 34 KB

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