1 // SPDX-License-Identifier: GPL-2.0
3 * Tty buffer allocation management
6 #include <linux/types.h>
7 #include <linux/errno.h>
8 #include <linux/minmax.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>
23 #define MIN_TTYB_SIZE 256
24 #define TTYB_ALIGN_MASK 0xff
27 * Byte threshold to limit memory consumption for flip buffers.
28 * The actual memory limit is > 2x this amount.
30 #define TTYB_DEFAULT_MEM_LIMIT (640 * 1024UL)
33 * We default to dicing tty buffer allocations to this many characters
34 * in order to avoid multiple page allocations. We know the size of
35 * tty_buffer itself but it must also be taken into account that the
36 * buffer is 256 byte aligned. See tty_buffer_find for the allocation
37 * logic this must match.
40 #define TTY_BUFFER_PAGE (((PAGE_SIZE - sizeof(struct tty_buffer)) / 2) & ~TTYB_ALIGN_MASK)
43 * tty_buffer_lock_exclusive - gain exclusive access to buffer
44 * @port: tty port owning the flip buffer
46 * Guarantees safe use of the &tty_ldisc_ops.receive_buf() method by excluding
47 * the buffer work and any pending flush from using the flip buffer. Data can
48 * continue to be added concurrently to the flip buffer from the driver side.
50 * See also tty_buffer_unlock_exclusive().
52 void tty_buffer_lock_exclusive(struct tty_port *port)
54 struct tty_bufhead *buf = &port->buf;
56 atomic_inc(&buf->priority);
57 mutex_lock(&buf->lock);
59 EXPORT_SYMBOL_GPL(tty_buffer_lock_exclusive);
62 * tty_buffer_unlock_exclusive - release exclusive access
63 * @port: tty port owning the flip buffer
65 * The buffer work is restarted if there is data in the flip buffer.
67 * See also tty_buffer_lock_exclusive().
69 void tty_buffer_unlock_exclusive(struct tty_port *port)
71 struct tty_bufhead *buf = &port->buf;
74 restart = buf->head->commit != buf->head->read;
76 atomic_dec(&buf->priority);
77 mutex_unlock(&buf->lock);
79 queue_work(system_unbound_wq, &buf->work);
81 EXPORT_SYMBOL_GPL(tty_buffer_unlock_exclusive);
84 * tty_buffer_space_avail - return unused buffer space
85 * @port: tty port owning the flip buffer
87 * Returns: the # of bytes which can be written by the driver without reaching
90 * Note: this does not guarantee that memory is available to write the returned
91 * # of bytes (use tty_prepare_flip_string() to pre-allocate if memory
92 * guarantee is required).
94 unsigned int tty_buffer_space_avail(struct tty_port *port)
96 int space = port->buf.mem_limit - atomic_read(&port->buf.mem_used);
100 EXPORT_SYMBOL_GPL(tty_buffer_space_avail);
102 static void tty_buffer_reset(struct tty_buffer *p, size_t size)
114 * tty_buffer_free_all - free buffers used by a tty
115 * @port: tty port to free from
117 * Remove all the buffers pending on a tty whether queued with data or in the
118 * free ring. Must be called when the tty is no longer in use.
120 void tty_buffer_free_all(struct tty_port *port)
122 struct tty_bufhead *buf = &port->buf;
123 struct tty_buffer *p, *next;
124 struct llist_node *llist;
125 unsigned int freed = 0;
128 while ((p = buf->head) != NULL) {
134 llist = llist_del_all(&buf->free);
135 llist_for_each_entry_safe(p, next, llist, free)
138 tty_buffer_reset(&buf->sentinel, 0);
139 buf->head = &buf->sentinel;
140 buf->tail = &buf->sentinel;
142 still_used = atomic_xchg(&buf->mem_used, 0);
143 WARN(still_used != freed, "we still have not freed %d bytes!",
148 * tty_buffer_alloc - allocate a tty buffer
150 * @size: desired size (characters)
152 * Allocate a new tty buffer to hold the desired number of characters. We
153 * round our buffers off in 256 character chunks to get better allocation
156 * Returns: %NULL if out of memory or the allocation would exceed the per
159 static struct tty_buffer *tty_buffer_alloc(struct tty_port *port, size_t size)
161 struct llist_node *free;
162 struct tty_buffer *p;
164 /* Round the buffer size out */
165 size = __ALIGN_MASK(size, TTYB_ALIGN_MASK);
167 if (size <= MIN_TTYB_SIZE) {
168 free = llist_del_first(&port->buf.free);
170 p = llist_entry(free, struct tty_buffer, free);
175 /* Should possibly check if this fails for the largest buffer we
176 * have queued and recycle that ?
178 if (atomic_read(&port->buf.mem_used) > port->buf.mem_limit)
180 p = kmalloc(sizeof(struct tty_buffer) + 2 * size,
181 GFP_ATOMIC | __GFP_NOWARN);
186 tty_buffer_reset(p, size);
187 atomic_add(size, &port->buf.mem_used);
192 * tty_buffer_free - free a tty buffer
193 * @port: tty port owning the buffer
194 * @b: the buffer to free
196 * Free a tty buffer, or add it to the free list according to our internal
199 static void tty_buffer_free(struct tty_port *port, struct tty_buffer *b)
201 struct tty_bufhead *buf = &port->buf;
203 /* Dumb strategy for now - should keep some stats */
204 WARN_ON(atomic_sub_return(b->size, &buf->mem_used) < 0);
206 if (b->size > MIN_TTYB_SIZE)
208 else if (b->size > 0)
209 llist_add(&b->free, &buf->free);
213 * tty_buffer_flush - flush full tty buffers
215 * @ld: optional ldisc ptr (must be referenced)
217 * Flush all the buffers containing receive data. If @ld != %NULL, flush the
218 * ldisc input buffer.
220 * Locking: takes buffer lock to ensure single-threaded flip buffer 'consumer'.
222 void tty_buffer_flush(struct tty_struct *tty, struct tty_ldisc *ld)
224 struct tty_port *port = tty->port;
225 struct tty_bufhead *buf = &port->buf;
226 struct tty_buffer *next;
228 atomic_inc(&buf->priority);
230 mutex_lock(&buf->lock);
231 /* paired w/ release in __tty_buffer_request_room; ensures there are
232 * no pending memory accesses to the freed buffer
234 while ((next = smp_load_acquire(&buf->head->next)) != NULL) {
235 tty_buffer_free(port, buf->head);
238 buf->head->read = buf->head->commit;
239 buf->head->lookahead = buf->head->read;
241 if (ld && ld->ops->flush_buffer)
242 ld->ops->flush_buffer(tty);
244 atomic_dec(&buf->priority);
245 mutex_unlock(&buf->lock);
249 * __tty_buffer_request_room - grow tty buffer if needed
251 * @size: size desired
252 * @flags: buffer has to store flags along character data
254 * Make at least @size bytes of linear space available for the tty buffer.
256 * Will change over to a new buffer if the current buffer is encoded as
257 * %TTY_NORMAL (so has no flags buffer) and the new buffer requires a flags
260 * Returns: the size we managed to find.
262 static int __tty_buffer_request_room(struct tty_port *port, size_t size,
265 struct tty_bufhead *buf = &port->buf;
266 struct tty_buffer *b, *n;
271 left = 2 * b->size - b->used;
273 left = b->size - b->used;
275 change = !b->flags && flags;
276 if (change || left < size) {
277 /* This is the slow path - looking for new buffers to use */
278 n = tty_buffer_alloc(port, size);
283 * Paired w/ acquire in flush_to_ldisc() and lookahead_bufs()
284 * ensures they see all buffer data.
286 smp_store_release(&b->commit, b->used);
288 * Paired w/ acquire in flush_to_ldisc() and lookahead_bufs()
289 * ensures the latest commit value can be read before the head
290 * is advanced to the next buffer.
292 smp_store_release(&b->next, n);
301 int tty_buffer_request_room(struct tty_port *port, size_t size)
303 return __tty_buffer_request_room(port, size, true);
305 EXPORT_SYMBOL_GPL(tty_buffer_request_room);
308 * tty_insert_flip_string_fixed_flag - add characters to the tty buffer
311 * @flag: flag value for each character
314 * Queue a series of bytes to the tty buffering. All the characters passed are
315 * marked with the supplied flag.
317 * Returns: the number added.
319 int tty_insert_flip_string_fixed_flag(struct tty_port *port,
320 const unsigned char *chars, char flag, size_t size)
323 bool flags = flag != TTY_NORMAL;
326 int goal = min_t(size_t, size - copied, TTY_BUFFER_PAGE);
327 int space = __tty_buffer_request_room(port, goal, flags);
328 struct tty_buffer *tb = port->buf.tail;
330 if (unlikely(space == 0))
332 memcpy(char_buf_ptr(tb, tb->used), chars, space);
334 memset(flag_buf_ptr(tb, tb->used), flag, space);
338 /* There is a small chance that we need to split the data over
339 * several buffers. If this is the case we must loop.
341 } while (unlikely(size > copied));
344 EXPORT_SYMBOL(tty_insert_flip_string_fixed_flag);
347 * tty_insert_flip_string_flags - add characters to the tty buffer
353 * Queue a series of bytes to the tty buffering. For each character the flags
354 * array indicates the status of the character.
356 * Returns: the number added.
358 int tty_insert_flip_string_flags(struct tty_port *port,
359 const unsigned char *chars, const char *flags, size_t size)
364 int goal = min_t(size_t, size - copied, TTY_BUFFER_PAGE);
365 int space = tty_buffer_request_room(port, goal);
366 struct tty_buffer *tb = port->buf.tail;
368 if (unlikely(space == 0))
370 memcpy(char_buf_ptr(tb, tb->used), chars, space);
371 memcpy(flag_buf_ptr(tb, tb->used), flags, space);
376 /* There is a small chance that we need to split the data over
377 * several buffers. If this is the case we must loop.
379 } while (unlikely(size > copied));
382 EXPORT_SYMBOL(tty_insert_flip_string_flags);
385 * __tty_insert_flip_char - add one character to the tty buffer
390 * Queue a single byte @ch to the tty buffering, with an optional flag. This is
391 * the slow path of tty_insert_flip_char().
393 int __tty_insert_flip_char(struct tty_port *port, unsigned char ch, char flag)
395 struct tty_buffer *tb;
396 bool flags = flag != TTY_NORMAL;
398 if (!__tty_buffer_request_room(port, 1, flags))
403 *flag_buf_ptr(tb, tb->used) = flag;
404 *char_buf_ptr(tb, tb->used++) = ch;
408 EXPORT_SYMBOL(__tty_insert_flip_char);
411 * tty_prepare_flip_string - make room for characters
413 * @chars: return pointer for character write area
414 * @size: desired size
416 * Prepare a block of space in the buffer for data.
418 * This is used for drivers that need their own block copy routines into the
419 * buffer. There is no guarantee the buffer is a DMA target!
421 * Returns: the length available and buffer pointer (@chars) to the space which
422 * is now allocated and accounted for as ready for normal characters.
424 int tty_prepare_flip_string(struct tty_port *port, unsigned char **chars,
427 int space = __tty_buffer_request_room(port, size, false);
430 struct tty_buffer *tb = port->buf.tail;
432 *chars = char_buf_ptr(tb, tb->used);
434 memset(flag_buf_ptr(tb, tb->used), TTY_NORMAL, space);
439 EXPORT_SYMBOL_GPL(tty_prepare_flip_string);
442 * tty_ldisc_receive_buf - forward data to line discipline
443 * @ld: line discipline to process input
445 * @f: %TTY_NORMAL, %TTY_BREAK, etc. flags buffer
446 * @count: number of bytes to process
448 * Callers other than flush_to_ldisc() need to exclude the kworker from
449 * concurrent use of the line discipline, see paste_selection().
451 * Returns: the number of bytes processed.
453 int tty_ldisc_receive_buf(struct tty_ldisc *ld, const unsigned char *p,
454 const char *f, int count)
456 if (ld->ops->receive_buf2)
457 count = ld->ops->receive_buf2(ld->tty, p, f, count);
459 count = min_t(int, count, ld->tty->receive_room);
460 if (count && ld->ops->receive_buf)
461 ld->ops->receive_buf(ld->tty, p, f, count);
465 EXPORT_SYMBOL_GPL(tty_ldisc_receive_buf);
467 static void lookahead_bufs(struct tty_port *port, struct tty_buffer *head)
469 head->lookahead = max(head->lookahead, head->read);
472 struct tty_buffer *next;
476 * Paired w/ release in __tty_buffer_request_room();
477 * ensures commit value read is not stale if the head
478 * is advancing to the next buffer.
480 next = smp_load_acquire(&head->next);
482 * Paired w/ release in __tty_buffer_request_room() or in
483 * tty_buffer_flush(); ensures we see the committed buffer data.
485 count = smp_load_acquire(&head->commit) - head->lookahead;
491 if (port->client_ops->lookahead_buf) {
492 unsigned char *p, *f = NULL;
494 p = char_buf_ptr(head, head->lookahead);
496 f = flag_buf_ptr(head, head->lookahead);
498 port->client_ops->lookahead_buf(port, p, f, count);
501 head->lookahead += count;
506 receive_buf(struct tty_port *port, struct tty_buffer *head, int count)
508 unsigned char *p = char_buf_ptr(head, head->read);
509 const char *f = NULL;
513 f = flag_buf_ptr(head, head->read);
515 n = port->client_ops->receive_buf(port, p, f, count);
522 * flush_to_ldisc - flush data from buffer to ldisc
523 * @work: tty structure passed from work queue.
525 * This routine is called out of the software interrupt to flush data from the
526 * buffer chain to the line discipline.
528 * The receive_buf() method is single threaded for each tty instance.
530 * Locking: takes buffer lock to ensure single-threaded flip buffer 'consumer'.
532 static void flush_to_ldisc(struct work_struct *work)
534 struct tty_port *port = container_of(work, struct tty_port, buf.work);
535 struct tty_bufhead *buf = &port->buf;
537 mutex_lock(&buf->lock);
540 struct tty_buffer *head = buf->head;
541 struct tty_buffer *next;
544 /* Ldisc or user is trying to gain exclusive access */
545 if (atomic_read(&buf->priority))
548 /* paired w/ release in __tty_buffer_request_room();
549 * ensures commit value read is not stale if the head
550 * is advancing to the next buffer
552 next = smp_load_acquire(&head->next);
553 /* paired w/ release in __tty_buffer_request_room() or in
554 * tty_buffer_flush(); ensures we see the committed buffer data
556 count = smp_load_acquire(&head->commit) - head->read;
561 tty_buffer_free(port, head);
565 rcvd = receive_buf(port, head, count);
568 lookahead_bufs(port, head);
576 mutex_unlock(&buf->lock);
580 static inline void tty_flip_buffer_commit(struct tty_buffer *tail)
583 * Paired w/ acquire in flush_to_ldisc(); ensures flush_to_ldisc() sees
586 smp_store_release(&tail->commit, tail->used);
590 * tty_flip_buffer_push - push terminal buffers
591 * @port: tty port to push
593 * Queue a push of the terminal flip buffers to the line discipline. Can be
594 * called from IRQ/atomic context.
596 * In the event of the queue being busy for flipping the work will be held off
599 void tty_flip_buffer_push(struct tty_port *port)
601 struct tty_bufhead *buf = &port->buf;
603 tty_flip_buffer_commit(buf->tail);
604 queue_work(system_unbound_wq, &buf->work);
606 EXPORT_SYMBOL(tty_flip_buffer_push);
609 * tty_insert_flip_string_and_push_buffer - add characters to the tty buffer and
615 * The function combines tty_insert_flip_string() and tty_flip_buffer_push()
616 * with the exception of properly holding the @port->lock.
618 * To be used only internally (by pty currently).
620 * Returns: the number added.
622 int tty_insert_flip_string_and_push_buffer(struct tty_port *port,
623 const unsigned char *chars, size_t size)
625 struct tty_bufhead *buf = &port->buf;
628 spin_lock_irqsave(&port->lock, flags);
629 size = tty_insert_flip_string(port, chars, size);
631 tty_flip_buffer_commit(buf->tail);
632 spin_unlock_irqrestore(&port->lock, flags);
634 queue_work(system_unbound_wq, &buf->work);
640 * tty_buffer_init - prepare a tty buffer structure
641 * @port: tty port to initialise
643 * Set up the initial state of the buffer management for a tty device. Must be
644 * called before the other tty buffer functions are used.
646 void tty_buffer_init(struct tty_port *port)
648 struct tty_bufhead *buf = &port->buf;
650 mutex_init(&buf->lock);
651 tty_buffer_reset(&buf->sentinel, 0);
652 buf->head = &buf->sentinel;
653 buf->tail = &buf->sentinel;
654 init_llist_head(&buf->free);
655 atomic_set(&buf->mem_used, 0);
656 atomic_set(&buf->priority, 0);
657 INIT_WORK(&buf->work, flush_to_ldisc);
658 buf->mem_limit = TTYB_DEFAULT_MEM_LIMIT;
662 * tty_buffer_set_limit - change the tty buffer memory limit
663 * @port: tty port to change
664 * @limit: memory limit to set
666 * Change the tty buffer memory limit.
668 * Must be called before the other tty buffer functions are used.
670 int tty_buffer_set_limit(struct tty_port *port, int limit)
672 if (limit < MIN_TTYB_SIZE)
674 port->buf.mem_limit = limit;
677 EXPORT_SYMBOL_GPL(tty_buffer_set_limit);
679 /* slave ptys can claim nested buffer lock when handling BRK and INTR */
680 void tty_buffer_set_lock_subclass(struct tty_port *port)
682 lockdep_set_subclass(&port->buf.lock, TTY_LOCK_SLAVE);
685 bool tty_buffer_restart_work(struct tty_port *port)
687 return queue_work(system_unbound_wq, &port->buf.work);
690 bool tty_buffer_cancel_work(struct tty_port *port)
692 return cancel_work_sync(&port->buf.work);
695 void tty_buffer_flush_work(struct tty_port *port)
697 flush_work(&port->buf.work);