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