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