u_serial.c 33 KB

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