tty_buffer.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Tty buffer allocation management
  4. */
  5. #include <linux/types.h>
  6. #include <linux/errno.h>
  7. #include <linux/tty.h>
  8. #include <linux/tty_driver.h>
  9. #include <linux/tty_flip.h>
  10. #include <linux/timer.h>
  11. #include <linux/string.h>
  12. #include <linux/slab.h>
  13. #include <linux/sched.h>
  14. #include <linux/wait.h>
  15. #include <linux/bitops.h>
  16. #include <linux/delay.h>
  17. #include <linux/module.h>
  18. #include <linux/ratelimit.h>
  19. #define MIN_TTYB_SIZE 256
  20. #define TTYB_ALIGN_MASK 255
  21. /*
  22. * Byte threshold to limit memory consumption for flip buffers.
  23. * The actual memory limit is > 2x this amount.
  24. */
  25. #define TTYB_DEFAULT_MEM_LIMIT (640 * 1024UL)
  26. /*
  27. * We default to dicing tty buffer allocations to this many characters
  28. * in order to avoid multiple page allocations. We know the size of
  29. * tty_buffer itself but it must also be taken into account that the
  30. * the buffer is 256 byte aligned. See tty_buffer_find for the allocation
  31. * logic this must match
  32. */
  33. #define TTY_BUFFER_PAGE (((PAGE_SIZE - sizeof(struct tty_buffer)) / 2) & ~0xFF)
  34. /**
  35. * tty_buffer_lock_exclusive - gain exclusive access to buffer
  36. * tty_buffer_unlock_exclusive - release exclusive access
  37. *
  38. * @port - tty_port owning the flip buffer
  39. *
  40. * Guarantees safe use of the line discipline's receive_buf() method by
  41. * excluding the buffer work and any pending flush from using the flip
  42. * buffer. Data can continue to be added concurrently to the flip buffer
  43. * from the driver side.
  44. *
  45. * On release, the buffer work is restarted if there is data in the
  46. * flip buffer
  47. */
  48. void tty_buffer_lock_exclusive(struct tty_port *port)
  49. {
  50. struct tty_bufhead *buf = &port->buf;
  51. atomic_inc(&buf->priority);
  52. mutex_lock(&buf->lock);
  53. }
  54. EXPORT_SYMBOL_GPL(tty_buffer_lock_exclusive);
  55. void tty_buffer_unlock_exclusive(struct tty_port *port)
  56. {
  57. struct tty_bufhead *buf = &port->buf;
  58. int restart;
  59. restart = buf->head->commit != buf->head->read;
  60. atomic_dec(&buf->priority);
  61. mutex_unlock(&buf->lock);
  62. if (restart)
  63. queue_work(system_unbound_wq, &buf->work);
  64. }
  65. EXPORT_SYMBOL_GPL(tty_buffer_unlock_exclusive);
  66. /**
  67. * tty_buffer_space_avail - return unused buffer space
  68. * @port - tty_port owning the flip buffer
  69. *
  70. * Returns the # of bytes which can be written by the driver without
  71. * reaching the buffer limit.
  72. *
  73. * Note: this does not guarantee that memory is available to write
  74. * the returned # of bytes (use tty_prepare_flip_string_xxx() to
  75. * pre-allocate if memory guarantee is required).
  76. */
  77. int tty_buffer_space_avail(struct tty_port *port)
  78. {
  79. int space = port->buf.mem_limit - atomic_read(&port->buf.mem_used);
  80. return max(space, 0);
  81. }
  82. EXPORT_SYMBOL_GPL(tty_buffer_space_avail);
  83. static void tty_buffer_reset(struct tty_buffer *p, size_t size)
  84. {
  85. p->used = 0;
  86. p->size = size;
  87. p->next = NULL;
  88. p->commit = 0;
  89. p->read = 0;
  90. p->flags = 0;
  91. }
  92. /**
  93. * tty_buffer_free_all - free buffers used by a tty
  94. * @tty: tty to free from
  95. *
  96. * Remove all the buffers pending on a tty whether queued with data
  97. * or in the free ring. Must be called when the tty is no longer in use
  98. */
  99. void tty_buffer_free_all(struct tty_port *port)
  100. {
  101. struct tty_bufhead *buf = &port->buf;
  102. struct tty_buffer *p, *next;
  103. struct llist_node *llist;
  104. while ((p = buf->head) != NULL) {
  105. buf->head = p->next;
  106. if (p->size > 0)
  107. kfree(p);
  108. }
  109. llist = llist_del_all(&buf->free);
  110. llist_for_each_entry_safe(p, next, llist, free)
  111. kfree(p);
  112. tty_buffer_reset(&buf->sentinel, 0);
  113. buf->head = &buf->sentinel;
  114. buf->tail = &buf->sentinel;
  115. atomic_set(&buf->mem_used, 0);
  116. }
  117. /**
  118. * tty_buffer_alloc - allocate a tty buffer
  119. * @tty: tty device
  120. * @size: desired size (characters)
  121. *
  122. * Allocate a new tty buffer to hold the desired number of characters.
  123. * We round our buffers off in 256 character chunks to get better
  124. * allocation behaviour.
  125. * Return NULL if out of memory or the allocation would exceed the
  126. * per device queue
  127. */
  128. static struct tty_buffer *tty_buffer_alloc(struct tty_port *port, size_t size)
  129. {
  130. struct llist_node *free;
  131. struct tty_buffer *p;
  132. /* Round the buffer size out */
  133. size = __ALIGN_MASK(size, TTYB_ALIGN_MASK);
  134. if (size <= MIN_TTYB_SIZE) {
  135. free = llist_del_first(&port->buf.free);
  136. if (free) {
  137. p = llist_entry(free, struct tty_buffer, free);
  138. goto found;
  139. }
  140. }
  141. /* Should possibly check if this fails for the largest buffer we
  142. have queued and recycle that ? */
  143. if (atomic_read(&port->buf.mem_used) > port->buf.mem_limit)
  144. return NULL;
  145. p = kmalloc(sizeof(struct tty_buffer) + 2 * size, GFP_ATOMIC);
  146. if (p == NULL)
  147. return NULL;
  148. found:
  149. tty_buffer_reset(p, size);
  150. atomic_add(size, &port->buf.mem_used);
  151. return p;
  152. }
  153. /**
  154. * tty_buffer_free - free a tty buffer
  155. * @tty: tty owning the buffer
  156. * @b: the buffer to free
  157. *
  158. * Free a tty buffer, or add it to the free list according to our
  159. * internal strategy
  160. */
  161. static void tty_buffer_free(struct tty_port *port, struct tty_buffer *b)
  162. {
  163. struct tty_bufhead *buf = &port->buf;
  164. /* Dumb strategy for now - should keep some stats */
  165. WARN_ON(atomic_sub_return(b->size, &buf->mem_used) < 0);
  166. if (b->size > MIN_TTYB_SIZE)
  167. kfree(b);
  168. else if (b->size > 0)
  169. llist_add(&b->free, &buf->free);
  170. }
  171. /**
  172. * tty_buffer_flush - flush full tty buffers
  173. * @tty: tty to flush
  174. * @ld: optional ldisc ptr (must be referenced)
  175. *
  176. * flush all the buffers containing receive data. If ld != NULL,
  177. * flush the ldisc input buffer.
  178. *
  179. * Locking: takes buffer lock to ensure single-threaded flip buffer
  180. * 'consumer'
  181. */
  182. void tty_buffer_flush(struct tty_struct *tty, struct tty_ldisc *ld)
  183. {
  184. struct tty_port *port = tty->port;
  185. struct tty_bufhead *buf = &port->buf;
  186. struct tty_buffer *next;
  187. atomic_inc(&buf->priority);
  188. mutex_lock(&buf->lock);
  189. /* paired w/ release in __tty_buffer_request_room; ensures there are
  190. * no pending memory accesses to the freed buffer
  191. */
  192. while ((next = smp_load_acquire(&buf->head->next)) != NULL) {
  193. tty_buffer_free(port, buf->head);
  194. buf->head = next;
  195. }
  196. buf->head->read = buf->head->commit;
  197. if (ld && ld->ops->flush_buffer)
  198. ld->ops->flush_buffer(tty);
  199. atomic_dec(&buf->priority);
  200. mutex_unlock(&buf->lock);
  201. }
  202. /**
  203. * tty_buffer_request_room - grow tty buffer if needed
  204. * @tty: tty structure
  205. * @size: size desired
  206. * @flags: buffer flags if new buffer allocated (default = 0)
  207. *
  208. * Make at least size bytes of linear space available for the tty
  209. * buffer. If we fail return the size we managed to find.
  210. *
  211. * Will change over to a new buffer if the current buffer is encoded as
  212. * TTY_NORMAL (so has no flags buffer) and the new buffer requires
  213. * a flags buffer.
  214. */
  215. static int __tty_buffer_request_room(struct tty_port *port, size_t size,
  216. int flags)
  217. {
  218. struct tty_bufhead *buf = &port->buf;
  219. struct tty_buffer *b, *n;
  220. int left, change;
  221. b = buf->tail;
  222. if (b->flags & TTYB_NORMAL)
  223. left = 2 * b->size - b->used;
  224. else
  225. left = b->size - b->used;
  226. change = (b->flags & TTYB_NORMAL) && (~flags & TTYB_NORMAL);
  227. if (change || left < size) {
  228. /* This is the slow path - looking for new buffers to use */
  229. n = tty_buffer_alloc(port, size);
  230. if (n != NULL) {
  231. n->flags = flags;
  232. buf->tail = n;
  233. /* paired w/ acquire in flush_to_ldisc(); ensures
  234. * flush_to_ldisc() sees buffer data.
  235. */
  236. smp_store_release(&b->commit, b->used);
  237. /* paired w/ acquire in flush_to_ldisc(); ensures the
  238. * latest commit value can be read before the head is
  239. * advanced to the next buffer
  240. */
  241. smp_store_release(&b->next, n);
  242. } else if (change)
  243. size = 0;
  244. else
  245. size = left;
  246. }
  247. return size;
  248. }
  249. int tty_buffer_request_room(struct tty_port *port, size_t size)
  250. {
  251. return __tty_buffer_request_room(port, size, 0);
  252. }
  253. EXPORT_SYMBOL_GPL(tty_buffer_request_room);
  254. /**
  255. * tty_insert_flip_string_fixed_flag - Add characters to the tty buffer
  256. * @port: tty port
  257. * @chars: characters
  258. * @flag: flag value for each character
  259. * @size: size
  260. *
  261. * Queue a series of bytes to the tty buffering. All the characters
  262. * passed are marked with the supplied flag. Returns the number added.
  263. */
  264. int tty_insert_flip_string_fixed_flag(struct tty_port *port,
  265. const unsigned char *chars, char flag, size_t size)
  266. {
  267. int copied = 0;
  268. do {
  269. int goal = min_t(size_t, size - copied, TTY_BUFFER_PAGE);
  270. int flags = (flag == TTY_NORMAL) ? TTYB_NORMAL : 0;
  271. int space = __tty_buffer_request_room(port, goal, flags);
  272. struct tty_buffer *tb = port->buf.tail;
  273. if (unlikely(space == 0))
  274. break;
  275. memcpy(char_buf_ptr(tb, tb->used), chars, space);
  276. if (~tb->flags & TTYB_NORMAL)
  277. memset(flag_buf_ptr(tb, tb->used), flag, space);
  278. tb->used += space;
  279. copied += space;
  280. chars += space;
  281. /* There is a small chance that we need to split the data over
  282. several buffers. If this is the case we must loop */
  283. } while (unlikely(size > copied));
  284. return copied;
  285. }
  286. EXPORT_SYMBOL(tty_insert_flip_string_fixed_flag);
  287. /**
  288. * tty_insert_flip_string_flags - Add characters to the tty buffer
  289. * @port: tty port
  290. * @chars: characters
  291. * @flags: flag bytes
  292. * @size: size
  293. *
  294. * Queue a series of bytes to the tty buffering. For each character
  295. * the flags array indicates the status of the character. Returns the
  296. * number added.
  297. */
  298. int tty_insert_flip_string_flags(struct tty_port *port,
  299. const unsigned char *chars, const char *flags, size_t size)
  300. {
  301. int copied = 0;
  302. do {
  303. int goal = min_t(size_t, size - copied, TTY_BUFFER_PAGE);
  304. int space = tty_buffer_request_room(port, goal);
  305. struct tty_buffer *tb = port->buf.tail;
  306. if (unlikely(space == 0))
  307. break;
  308. memcpy(char_buf_ptr(tb, tb->used), chars, space);
  309. memcpy(flag_buf_ptr(tb, tb->used), flags, space);
  310. tb->used += space;
  311. copied += space;
  312. chars += space;
  313. flags += space;
  314. /* There is a small chance that we need to split the data over
  315. several buffers. If this is the case we must loop */
  316. } while (unlikely(size > copied));
  317. return copied;
  318. }
  319. EXPORT_SYMBOL(tty_insert_flip_string_flags);
  320. /**
  321. * __tty_insert_flip_char - Add one character to the tty buffer
  322. * @port: tty port
  323. * @ch: character
  324. * @flag: flag byte
  325. *
  326. * Queue a single byte to the tty buffering, with an optional flag.
  327. * This is the slow path of tty_insert_flip_char.
  328. */
  329. int __tty_insert_flip_char(struct tty_port *port, unsigned char ch, char flag)
  330. {
  331. struct tty_buffer *tb;
  332. int flags = (flag == TTY_NORMAL) ? TTYB_NORMAL : 0;
  333. if (!__tty_buffer_request_room(port, 1, flags))
  334. return 0;
  335. tb = port->buf.tail;
  336. if (~tb->flags & TTYB_NORMAL)
  337. *flag_buf_ptr(tb, tb->used) = flag;
  338. *char_buf_ptr(tb, tb->used++) = ch;
  339. return 1;
  340. }
  341. EXPORT_SYMBOL(__tty_insert_flip_char);
  342. /**
  343. * tty_schedule_flip - push characters to ldisc
  344. * @port: tty port to push from
  345. *
  346. * Takes any pending buffers and transfers their ownership to the
  347. * ldisc side of the queue. It then schedules those characters for
  348. * processing by the line discipline.
  349. */
  350. void tty_schedule_flip(struct tty_port *port)
  351. {
  352. struct tty_bufhead *buf = &port->buf;
  353. /* paired w/ acquire in flush_to_ldisc(); ensures
  354. * flush_to_ldisc() sees buffer data.
  355. */
  356. smp_store_release(&buf->tail->commit, buf->tail->used);
  357. queue_work(system_unbound_wq, &buf->work);
  358. }
  359. EXPORT_SYMBOL(tty_schedule_flip);
  360. /**
  361. * tty_prepare_flip_string - make room for characters
  362. * @port: tty port
  363. * @chars: return pointer for character write area
  364. * @size: desired size
  365. *
  366. * Prepare a block of space in the buffer for data. Returns the length
  367. * available and buffer pointer to the space which is now allocated and
  368. * accounted for as ready for normal characters. This is used for drivers
  369. * that need their own block copy routines into the buffer. There is no
  370. * guarantee the buffer is a DMA target!
  371. */
  372. int tty_prepare_flip_string(struct tty_port *port, unsigned char **chars,
  373. size_t size)
  374. {
  375. int space = __tty_buffer_request_room(port, size, TTYB_NORMAL);
  376. if (likely(space)) {
  377. struct tty_buffer *tb = port->buf.tail;
  378. *chars = char_buf_ptr(tb, tb->used);
  379. if (~tb->flags & TTYB_NORMAL)
  380. memset(flag_buf_ptr(tb, tb->used), TTY_NORMAL, space);
  381. tb->used += space;
  382. }
  383. return space;
  384. }
  385. EXPORT_SYMBOL_GPL(tty_prepare_flip_string);
  386. /**
  387. * tty_ldisc_receive_buf - forward data to line discipline
  388. * @ld: line discipline to process input
  389. * @p: char buffer
  390. * @f: TTY_* flags buffer
  391. * @count: number of bytes to process
  392. *
  393. * Callers other than flush_to_ldisc() need to exclude the kworker
  394. * from concurrent use of the line discipline, see paste_selection().
  395. *
  396. * Returns the number of bytes processed
  397. */
  398. int tty_ldisc_receive_buf(struct tty_ldisc *ld, const unsigned char *p,
  399. char *f, int count)
  400. {
  401. if (ld->ops->receive_buf2)
  402. count = ld->ops->receive_buf2(ld->tty, p, f, count);
  403. else {
  404. count = min_t(int, count, ld->tty->receive_room);
  405. if (count && ld->ops->receive_buf)
  406. ld->ops->receive_buf(ld->tty, p, f, count);
  407. }
  408. return count;
  409. }
  410. EXPORT_SYMBOL_GPL(tty_ldisc_receive_buf);
  411. static int
  412. receive_buf(struct tty_port *port, struct tty_buffer *head, int count)
  413. {
  414. unsigned char *p = char_buf_ptr(head, head->read);
  415. char *f = NULL;
  416. int n;
  417. if (~head->flags & TTYB_NORMAL)
  418. f = flag_buf_ptr(head, head->read);
  419. n = port->client_ops->receive_buf(port, p, f, count);
  420. if (n > 0)
  421. memset(p, 0, n);
  422. return n;
  423. }
  424. /**
  425. * flush_to_ldisc
  426. * @work: tty structure passed from work queue.
  427. *
  428. * This routine is called out of the software interrupt to flush data
  429. * from the buffer chain to the line discipline.
  430. *
  431. * The receive_buf method is single threaded for each tty instance.
  432. *
  433. * Locking: takes buffer lock to ensure single-threaded flip buffer
  434. * 'consumer'
  435. */
  436. static void flush_to_ldisc(struct work_struct *work)
  437. {
  438. struct tty_port *port = container_of(work, struct tty_port, buf.work);
  439. struct tty_bufhead *buf = &port->buf;
  440. mutex_lock(&buf->lock);
  441. while (1) {
  442. struct tty_buffer *head = buf->head;
  443. struct tty_buffer *next;
  444. int count;
  445. /* Ldisc or user is trying to gain exclusive access */
  446. if (atomic_read(&buf->priority))
  447. break;
  448. /* paired w/ release in __tty_buffer_request_room();
  449. * ensures commit value read is not stale if the head
  450. * is advancing to the next buffer
  451. */
  452. next = smp_load_acquire(&head->next);
  453. /* paired w/ release in __tty_buffer_request_room() or in
  454. * tty_buffer_flush(); ensures we see the committed buffer data
  455. */
  456. count = smp_load_acquire(&head->commit) - head->read;
  457. if (!count) {
  458. if (next == NULL)
  459. break;
  460. buf->head = next;
  461. tty_buffer_free(port, head);
  462. continue;
  463. }
  464. count = receive_buf(port, head, count);
  465. if (!count)
  466. break;
  467. head->read += count;
  468. }
  469. mutex_unlock(&buf->lock);
  470. }
  471. /**
  472. * tty_flip_buffer_push - terminal
  473. * @port: tty port to push
  474. *
  475. * Queue a push of the terminal flip buffers to the line discipline.
  476. * Can be called from IRQ/atomic context.
  477. *
  478. * In the event of the queue being busy for flipping the work will be
  479. * held off and retried later.
  480. */
  481. void tty_flip_buffer_push(struct tty_port *port)
  482. {
  483. tty_schedule_flip(port);
  484. }
  485. EXPORT_SYMBOL(tty_flip_buffer_push);
  486. /**
  487. * tty_buffer_init - prepare a tty buffer structure
  488. * @tty: tty to initialise
  489. *
  490. * Set up the initial state of the buffer management for a tty device.
  491. * Must be called before the other tty buffer functions are used.
  492. */
  493. void tty_buffer_init(struct tty_port *port)
  494. {
  495. struct tty_bufhead *buf = &port->buf;
  496. mutex_init(&buf->lock);
  497. tty_buffer_reset(&buf->sentinel, 0);
  498. buf->head = &buf->sentinel;
  499. buf->tail = &buf->sentinel;
  500. init_llist_head(&buf->free);
  501. atomic_set(&buf->mem_used, 0);
  502. atomic_set(&buf->priority, 0);
  503. INIT_WORK(&buf->work, flush_to_ldisc);
  504. buf->mem_limit = TTYB_DEFAULT_MEM_LIMIT;
  505. }
  506. /**
  507. * tty_buffer_set_limit - change the tty buffer memory limit
  508. * @port: tty port to change
  509. *
  510. * Change the tty buffer memory limit.
  511. * Must be called before the other tty buffer functions are used.
  512. */
  513. int tty_buffer_set_limit(struct tty_port *port, int limit)
  514. {
  515. if (limit < MIN_TTYB_SIZE)
  516. return -EINVAL;
  517. port->buf.mem_limit = limit;
  518. return 0;
  519. }
  520. EXPORT_SYMBOL_GPL(tty_buffer_set_limit);
  521. /* slave ptys can claim nested buffer lock when handling BRK and INTR */
  522. void tty_buffer_set_lock_subclass(struct tty_port *port)
  523. {
  524. lockdep_set_subclass(&port->buf.lock, TTY_LOCK_SLAVE);
  525. }
  526. bool tty_buffer_restart_work(struct tty_port *port)
  527. {
  528. return queue_work(system_unbound_wq, &port->buf.work);
  529. }
  530. bool tty_buffer_cancel_work(struct tty_port *port)
  531. {
  532. return cancel_work_sync(&port->buf.work);
  533. }
  534. void tty_buffer_flush_work(struct tty_port *port)
  535. {
  536. flush_work(&port->buf.work);
  537. }