u_serial.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  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; this is immediate with low_latency, and
  464. * may trigger callbacks to this driver ... so drop the spinlock.
  465. */
  466. if (tty && do_push) {
  467. spin_unlock_irq(&port->port_lock);
  468. tty_flip_buffer_push(tty);
  469. wake_up_interruptible(&tty->read_wait);
  470. spin_lock_irq(&port->port_lock);
  471. /* tty may have been closed */
  472. tty = port->port_tty;
  473. }
  474. /* We want our data queue to become empty ASAP, keeping data
  475. * in the tty and ldisc (not here). If we couldn't push any
  476. * this time around, there may be trouble unless there's an
  477. * implicit tty_unthrottle() call on its way...
  478. *
  479. * REVISIT we should probably add a timer to keep the tasklet
  480. * from starving ... but it's not clear that case ever happens.
  481. */
  482. if (!list_empty(queue) && tty) {
  483. if (!test_bit(TTY_THROTTLED, &tty->flags)) {
  484. if (do_push)
  485. tasklet_schedule(&port->push);
  486. else
  487. pr_warning(PREFIX "%d: RX not scheduled?\n",
  488. port->port_num);
  489. }
  490. }
  491. /* If we're still connected, refill the USB RX queue. */
  492. if (!disconnect && port->port_usb)
  493. gs_start_rx(port);
  494. spin_unlock_irq(&port->port_lock);
  495. }
  496. static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
  497. {
  498. struct gs_port *port = ep->driver_data;
  499. /* Queue all received data until the tty layer is ready for it. */
  500. spin_lock(&port->port_lock);
  501. list_add_tail(&req->list, &port->read_queue);
  502. tasklet_schedule(&port->push);
  503. spin_unlock(&port->port_lock);
  504. }
  505. static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
  506. {
  507. struct gs_port *port = ep->driver_data;
  508. spin_lock(&port->port_lock);
  509. list_add(&req->list, &port->write_pool);
  510. switch (req->status) {
  511. default:
  512. /* presumably a transient fault */
  513. pr_warning("%s: unexpected %s status %d\n",
  514. __func__, ep->name, req->status);
  515. /* FALL THROUGH */
  516. case 0:
  517. /* normal completion */
  518. gs_start_tx(port);
  519. break;
  520. case -ESHUTDOWN:
  521. /* disconnect */
  522. pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
  523. break;
  524. }
  525. spin_unlock(&port->port_lock);
  526. }
  527. static void gs_free_requests(struct usb_ep *ep, struct list_head *head)
  528. {
  529. struct usb_request *req;
  530. while (!list_empty(head)) {
  531. req = list_entry(head->next, struct usb_request, list);
  532. list_del(&req->list);
  533. gs_free_req(ep, req);
  534. }
  535. }
  536. static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
  537. void (*fn)(struct usb_ep *, struct usb_request *))
  538. {
  539. int i;
  540. struct usb_request *req;
  541. /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
  542. * do quite that many this time, don't fail ... we just won't
  543. * be as speedy as we might otherwise be.
  544. */
  545. for (i = 0; i < QUEUE_SIZE; i++) {
  546. req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
  547. if (!req)
  548. return list_empty(head) ? -ENOMEM : 0;
  549. req->complete = fn;
  550. list_add_tail(&req->list, head);
  551. }
  552. return 0;
  553. }
  554. /**
  555. * gs_start_io - start USB I/O streams
  556. * @dev: encapsulates endpoints to use
  557. * Context: holding port_lock; port_tty and port_usb are non-null
  558. *
  559. * We only start I/O when something is connected to both sides of
  560. * this port. If nothing is listening on the host side, we may
  561. * be pointlessly filling up our TX buffers and FIFO.
  562. */
  563. static int gs_start_io(struct gs_port *port)
  564. {
  565. struct list_head *head = &port->read_pool;
  566. struct usb_ep *ep = port->port_usb->out;
  567. int status;
  568. unsigned started;
  569. /* Allocate RX and TX I/O buffers. We can't easily do this much
  570. * earlier (with GFP_KERNEL) because the requests are coupled to
  571. * endpoints, as are the packet sizes we'll be using. Different
  572. * configurations may use different endpoints with a given port;
  573. * and high speed vs full speed changes packet sizes too.
  574. */
  575. status = gs_alloc_requests(ep, head, gs_read_complete);
  576. if (status)
  577. return status;
  578. status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
  579. gs_write_complete);
  580. if (status) {
  581. gs_free_requests(ep, head);
  582. return status;
  583. }
  584. /* queue read requests */
  585. port->n_read = 0;
  586. started = gs_start_rx(port);
  587. /* unblock any pending writes into our circular buffer */
  588. if (started) {
  589. tty_wakeup(port->port_tty);
  590. } else {
  591. gs_free_requests(ep, head);
  592. gs_free_requests(port->port_usb->in, &port->write_pool);
  593. status = -EIO;
  594. }
  595. return status;
  596. }
  597. /*-------------------------------------------------------------------------*/
  598. /* TTY Driver */
  599. /*
  600. * gs_open sets up the link between a gs_port and its associated TTY.
  601. * That link is broken *only* by TTY close(), and all driver methods
  602. * know that.
  603. */
  604. static int gs_open(struct tty_struct *tty, struct file *file)
  605. {
  606. int port_num = tty->index;
  607. struct gs_port *port;
  608. int status;
  609. if (port_num < 0 || port_num >= n_ports)
  610. return -ENXIO;
  611. do {
  612. mutex_lock(&ports[port_num].lock);
  613. port = ports[port_num].port;
  614. if (!port)
  615. status = -ENODEV;
  616. else {
  617. spin_lock_irq(&port->port_lock);
  618. /* already open? Great. */
  619. if (port->open_count) {
  620. status = 0;
  621. port->open_count++;
  622. /* currently opening/closing? wait ... */
  623. } else if (port->openclose) {
  624. status = -EBUSY;
  625. /* ... else we do the work */
  626. } else {
  627. status = -EAGAIN;
  628. port->openclose = true;
  629. }
  630. spin_unlock_irq(&port->port_lock);
  631. }
  632. mutex_unlock(&ports[port_num].lock);
  633. switch (status) {
  634. default:
  635. /* fully handled */
  636. return status;
  637. case -EAGAIN:
  638. /* must do the work */
  639. break;
  640. case -EBUSY:
  641. /* wait for EAGAIN task to finish */
  642. msleep(1);
  643. /* REVISIT could have a waitchannel here, if
  644. * concurrent open performance is important
  645. */
  646. break;
  647. }
  648. } while (status != -EAGAIN);
  649. /* Do the "real open" */
  650. spin_lock_irq(&port->port_lock);
  651. /* allocate circular buffer on first open */
  652. if (port->port_write_buf.buf_buf == NULL) {
  653. spin_unlock_irq(&port->port_lock);
  654. status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
  655. spin_lock_irq(&port->port_lock);
  656. if (status) {
  657. pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
  658. port->port_num, tty, file);
  659. port->openclose = false;
  660. goto exit_unlock_port;
  661. }
  662. }
  663. /* REVISIT if REMOVED (ports[].port NULL), abort the open
  664. * to let rmmod work faster (but this way isn't wrong).
  665. */
  666. /* REVISIT maybe wait for "carrier detect" */
  667. tty->driver_data = port;
  668. port->port_tty = tty;
  669. port->open_count = 1;
  670. port->openclose = false;
  671. /* low_latency means ldiscs work in tasklet context, without
  672. * needing a workqueue schedule ... easier to keep up.
  673. */
  674. tty->low_latency = 1;
  675. /* if connected, start the I/O stream */
  676. if (port->port_usb) {
  677. struct gserial *gser = port->port_usb;
  678. pr_debug("gs_open: start ttyGS%d\n", port->port_num);
  679. gs_start_io(port);
  680. if (gser->connect)
  681. gser->connect(gser);
  682. }
  683. pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
  684. status = 0;
  685. exit_unlock_port:
  686. spin_unlock_irq(&port->port_lock);
  687. return status;
  688. }
  689. static int gs_writes_finished(struct gs_port *p)
  690. {
  691. int cond;
  692. /* return true on disconnect or empty buffer */
  693. spin_lock_irq(&p->port_lock);
  694. cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
  695. spin_unlock_irq(&p->port_lock);
  696. return cond;
  697. }
  698. static void gs_close(struct tty_struct *tty, struct file *file)
  699. {
  700. struct gs_port *port = tty->driver_data;
  701. struct gserial *gser;
  702. spin_lock_irq(&port->port_lock);
  703. if (port->open_count != 1) {
  704. if (port->open_count == 0)
  705. WARN_ON(1);
  706. else
  707. --port->open_count;
  708. goto exit;
  709. }
  710. pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
  711. /* mark port as closing but in use; we can drop port lock
  712. * and sleep if necessary
  713. */
  714. port->openclose = true;
  715. port->open_count = 0;
  716. gser = port->port_usb;
  717. if (gser && gser->disconnect)
  718. gser->disconnect(gser);
  719. /* wait for circular write buffer to drain, disconnect, or at
  720. * most GS_CLOSE_TIMEOUT seconds; then discard the rest
  721. */
  722. if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
  723. spin_unlock_irq(&port->port_lock);
  724. wait_event_interruptible_timeout(port->drain_wait,
  725. gs_writes_finished(port),
  726. GS_CLOSE_TIMEOUT * HZ);
  727. spin_lock_irq(&port->port_lock);
  728. gser = port->port_usb;
  729. }
  730. /* Iff we're disconnected, there can be no I/O in flight so it's
  731. * ok to free the circular buffer; else just scrub it. And don't
  732. * let the push tasklet fire again until we're re-opened.
  733. */
  734. if (gser == NULL)
  735. gs_buf_free(&port->port_write_buf);
  736. else
  737. gs_buf_clear(&port->port_write_buf);
  738. tty->driver_data = NULL;
  739. port->port_tty = NULL;
  740. port->openclose = false;
  741. pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
  742. port->port_num, tty, file);
  743. wake_up_interruptible(&port->close_wait);
  744. exit:
  745. spin_unlock_irq(&port->port_lock);
  746. }
  747. static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
  748. {
  749. struct gs_port *port = tty->driver_data;
  750. unsigned long flags;
  751. int status;
  752. pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
  753. port->port_num, tty, count);
  754. spin_lock_irqsave(&port->port_lock, flags);
  755. if (count)
  756. count = gs_buf_put(&port->port_write_buf, buf, count);
  757. /* treat count == 0 as flush_chars() */
  758. if (port->port_usb)
  759. status = gs_start_tx(port);
  760. spin_unlock_irqrestore(&port->port_lock, flags);
  761. return count;
  762. }
  763. static int gs_put_char(struct tty_struct *tty, unsigned char ch)
  764. {
  765. struct gs_port *port = tty->driver_data;
  766. unsigned long flags;
  767. int status;
  768. pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %p\n",
  769. port->port_num, tty, ch, __builtin_return_address(0));
  770. spin_lock_irqsave(&port->port_lock, flags);
  771. status = gs_buf_put(&port->port_write_buf, &ch, 1);
  772. spin_unlock_irqrestore(&port->port_lock, flags);
  773. return status;
  774. }
  775. static void gs_flush_chars(struct tty_struct *tty)
  776. {
  777. struct gs_port *port = tty->driver_data;
  778. unsigned long flags;
  779. pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
  780. spin_lock_irqsave(&port->port_lock, flags);
  781. if (port->port_usb)
  782. gs_start_tx(port);
  783. spin_unlock_irqrestore(&port->port_lock, flags);
  784. }
  785. static int gs_write_room(struct tty_struct *tty)
  786. {
  787. struct gs_port *port = tty->driver_data;
  788. unsigned long flags;
  789. int room = 0;
  790. spin_lock_irqsave(&port->port_lock, flags);
  791. if (port->port_usb)
  792. room = gs_buf_space_avail(&port->port_write_buf);
  793. spin_unlock_irqrestore(&port->port_lock, flags);
  794. pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
  795. port->port_num, tty, room);
  796. return room;
  797. }
  798. static int gs_chars_in_buffer(struct tty_struct *tty)
  799. {
  800. struct gs_port *port = tty->driver_data;
  801. unsigned long flags;
  802. int chars = 0;
  803. spin_lock_irqsave(&port->port_lock, flags);
  804. chars = gs_buf_data_avail(&port->port_write_buf);
  805. spin_unlock_irqrestore(&port->port_lock, flags);
  806. pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
  807. port->port_num, tty, chars);
  808. return chars;
  809. }
  810. /* undo side effects of setting TTY_THROTTLED */
  811. static void gs_unthrottle(struct tty_struct *tty)
  812. {
  813. struct gs_port *port = tty->driver_data;
  814. unsigned long flags;
  815. spin_lock_irqsave(&port->port_lock, flags);
  816. if (port->port_usb) {
  817. /* Kickstart read queue processing. We don't do xon/xoff,
  818. * rts/cts, or other handshaking with the host, but if the
  819. * read queue backs up enough we'll be NAKing OUT packets.
  820. */
  821. tasklet_schedule(&port->push);
  822. pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
  823. }
  824. spin_unlock_irqrestore(&port->port_lock, flags);
  825. }
  826. static int gs_break_ctl(struct tty_struct *tty, int duration)
  827. {
  828. struct gs_port *port = tty->driver_data;
  829. int status = 0;
  830. struct gserial *gser;
  831. pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
  832. port->port_num, duration);
  833. spin_lock_irq(&port->port_lock);
  834. gser = port->port_usb;
  835. if (gser && gser->send_break)
  836. status = gser->send_break(gser, duration);
  837. spin_unlock_irq(&port->port_lock);
  838. return status;
  839. }
  840. static const struct tty_operations gs_tty_ops = {
  841. .open = gs_open,
  842. .close = gs_close,
  843. .write = gs_write,
  844. .put_char = gs_put_char,
  845. .flush_chars = gs_flush_chars,
  846. .write_room = gs_write_room,
  847. .chars_in_buffer = gs_chars_in_buffer,
  848. .unthrottle = gs_unthrottle,
  849. .break_ctl = gs_break_ctl,
  850. };
  851. /*-------------------------------------------------------------------------*/
  852. static struct tty_driver *gs_tty_driver;
  853. static int __init
  854. gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
  855. {
  856. struct gs_port *port;
  857. port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
  858. if (port == NULL)
  859. return -ENOMEM;
  860. spin_lock_init(&port->port_lock);
  861. init_waitqueue_head(&port->close_wait);
  862. init_waitqueue_head(&port->drain_wait);
  863. tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
  864. INIT_LIST_HEAD(&port->read_pool);
  865. INIT_LIST_HEAD(&port->read_queue);
  866. INIT_LIST_HEAD(&port->write_pool);
  867. port->port_num = port_num;
  868. port->port_line_coding = *coding;
  869. ports[port_num].port = port;
  870. return 0;
  871. }
  872. /**
  873. * gserial_setup - initialize TTY driver for one or more ports
  874. * @g: gadget to associate with these ports
  875. * @count: how many ports to support
  876. * Context: may sleep
  877. *
  878. * The TTY stack needs to know in advance how many devices it should
  879. * plan to manage. Use this call to set up the ports you will be
  880. * exporting through USB. Later, connect them to functions based
  881. * on what configuration is activated by the USB host; and disconnect
  882. * them as appropriate.
  883. *
  884. * An example would be a two-configuration device in which both
  885. * configurations expose port 0, but through different functions.
  886. * One configuration could even expose port 1 while the other
  887. * one doesn't.
  888. *
  889. * Returns negative errno or zero.
  890. */
  891. int __init gserial_setup(struct usb_gadget *g, unsigned count)
  892. {
  893. unsigned i;
  894. struct usb_cdc_line_coding coding;
  895. int status;
  896. if (count == 0 || count > N_PORTS)
  897. return -EINVAL;
  898. gs_tty_driver = alloc_tty_driver(count);
  899. if (!gs_tty_driver)
  900. return -ENOMEM;
  901. gs_tty_driver->owner = THIS_MODULE;
  902. gs_tty_driver->driver_name = "g_serial";
  903. gs_tty_driver->name = PREFIX;
  904. /* uses dynamically assigned dev_t values */
  905. gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
  906. gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
  907. gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
  908. gs_tty_driver->init_termios = tty_std_termios;
  909. /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
  910. * MS-Windows. Otherwise, most of these flags shouldn't affect
  911. * anything unless we were to actually hook up to a serial line.
  912. */
  913. gs_tty_driver->init_termios.c_cflag =
  914. B9600 | CS8 | CREAD | HUPCL | CLOCAL;
  915. gs_tty_driver->init_termios.c_ispeed = 9600;
  916. gs_tty_driver->init_termios.c_ospeed = 9600;
  917. coding.dwDTERate = cpu_to_le32(9600);
  918. coding.bCharFormat = 8;
  919. coding.bParityType = USB_CDC_NO_PARITY;
  920. coding.bDataBits = USB_CDC_1_STOP_BITS;
  921. tty_set_operations(gs_tty_driver, &gs_tty_ops);
  922. /* make devices be openable */
  923. for (i = 0; i < count; i++) {
  924. mutex_init(&ports[i].lock);
  925. status = gs_port_alloc(i, &coding);
  926. if (status) {
  927. count = i;
  928. goto fail;
  929. }
  930. }
  931. n_ports = count;
  932. /* export the driver ... */
  933. status = tty_register_driver(gs_tty_driver);
  934. if (status) {
  935. pr_err("%s: cannot register, err %d\n",
  936. __func__, status);
  937. goto fail;
  938. }
  939. /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
  940. for (i = 0; i < count; i++) {
  941. struct device *tty_dev;
  942. tty_dev = tty_register_device(gs_tty_driver, i, &g->dev);
  943. if (IS_ERR(tty_dev))
  944. pr_warning("%s: no classdev for port %d, err %ld\n",
  945. __func__, i, PTR_ERR(tty_dev));
  946. }
  947. pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
  948. count, (count == 1) ? "" : "s");
  949. return status;
  950. fail:
  951. while (count--)
  952. kfree(ports[count].port);
  953. put_tty_driver(gs_tty_driver);
  954. gs_tty_driver = NULL;
  955. return status;
  956. }
  957. static int gs_closed(struct gs_port *port)
  958. {
  959. int cond;
  960. spin_lock_irq(&port->port_lock);
  961. cond = (port->open_count == 0) && !port->openclose;
  962. spin_unlock_irq(&port->port_lock);
  963. return cond;
  964. }
  965. /**
  966. * gserial_cleanup - remove TTY-over-USB driver and devices
  967. * Context: may sleep
  968. *
  969. * This is called to free all resources allocated by @gserial_setup().
  970. * Accordingly, it may need to wait until some open /dev/ files have
  971. * closed.
  972. *
  973. * The caller must have issued @gserial_disconnect() for any ports
  974. * that had previously been connected, so that there is never any
  975. * I/O pending when it's called.
  976. */
  977. void gserial_cleanup(void)
  978. {
  979. unsigned i;
  980. struct gs_port *port;
  981. if (!gs_tty_driver)
  982. return;
  983. /* start sysfs and /dev/ttyGS* node removal */
  984. for (i = 0; i < n_ports; i++)
  985. tty_unregister_device(gs_tty_driver, i);
  986. for (i = 0; i < n_ports; i++) {
  987. /* prevent new opens */
  988. mutex_lock(&ports[i].lock);
  989. port = ports[i].port;
  990. ports[i].port = NULL;
  991. mutex_unlock(&ports[i].lock);
  992. tasklet_kill(&port->push);
  993. /* wait for old opens to finish */
  994. wait_event(port->close_wait, gs_closed(port));
  995. WARN_ON(port->port_usb != NULL);
  996. kfree(port);
  997. }
  998. n_ports = 0;
  999. tty_unregister_driver(gs_tty_driver);
  1000. gs_tty_driver = NULL;
  1001. pr_debug("%s: cleaned up ttyGS* support\n", __func__);
  1002. }
  1003. /**
  1004. * gserial_connect - notify TTY I/O glue that USB link is active
  1005. * @gser: the function, set up with endpoints and descriptors
  1006. * @port_num: which port is active
  1007. * Context: any (usually from irq)
  1008. *
  1009. * This is called activate endpoints and let the TTY layer know that
  1010. * the connection is active ... not unlike "carrier detect". It won't
  1011. * necessarily start I/O queues; unless the TTY is held open by any
  1012. * task, there would be no point. However, the endpoints will be
  1013. * activated so the USB host can perform I/O, subject to basic USB
  1014. * hardware flow control.
  1015. *
  1016. * Caller needs to have set up the endpoints and USB function in @dev
  1017. * before calling this, as well as the appropriate (speed-specific)
  1018. * endpoint descriptors, and also have set up the TTY driver by calling
  1019. * @gserial_setup().
  1020. *
  1021. * Returns negative errno or zero.
  1022. * On success, ep->driver_data will be overwritten.
  1023. */
  1024. int gserial_connect(struct gserial *gser, u8 port_num)
  1025. {
  1026. struct gs_port *port;
  1027. unsigned long flags;
  1028. int status;
  1029. if (!gs_tty_driver || port_num >= n_ports)
  1030. return -ENXIO;
  1031. /* we "know" gserial_cleanup() hasn't been called */
  1032. port = ports[port_num].port;
  1033. /* activate the endpoints */
  1034. status = usb_ep_enable(gser->in, gser->in_desc);
  1035. if (status < 0)
  1036. return status;
  1037. gser->in->driver_data = port;
  1038. status = usb_ep_enable(gser->out, gser->out_desc);
  1039. if (status < 0)
  1040. goto fail_out;
  1041. gser->out->driver_data = port;
  1042. /* then tell the tty glue that I/O can work */
  1043. spin_lock_irqsave(&port->port_lock, flags);
  1044. gser->ioport = port;
  1045. port->port_usb = gser;
  1046. /* REVISIT unclear how best to handle this state...
  1047. * we don't really couple it with the Linux TTY.
  1048. */
  1049. gser->port_line_coding = port->port_line_coding;
  1050. /* REVISIT if waiting on "carrier detect", signal. */
  1051. /* if it's already open, start I/O ... and notify the serial
  1052. * protocol about open/close status (connect/disconnect).
  1053. */
  1054. if (port->open_count) {
  1055. pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
  1056. gs_start_io(port);
  1057. if (gser->connect)
  1058. gser->connect(gser);
  1059. } else {
  1060. if (gser->disconnect)
  1061. gser->disconnect(gser);
  1062. }
  1063. spin_unlock_irqrestore(&port->port_lock, flags);
  1064. return status;
  1065. fail_out:
  1066. usb_ep_disable(gser->in);
  1067. gser->in->driver_data = NULL;
  1068. return status;
  1069. }
  1070. /**
  1071. * gserial_disconnect - notify TTY I/O glue that USB link is inactive
  1072. * @gser: the function, on which gserial_connect() was called
  1073. * Context: any (usually from irq)
  1074. *
  1075. * This is called to deactivate endpoints and let the TTY layer know
  1076. * that the connection went inactive ... not unlike "hangup".
  1077. *
  1078. * On return, the state is as if gserial_connect() had never been called;
  1079. * there is no active USB I/O on these endpoints.
  1080. */
  1081. void gserial_disconnect(struct gserial *gser)
  1082. {
  1083. struct gs_port *port = gser->ioport;
  1084. unsigned long flags;
  1085. if (!port)
  1086. return;
  1087. /* tell the TTY glue not to do I/O here any more */
  1088. spin_lock_irqsave(&port->port_lock, flags);
  1089. /* REVISIT as above: how best to track this? */
  1090. port->port_line_coding = gser->port_line_coding;
  1091. port->port_usb = NULL;
  1092. gser->ioport = NULL;
  1093. if (port->open_count > 0 || port->openclose) {
  1094. wake_up_interruptible(&port->drain_wait);
  1095. if (port->port_tty)
  1096. tty_hangup(port->port_tty);
  1097. }
  1098. spin_unlock_irqrestore(&port->port_lock, flags);
  1099. /* disable endpoints, aborting down any active I/O */
  1100. usb_ep_disable(gser->out);
  1101. gser->out->driver_data = NULL;
  1102. usb_ep_disable(gser->in);
  1103. gser->in->driver_data = NULL;
  1104. /* finally, free any unused/unusable I/O buffers */
  1105. spin_lock_irqsave(&port->port_lock, flags);
  1106. if (port->open_count == 0 && !port->openclose)
  1107. gs_buf_free(&port->port_write_buf);
  1108. gs_free_requests(gser->out, &port->read_pool);
  1109. gs_free_requests(gser->out, &port->read_queue);
  1110. gs_free_requests(gser->in, &port->write_pool);
  1111. spin_unlock_irqrestore(&port->port_lock, flags);
  1112. }