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. pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
  322. port->port_num, len, *((u8 *)req->buf),
  323. *((u8 *)req->buf+1), *((u8 *)req->buf+2));
  324. /* Drop lock while we call out of driver; completions
  325. * could be issued while we do so. Disconnection may
  326. * happen too; maybe immediately before we queue this!
  327. *
  328. * NOTE that we may keep sending data for a while after
  329. * the TTY closed (dev->ioport->port_tty is NULL).
  330. */
  331. spin_unlock(&port->port_lock);
  332. status = usb_ep_queue(in, req, GFP_ATOMIC);
  333. spin_lock(&port->port_lock);
  334. if (status) {
  335. pr_debug("%s: %s %s err %d\n",
  336. __func__, "queue", in->name, status);
  337. list_add(&req->list, pool);
  338. break;
  339. }
  340. /* abort immediately after disconnect */
  341. if (!port->port_usb)
  342. break;
  343. }
  344. if (do_tty_wake && port->port_tty)
  345. tty_wakeup(port->port_tty);
  346. return status;
  347. }
  348. /*
  349. * Context: caller owns port_lock, and port_usb is set
  350. */
  351. static unsigned gs_start_rx(struct gs_port *port)
  352. /*
  353. __releases(&port->port_lock)
  354. __acquires(&port->port_lock)
  355. */
  356. {
  357. struct list_head *pool = &port->read_pool;
  358. struct usb_ep *out = port->port_usb->out;
  359. unsigned started = 0;
  360. while (!list_empty(pool)) {
  361. struct usb_request *req;
  362. int status;
  363. struct tty_struct *tty;
  364. /* no more rx if closed */
  365. tty = port->port_tty;
  366. if (!tty)
  367. break;
  368. req = list_entry(pool->next, struct usb_request, list);
  369. list_del(&req->list);
  370. req->length = out->maxpacket;
  371. /* drop lock while we call out; the controller driver
  372. * may need to call us back (e.g. for disconnect)
  373. */
  374. spin_unlock(&port->port_lock);
  375. status = usb_ep_queue(out, req, GFP_ATOMIC);
  376. spin_lock(&port->port_lock);
  377. if (status) {
  378. pr_debug("%s: %s %s err %d\n",
  379. __func__, "queue", out->name, status);
  380. list_add(&req->list, pool);
  381. break;
  382. }
  383. started++;
  384. /* abort immediately after disconnect */
  385. if (!port->port_usb)
  386. break;
  387. }
  388. return started;
  389. }
  390. /*
  391. * RX tasklet takes data out of the RX queue and hands it up to the TTY
  392. * layer until it refuses to take any more data (or is throttled back).
  393. * Then it issues reads for any further data.
  394. *
  395. * If the RX queue becomes full enough that no usb_request is queued,
  396. * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
  397. * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
  398. * can be buffered before the TTY layer's buffers (currently 64 KB).
  399. */
  400. static void gs_rx_push(unsigned long _port)
  401. {
  402. struct gs_port *port = (void *)_port;
  403. struct tty_struct *tty;
  404. struct list_head *queue = &port->read_queue;
  405. bool disconnect = false;
  406. bool do_push = false;
  407. /* hand any queued data to the tty */
  408. spin_lock_irq(&port->port_lock);
  409. tty = port->port_tty;
  410. while (!list_empty(queue)) {
  411. struct usb_request *req;
  412. req = list_first_entry(queue, struct usb_request, list);
  413. /* discard data if tty was closed */
  414. if (!tty)
  415. goto recycle;
  416. /* leave data queued if tty was rx throttled */
  417. if (test_bit(TTY_THROTTLED, &tty->flags))
  418. break;
  419. switch (req->status) {
  420. case -ESHUTDOWN:
  421. disconnect = true;
  422. pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
  423. break;
  424. default:
  425. /* presumably a transient fault */
  426. pr_warning(PREFIX "%d: unexpected RX status %d\n",
  427. port->port_num, req->status);
  428. /* FALLTHROUGH */
  429. case 0:
  430. /* normal completion */
  431. break;
  432. }
  433. /* push data to (open) tty */
  434. if (req->actual) {
  435. char *packet = req->buf;
  436. unsigned size = req->actual;
  437. unsigned n;
  438. int count;
  439. /* we may have pushed part of this packet already... */
  440. n = port->n_read;
  441. if (n) {
  442. packet += n;
  443. size -= n;
  444. }
  445. count = tty_insert_flip_string(tty, packet, size);
  446. if (count)
  447. do_push = true;
  448. if (count != size) {
  449. /* stop pushing; TTY layer can't handle more */
  450. port->n_read += count;
  451. pr_vdebug(PREFIX "%d: rx block %d/%d\n",
  452. port->port_num,
  453. count, req->actual);
  454. break;
  455. }
  456. port->n_read = 0;
  457. }
  458. recycle:
  459. list_move(&req->list, &port->read_pool);
  460. }
  461. /* Push from tty to ldisc; this is immediate with low_latency, and
  462. * may trigger callbacks to this driver ... so drop the spinlock.
  463. */
  464. if (tty && do_push) {
  465. spin_unlock_irq(&port->port_lock);
  466. tty_flip_buffer_push(tty);
  467. wake_up_interruptible(&tty->read_wait);
  468. spin_lock_irq(&port->port_lock);
  469. /* tty may have been closed */
  470. tty = port->port_tty;
  471. }
  472. /* We want our data queue to become empty ASAP, keeping data
  473. * in the tty and ldisc (not here). If we couldn't push any
  474. * this time around, there may be trouble unless there's an
  475. * implicit tty_unthrottle() call on its way...
  476. *
  477. * REVISIT we should probably add a timer to keep the tasklet
  478. * from starving ... but it's not clear that case ever happens.
  479. */
  480. if (!list_empty(queue) && tty) {
  481. if (!test_bit(TTY_THROTTLED, &tty->flags)) {
  482. if (do_push)
  483. tasklet_schedule(&port->push);
  484. else
  485. pr_warning(PREFIX "%d: RX not scheduled?\n",
  486. port->port_num);
  487. }
  488. }
  489. /* If we're still connected, refill the USB RX queue. */
  490. if (!disconnect && port->port_usb)
  491. gs_start_rx(port);
  492. spin_unlock_irq(&port->port_lock);
  493. }
  494. static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
  495. {
  496. struct gs_port *port = ep->driver_data;
  497. /* Queue all received data until the tty layer is ready for it. */
  498. spin_lock(&port->port_lock);
  499. list_add_tail(&req->list, &port->read_queue);
  500. tasklet_schedule(&port->push);
  501. spin_unlock(&port->port_lock);
  502. }
  503. static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
  504. {
  505. struct gs_port *port = ep->driver_data;
  506. spin_lock(&port->port_lock);
  507. list_add(&req->list, &port->write_pool);
  508. switch (req->status) {
  509. default:
  510. /* presumably a transient fault */
  511. pr_warning("%s: unexpected %s status %d\n",
  512. __func__, ep->name, req->status);
  513. /* FALL THROUGH */
  514. case 0:
  515. /* normal completion */
  516. gs_start_tx(port);
  517. break;
  518. case -ESHUTDOWN:
  519. /* disconnect */
  520. pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
  521. break;
  522. }
  523. spin_unlock(&port->port_lock);
  524. }
  525. static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
  526. {
  527. struct usb_request *req;
  528. while (!list_empty(head)) {
  529. req = list_entry(head->next, struct usb_request, list);
  530. list_del(&req->list);
  531. gs_free_req(ep, req);
  532. }
  533. }
  534. static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
  535. void (*fn)(struct usb_ep *, struct usb_request *))
  536. {
  537. int i;
  538. struct usb_request *req;
  539. /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
  540. * do quite that many this time, don't fail ... we just won't
  541. * be as speedy as we might otherwise be.
  542. */
  543. for (i = 0; i < QUEUE_SIZE; i++) {
  544. req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
  545. if (!req)
  546. return list_empty(head) ? -ENOMEM : 0;
  547. req->complete = fn;
  548. list_add_tail(&req->list, head);
  549. }
  550. return 0;
  551. }
  552. /**
  553. * gs_start_io - start USB I/O streams
  554. * @dev: encapsulates endpoints to use
  555. * Context: holding port_lock; port_tty and port_usb are non-null
  556. *
  557. * We only start I/O when something is connected to both sides of
  558. * this port. If nothing is listening on the host side, we may
  559. * be pointlessly filling up our TX buffers and FIFO.
  560. */
  561. static int gs_start_io(struct gs_port *port)
  562. {
  563. struct list_head *head = &port->read_pool;
  564. struct usb_ep *ep = port->port_usb->out;
  565. int status;
  566. unsigned started;
  567. /* Allocate RX and TX I/O buffers. We can't easily do this much
  568. * earlier (with GFP_KERNEL) because the requests are coupled to
  569. * endpoints, as are the packet sizes we'll be using. Different
  570. * configurations may use different endpoints with a given port;
  571. * and high speed vs full speed changes packet sizes too.
  572. */
  573. status = gs_alloc_requests(ep, head, gs_read_complete);
  574. if (status)
  575. return status;
  576. status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
  577. gs_write_complete);
  578. if (status) {
  579. gs_free_requests(ep, head);
  580. return status;
  581. }
  582. /* queue read requests */
  583. port->n_read = 0;
  584. started = gs_start_rx(port);
  585. /* unblock any pending writes into our circular buffer */
  586. if (started) {
  587. tty_wakeup(port->port_tty);
  588. } else {
  589. gs_free_requests(ep, head);
  590. gs_free_requests(port->port_usb->in, &port->write_pool);
  591. status = -EIO;
  592. }
  593. return status;
  594. }
  595. /*-------------------------------------------------------------------------*/
  596. /* TTY Driver */
  597. /*
  598. * gs_open sets up the link between a gs_port and its associated TTY.
  599. * That link is broken *only* by TTY close(), and all driver methods
  600. * know that.
  601. */
  602. static int gs_open(struct tty_struct *tty, struct file *file)
  603. {
  604. int port_num = tty->index;
  605. struct gs_port *port;
  606. int status;
  607. if (port_num < 0 || port_num >= n_ports)
  608. return -ENXIO;
  609. do {
  610. mutex_lock(&ports[port_num].lock);
  611. port = ports[port_num].port;
  612. if (!port)
  613. status = -ENODEV;
  614. else {
  615. spin_lock_irq(&port->port_lock);
  616. /* already open? Great. */
  617. if (port->open_count) {
  618. status = 0;
  619. port->open_count++;
  620. /* currently opening/closing? wait ... */
  621. } else if (port->openclose) {
  622. status = -EBUSY;
  623. /* ... else we do the work */
  624. } else {
  625. status = -EAGAIN;
  626. port->openclose = true;
  627. }
  628. spin_unlock_irq(&port->port_lock);
  629. }
  630. mutex_unlock(&ports[port_num].lock);
  631. switch (status) {
  632. default:
  633. /* fully handled */
  634. return status;
  635. case -EAGAIN:
  636. /* must do the work */
  637. break;
  638. case -EBUSY:
  639. /* wait for EAGAIN task to finish */
  640. msleep(1);
  641. /* REVISIT could have a waitchannel here, if
  642. * concurrent open performance is important
  643. */
  644. break;
  645. }
  646. } while (status != -EAGAIN);
  647. /* Do the "real open" */
  648. spin_lock_irq(&port->port_lock);
  649. /* allocate circular buffer on first open */
  650. if (port->port_write_buf.buf_buf == NULL) {
  651. spin_unlock_irq(&port->port_lock);
  652. status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
  653. spin_lock_irq(&port->port_lock);
  654. if (status) {
  655. pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
  656. port->port_num, tty, file);
  657. port->openclose = false;
  658. goto exit_unlock_port;
  659. }
  660. }
  661. /* REVISIT if REMOVED (ports[].port NULL), abort the open
  662. * to let rmmod work faster (but this way isn't wrong).
  663. */
  664. /* REVISIT maybe wait for "carrier detect" */
  665. tty->driver_data = port;
  666. port->port_tty = tty;
  667. port->open_count = 1;
  668. port->openclose = false;
  669. /* low_latency means ldiscs work in tasklet context, without
  670. * needing a workqueue schedule ... easier to keep up.
  671. */
  672. tty->low_latency = 1;
  673. /* if connected, start the I/O stream */
  674. if (port->port_usb) {
  675. struct gserial *gser = port->port_usb;
  676. pr_debug("gs_open: start ttyGS%d\n", port->port_num);
  677. gs_start_io(port);
  678. if (gser->connect)
  679. gser->connect(gser);
  680. }
  681. pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
  682. status = 0;
  683. exit_unlock_port:
  684. spin_unlock_irq(&port->port_lock);
  685. return status;
  686. }
  687. static int gs_writes_finished(struct gs_port *p)
  688. {
  689. int cond;
  690. /* return true on disconnect or empty buffer */
  691. spin_lock_irq(&p->port_lock);
  692. cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
  693. spin_unlock_irq(&p->port_lock);
  694. return cond;
  695. }
  696. static void gs_close(struct tty_struct *tty, struct file *file)
  697. {
  698. struct gs_port *port = tty->driver_data;
  699. struct gserial *gser;
  700. spin_lock_irq(&port->port_lock);
  701. if (port->open_count != 1) {
  702. if (port->open_count == 0)
  703. WARN_ON(1);
  704. else
  705. --port->open_count;
  706. goto exit;
  707. }
  708. pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
  709. /* mark port as closing but in use; we can drop port lock
  710. * and sleep if necessary
  711. */
  712. port->openclose = true;
  713. port->open_count = 0;
  714. gser = port->port_usb;
  715. if (gser && gser->disconnect)
  716. gser->disconnect(gser);
  717. /* wait for circular write buffer to drain, disconnect, or at
  718. * most GS_CLOSE_TIMEOUT seconds; then discard the rest
  719. */
  720. if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
  721. spin_unlock_irq(&port->port_lock);
  722. wait_event_interruptible_timeout(port->drain_wait,
  723. gs_writes_finished(port),
  724. GS_CLOSE_TIMEOUT * HZ);
  725. spin_lock_irq(&port->port_lock);
  726. gser = port->port_usb;
  727. }
  728. /* Iff we're disconnected, there can be no I/O in flight so it's
  729. * ok to free the circular buffer; else just scrub it. And don't
  730. * let the push tasklet fire again until we're re-opened.
  731. */
  732. if (gser == NULL)
  733. gs_buf_free(&port->port_write_buf);
  734. else
  735. gs_buf_clear(&port->port_write_buf);
  736. tty->driver_data = NULL;
  737. port->port_tty = NULL;
  738. port->openclose = false;
  739. pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
  740. port->port_num, tty, file);
  741. wake_up_interruptible(&port->close_wait);
  742. exit:
  743. spin_unlock_irq(&port->port_lock);
  744. }
  745. static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
  746. {
  747. struct gs_port *port = tty->driver_data;
  748. unsigned long flags;
  749. int status;
  750. pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
  751. port->port_num, tty, count);
  752. spin_lock_irqsave(&port->port_lock, flags);
  753. if (count)
  754. count = gs_buf_put(&port->port_write_buf, buf, count);
  755. /* treat count == 0 as flush_chars() */
  756. if (port->port_usb)
  757. status = gs_start_tx(port);
  758. spin_unlock_irqrestore(&port->port_lock, flags);
  759. return count;
  760. }
  761. static int gs_put_char(struct tty_struct *tty, unsigned char ch)
  762. {
  763. struct gs_port *port = tty->driver_data;
  764. unsigned long flags;
  765. int status;
  766. pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
  767. port->port_num, tty, ch, __builtin_return_address(0));
  768. spin_lock_irqsave(&port->port_lock, flags);
  769. status = gs_buf_put(&port->port_write_buf, &ch, 1);
  770. spin_unlock_irqrestore(&port->port_lock, flags);
  771. return status;
  772. }
  773. static void gs_flush_chars(struct tty_struct *tty)
  774. {
  775. struct gs_port *port = tty->driver_data;
  776. unsigned long flags;
  777. pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
  778. spin_lock_irqsave(&port->port_lock, flags);
  779. if (port->port_usb)
  780. gs_start_tx(port);
  781. spin_unlock_irqrestore(&port->port_lock, flags);
  782. }
  783. static int gs_write_room(struct tty_struct *tty)
  784. {
  785. struct gs_port *port = tty->driver_data;
  786. unsigned long flags;
  787. int room = 0;
  788. spin_lock_irqsave(&port->port_lock, flags);
  789. if (port->port_usb)
  790. room = gs_buf_space_avail(&port->port_write_buf);
  791. spin_unlock_irqrestore(&port->port_lock, flags);
  792. pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
  793. port->port_num, tty, room);
  794. return room;
  795. }
  796. static int gs_chars_in_buffer(struct tty_struct *tty)
  797. {
  798. struct gs_port *port = tty->driver_data;
  799. unsigned long flags;
  800. int chars = 0;
  801. spin_lock_irqsave(&port->port_lock, flags);
  802. chars = gs_buf_data_avail(&port->port_write_buf);
  803. spin_unlock_irqrestore(&port->port_lock, flags);
  804. pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
  805. port->port_num, tty, chars);
  806. return chars;
  807. }
  808. /* undo side effects of setting TTY_THROTTLED */
  809. static void gs_unthrottle(struct tty_struct *tty)
  810. {
  811. struct gs_port *port = tty->driver_data;
  812. unsigned long flags;
  813. spin_lock_irqsave(&port->port_lock, flags);
  814. if (port->port_usb) {
  815. /* Kickstart read queue processing. We don't do xon/xoff,
  816. * rts/cts, or other handshaking with the host, but if the
  817. * read queue backs up enough we'll be NAKing OUT packets.
  818. */
  819. tasklet_schedule(&port->push);
  820. pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
  821. }
  822. spin_unlock_irqrestore(&port->port_lock, flags);
  823. }
  824. static int gs_break_ctl(struct tty_struct *tty, int duration)
  825. {
  826. struct gs_port *port = tty->driver_data;
  827. int status = 0;
  828. struct gserial *gser;
  829. pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
  830. port->port_num, duration);
  831. spin_lock_irq(&port->port_lock);
  832. gser = port->port_usb;
  833. if (gser && gser->send_break)
  834. status = gser->send_break(gser, duration);
  835. spin_unlock_irq(&port->port_lock);
  836. return status;
  837. }
  838. static const struct tty_operations gs_tty_ops = {
  839. .open = gs_open,
  840. .close = gs_close,
  841. .write = gs_write,
  842. .put_char = gs_put_char,
  843. .flush_chars = gs_flush_chars,
  844. .write_room = gs_write_room,
  845. .chars_in_buffer = gs_chars_in_buffer,
  846. .unthrottle = gs_unthrottle,
  847. .break_ctl = gs_break_ctl,
  848. };
  849. /*-------------------------------------------------------------------------*/
  850. static struct tty_driver *gs_tty_driver;
  851. static int __init
  852. gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
  853. {
  854. struct gs_port *port;
  855. port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
  856. if (port == NULL)
  857. return -ENOMEM;
  858. spin_lock_init(&port->port_lock);
  859. init_waitqueue_head(&port->close_wait);
  860. init_waitqueue_head(&port->drain_wait);
  861. tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
  862. INIT_LIST_HEAD(&port->read_pool);
  863. INIT_LIST_HEAD(&port->read_queue);
  864. INIT_LIST_HEAD(&port->write_pool);
  865. port->port_num = port_num;
  866. port->port_line_coding = *coding;
  867. ports[port_num].port = port;
  868. return 0;
  869. }
  870. /**
  871. * gserial_setup - initialize TTY driver for one or more ports
  872. * @g: gadget to associate with these ports
  873. * @count: how many ports to support
  874. * Context: may sleep
  875. *
  876. * The TTY stack needs to know in advance how many devices it should
  877. * plan to manage. Use this call to set up the ports you will be
  878. * exporting through USB. Later, connect them to functions based
  879. * on what configuration is activated by the USB host; and disconnect
  880. * them as appropriate.
  881. *
  882. * An example would be a two-configuration device in which both
  883. * configurations expose port 0, but through different functions.
  884. * One configuration could even expose port 1 while the other
  885. * one doesn't.
  886. *
  887. * Returns negative errno or zero.
  888. */
  889. int __init gserial_setup(struct usb_gadget *g, unsigned count)
  890. {
  891. unsigned i;
  892. struct usb_cdc_line_coding coding;
  893. int status;
  894. if (count == 0 || count > N_PORTS)
  895. return -EINVAL;
  896. gs_tty_driver = alloc_tty_driver(count);
  897. if (!gs_tty_driver)
  898. return -ENOMEM;
  899. gs_tty_driver->owner = THIS_MODULE;
  900. gs_tty_driver->driver_name = "g_serial";
  901. gs_tty_driver->name = PREFIX;
  902. /* uses dynamically assigned dev_t values */
  903. gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
  904. gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
  905. gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
  906. gs_tty_driver->init_termios = tty_std_termios;
  907. /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
  908. * MS-Windows. Otherwise, most of these flags shouldn't affect
  909. * anything unless we were to actually hook up to a serial line.
  910. */
  911. gs_tty_driver->init_termios.c_cflag =
  912. B9600 | CS8 | CREAD | HUPCL | CLOCAL;
  913. gs_tty_driver->init_termios.c_ispeed = 9600;
  914. gs_tty_driver->init_termios.c_ospeed = 9600;
  915. coding.dwDTERate = __constant_cpu_to_le32(9600);
  916. coding.bCharFormat = 8;
  917. coding.bParityType = USB_CDC_NO_PARITY;
  918. coding.bDataBits = USB_CDC_1_STOP_BITS;
  919. tty_set_operations(gs_tty_driver, &gs_tty_ops);
  920. /* make devices be openable */
  921. for (i = 0; i < count; i++) {
  922. mutex_init(&ports[i].lock);
  923. status = gs_port_alloc(i, &coding);
  924. if (status) {
  925. count = i;
  926. goto fail;
  927. }
  928. }
  929. n_ports = count;
  930. /* export the driver ... */
  931. status = tty_register_driver(gs_tty_driver);
  932. if (status) {
  933. put_tty_driver(gs_tty_driver);
  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. }