u_serial.c 33 KB

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