u_serial.c 33 KB

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