u_serial.c 34 KB

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