u_serial.c 34 KB

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