tty_buffer.c 16 KB

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