1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * linux/fs/pipe.c 4 * 5 * Copyright (C) 1991, 1992, 1999 Linus Torvalds 6 */ 7 8 #include <linux/mm.h> 9 #include <linux/file.h> 10 #include <linux/poll.h> 11 #include <linux/slab.h> 12 #include <linux/module.h> 13 #include <linux/init.h> 14 #include <linux/fs.h> 15 #include <linux/log2.h> 16 #include <linux/mount.h> 17 #include <linux/pseudo_fs.h> 18 #include <linux/magic.h> 19 #include <linux/pipe_fs_i.h> 20 #include <linux/uio.h> 21 #include <linux/highmem.h> 22 #include <linux/pagemap.h> 23 #include <linux/audit.h> 24 #include <linux/syscalls.h> 25 #include <linux/fcntl.h> 26 #include <linux/memcontrol.h> 27 #include <linux/watch_queue.h> 28 #include <linux/sysctl.h> 29 #include <linux/sort.h> 30 31 #include <linux/uaccess.h> 32 #include <asm/ioctls.h> 33 34 #include "internal.h" 35 36 /* 37 * New pipe buffers will be restricted to this size while the user is exceeding 38 * their pipe buffer quota. The general pipe use case needs at least two 39 * buffers: one for data yet to be read, and one for new data. If this is less 40 * than two, then a write to a non-empty pipe may block even if the pipe is not 41 * full. This can occur with GNU make jobserver or similar uses of pipes as 42 * semaphores: multiple processes may be waiting to write tokens back to the 43 * pipe before reading tokens: https://lore.kernel.org/lkml/1628086770.5rn8p04n6j.none@localhost/. 44 * 45 * Users can reduce their pipe buffers with F_SETPIPE_SZ below this at their 46 * own risk, namely: pipe writes to non-full pipes may block until the pipe is 47 * emptied. 48 */ 49 #define PIPE_MIN_DEF_BUFFERS 2 50 51 /* 52 * The max size that a non-root user is allowed to grow the pipe. Can 53 * be set by root in /proc/sys/fs/pipe-max-size 54 */ 55 static unsigned int pipe_max_size = 1048576; 56 57 /* Maximum allocatable pages per user. Hard limit is unset by default, soft 58 * matches default values. 59 */ 60 static unsigned long pipe_user_pages_hard; 61 static unsigned long pipe_user_pages_soft = PIPE_DEF_BUFFERS * INR_OPEN_CUR; 62 63 /* 64 * We use head and tail indices that aren't masked off, except at the point of 65 * dereference, but rather they're allowed to wrap naturally. This means there 66 * isn't a dead spot in the buffer, but the ring has to be a power of two and 67 * <= 2^31. 68 * -- David Howells 2019-09-23. 69 * 70 * Reads with count = 0 should always return 0. 71 * -- Julian Bradfield 1999-06-07. 72 * 73 * FIFOs and Pipes now generate SIGIO for both readers and writers. 74 * -- Jeremy Elson <jelson@circlemud.org> 2001-08-16 75 * 76 * pipe_read & write cleanup 77 * -- Manfred Spraul <manfred@colorfullife.com> 2002-05-09 78 */ 79 80 #ifdef CONFIG_PROVE_LOCKING 81 static int pipe_lock_cmp_fn(const struct lockdep_map *a, 82 const struct lockdep_map *b) 83 { 84 return cmp_int((unsigned long) a, (unsigned long) b); 85 } 86 #endif 87 88 void pipe_lock(struct pipe_inode_info *pipe) 89 { 90 if (pipe->files) 91 mutex_lock(&pipe->mutex); 92 } 93 EXPORT_SYMBOL(pipe_lock); 94 95 void pipe_unlock(struct pipe_inode_info *pipe) 96 { 97 if (pipe->files) 98 mutex_unlock(&pipe->mutex); 99 } 100 EXPORT_SYMBOL(pipe_unlock); 101 102 void pipe_double_lock(struct pipe_inode_info *pipe1, 103 struct pipe_inode_info *pipe2) 104 { 105 BUG_ON(pipe1 == pipe2); 106 107 if (pipe1 > pipe2) 108 swap(pipe1, pipe2); 109 110 pipe_lock(pipe1); 111 pipe_lock(pipe2); 112 } 113 114 static struct page *anon_pipe_prealloc_pop(struct anon_pipe_prealloc *prealloc) 115 { 116 if (!prealloc->count) 117 return NULL; 118 119 prealloc->count--; 120 121 return prealloc->pages[prealloc->count]; 122 } 123 124 /* Push a page to the prealloc pool. Returns true if added, false if full. */ 125 static bool anon_pipe_prealloc_push(struct anon_pipe_prealloc *prealloc, 126 struct page *page) 127 { 128 if (prealloc->count >= PIPE_PREALLOC_MAX) 129 return false; 130 prealloc->pages[prealloc->count++] = page; 131 return true; 132 } 133 134 /* 135 * Top up the pipe's own pool, then take pipe->mutex and return with it held. 136 * The shortfall is allocated outside the lock; the push and the caller's write 137 * then run under a single lock acquisition, avoiding a separate prefill 138 * lock/unlock cycle. anon_pipe_get_page() drains the pool instead of allocating 139 * under the lock. 140 */ 141 static void anon_pipe_prefill_and_lock(struct pipe_inode_info *pipe, size_t total_len) 142 { 143 struct page *pages[PIPE_PREALLOC_MAX]; 144 unsigned int want, have, need, n = 0; 145 146 want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE), 147 PIPE_PREALLOC_MAX); 148 /* Unlocked read; the pool is refilled under the lock below. */ 149 have = min_t(unsigned int, READ_ONCE(pipe->prealloc.count), want); 150 need = want - have; 151 152 if (!need) { 153 mutex_lock(&pipe->mutex); 154 return; 155 } 156 157 while (n < need) { 158 struct page *page = alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT); 159 160 if (!page) 161 break; 162 pages[n++] = page; 163 } 164 165 mutex_lock(&pipe->mutex); 166 while (n && anon_pipe_prealloc_push(&pipe->prealloc, pages[n - 1])) 167 n--; 168 169 /* 170 * Just flush any extra page that got affected by the TOCTOU 171 * effect 172 */ 173 while (n) 174 put_page(pages[--n]); 175 } 176 177 /* 178 * Called with pipe->mutex held. Trim the pool down to PIPE_PREALLOC_KEEP under 179 * the lock, drop it, then free the excess outside the critical section. 180 */ 181 static void anon_pipe_trim_and_unlock(struct pipe_inode_info *pipe) 182 { 183 struct page *excess[PIPE_PREALLOC_MAX]; 184 unsigned int nexcess = 0; 185 186 while (pipe->prealloc.count > PIPE_PREALLOC_KEEP) 187 excess[nexcess++] = anon_pipe_prealloc_pop(&pipe->prealloc); 188 mutex_unlock(&pipe->mutex); 189 190 while (nexcess) 191 put_page(excess[--nexcess]); 192 } 193 194 static struct page *anon_pipe_get_page(struct pipe_inode_info *pipe) 195 { 196 struct page *page; 197 198 /* Drain the prealloc pool before allocating. Called with mutex held. */ 199 page = anon_pipe_prealloc_pop(&pipe->prealloc); 200 if (page) 201 return page; 202 203 /* FWIW: This is called with pipe->mutex held */ 204 return alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT); 205 } 206 207 static void anon_pipe_put_page(struct pipe_inode_info *pipe, 208 struct page *page) 209 { 210 if (page_count(page) == 1 && 211 anon_pipe_prealloc_push(&pipe->prealloc, page)) 212 return; 213 214 put_page(page); 215 } 216 217 static void anon_pipe_buf_release(struct pipe_inode_info *pipe, 218 struct pipe_buffer *buf) 219 { 220 struct page *page = buf->page; 221 222 anon_pipe_put_page(pipe, page); 223 } 224 225 static bool anon_pipe_buf_try_steal(struct pipe_inode_info *pipe, 226 struct pipe_buffer *buf) 227 { 228 struct page *page = buf->page; 229 230 if (page_count(page) != 1) 231 return false; 232 memcg_kmem_uncharge_page(page, 0); 233 __SetPageLocked(page); 234 return true; 235 } 236 237 /** 238 * generic_pipe_buf_try_steal - attempt to take ownership of a &pipe_buffer 239 * @pipe: the pipe that the buffer belongs to 240 * @buf: the buffer to attempt to steal 241 * 242 * Description: 243 * This function attempts to steal the &struct page attached to 244 * @buf. If successful, this function returns 0 and returns with 245 * the page locked. The caller may then reuse the page for whatever 246 * he wishes; the typical use is insertion into a different file 247 * page cache. 248 */ 249 bool generic_pipe_buf_try_steal(struct pipe_inode_info *pipe, 250 struct pipe_buffer *buf) 251 { 252 struct page *page = buf->page; 253 254 /* 255 * A reference of one is golden, that means that the owner of this 256 * page is the only one holding a reference to it. lock the page 257 * and return OK. 258 */ 259 if (page_count(page) == 1) { 260 lock_page(page); 261 return true; 262 } 263 return false; 264 } 265 EXPORT_SYMBOL(generic_pipe_buf_try_steal); 266 267 /** 268 * generic_pipe_buf_get - get a reference to a &struct pipe_buffer 269 * @pipe: the pipe that the buffer belongs to 270 * @buf: the buffer to get a reference to 271 * 272 * Description: 273 * This function grabs an extra reference to @buf. It's used in 274 * the tee() system call, when we duplicate the buffers in one 275 * pipe into another. 276 */ 277 bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) 278 { 279 return try_get_page(buf->page); 280 } 281 EXPORT_SYMBOL(generic_pipe_buf_get); 282 283 /** 284 * generic_pipe_buf_release - put a reference to a &struct pipe_buffer 285 * @pipe: the pipe that the buffer belongs to 286 * @buf: the buffer to put a reference to 287 * 288 * Description: 289 * This function releases a reference to @buf. 290 */ 291 void generic_pipe_buf_release(struct pipe_inode_info *pipe, 292 struct pipe_buffer *buf) 293 { 294 put_page(buf->page); 295 } 296 EXPORT_SYMBOL(generic_pipe_buf_release); 297 298 static const struct pipe_buf_operations anon_pipe_buf_ops = { 299 .release = anon_pipe_buf_release, 300 .try_steal = anon_pipe_buf_try_steal, 301 .get = generic_pipe_buf_get, 302 }; 303 304 /* Done while waiting without holding the pipe lock - thus the READ_ONCE() */ 305 static inline bool pipe_readable(const struct pipe_inode_info *pipe) 306 { 307 union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) }; 308 unsigned int writers = READ_ONCE(pipe->writers); 309 310 return !pipe_empty(idx.head, idx.tail) || !writers; 311 } 312 313 static inline unsigned int pipe_update_tail(struct pipe_inode_info *pipe, 314 struct pipe_buffer *buf, 315 unsigned int tail) 316 { 317 pipe_buf_release(pipe, buf); 318 319 /* 320 * If the pipe has a watch_queue, we need additional protection 321 * by the spinlock because notifications get posted with only 322 * this spinlock, no mutex 323 */ 324 if (pipe_has_watch_queue(pipe)) { 325 spin_lock_irq(&pipe->rd_wait.lock); 326 #ifdef CONFIG_WATCH_QUEUE 327 if (buf->flags & PIPE_BUF_FLAG_LOSS) 328 pipe->note_loss = true; 329 #endif 330 pipe->tail = ++tail; 331 spin_unlock_irq(&pipe->rd_wait.lock); 332 return tail; 333 } 334 335 /* 336 * Without a watch_queue, we can simply increment the tail 337 * without the spinlock - the mutex is enough. 338 */ 339 pipe->tail = ++tail; 340 return tail; 341 } 342 343 static ssize_t 344 anon_pipe_read(struct kiocb *iocb, struct iov_iter *to) 345 { 346 size_t total_len = iov_iter_count(to); 347 struct file *filp = iocb->ki_filp; 348 struct pipe_inode_info *pipe = filp->private_data; 349 bool wake_writer = false, wake_next_reader = false; 350 ssize_t ret; 351 352 /* Null read succeeds. */ 353 if (unlikely(total_len == 0)) 354 return 0; 355 356 ret = 0; 357 mutex_lock(&pipe->mutex); 358 359 /* 360 * We only wake up writers if the pipe was full when we started reading 361 * and it is no longer full after reading to avoid unnecessary wakeups. 362 * 363 * But when we do wake up writers, we do so using a sync wakeup 364 * (WF_SYNC), because we want them to get going and generate more 365 * data for us. 366 */ 367 for (;;) { 368 /* Read ->head with a barrier vs post_one_notification() */ 369 unsigned int head = smp_load_acquire(&pipe->head); 370 unsigned int tail = pipe->tail; 371 372 #ifdef CONFIG_WATCH_QUEUE 373 if (pipe->note_loss) { 374 struct watch_notification n; 375 376 if (total_len < 8) { 377 if (ret == 0) 378 ret = -ENOBUFS; 379 break; 380 } 381 382 n.type = WATCH_TYPE_META; 383 n.subtype = WATCH_META_LOSS_NOTIFICATION; 384 n.info = watch_sizeof(n); 385 if (copy_to_iter(&n, sizeof(n), to) != sizeof(n)) { 386 if (ret == 0) 387 ret = -EFAULT; 388 break; 389 } 390 ret += sizeof(n); 391 total_len -= sizeof(n); 392 pipe->note_loss = false; 393 } 394 #endif 395 396 if (!pipe_empty(head, tail)) { 397 struct pipe_buffer *buf = pipe_buf(pipe, tail); 398 size_t chars = buf->len; 399 size_t written; 400 int error; 401 402 if (chars > total_len) { 403 if (buf->flags & PIPE_BUF_FLAG_WHOLE) { 404 if (ret == 0) 405 ret = -ENOBUFS; 406 break; 407 } 408 chars = total_len; 409 } 410 411 error = pipe_buf_confirm(pipe, buf); 412 if (error) { 413 if (!ret) 414 ret = error; 415 break; 416 } 417 418 written = copy_page_to_iter(buf->page, buf->offset, chars, to); 419 if (unlikely(written < chars)) { 420 if (!ret) 421 ret = -EFAULT; 422 break; 423 } 424 ret += chars; 425 buf->offset += chars; 426 buf->len -= chars; 427 428 /* Was it a packet buffer? Clean up and exit */ 429 if (buf->flags & PIPE_BUF_FLAG_PACKET) { 430 total_len = chars; 431 buf->len = 0; 432 } 433 434 if (!buf->len) { 435 wake_writer |= pipe_full(head, tail, pipe->max_usage); 436 tail = pipe_update_tail(pipe, buf, tail); 437 } 438 total_len -= chars; 439 if (!total_len) 440 break; /* common path: read succeeded */ 441 if (!pipe_empty(head, tail)) /* More to do? */ 442 continue; 443 } 444 445 if (!pipe->writers) 446 break; 447 if (ret) 448 break; 449 if ((filp->f_flags & O_NONBLOCK) || 450 (iocb->ki_flags & IOCB_NOWAIT)) { 451 ret = -EAGAIN; 452 break; 453 } 454 mutex_unlock(&pipe->mutex); 455 /* 456 * We only get here if we didn't actually read anything. 457 * 458 * But because we didn't read anything, at this point we can 459 * just return directly with -ERESTARTSYS if we're interrupted, 460 * since we've done any required wakeups and there's no need 461 * to mark anything accessed. And we've dropped the lock. 462 */ 463 if (wait_event_interruptible_exclusive(pipe->rd_wait, pipe_readable(pipe)) < 0) 464 return -ERESTARTSYS; 465 466 wake_next_reader = true; 467 mutex_lock(&pipe->mutex); 468 } 469 if (pipe_is_empty(pipe)) 470 wake_next_reader = false; 471 /* Consumed buffers may have refilled the pool; trim it and unlock. */ 472 anon_pipe_trim_and_unlock(pipe); 473 474 if (wake_writer) 475 wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM); 476 if (wake_next_reader) 477 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM); 478 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT); 479 return ret; 480 } 481 482 static ssize_t 483 fifo_pipe_read(struct kiocb *iocb, struct iov_iter *to) 484 { 485 int ret = anon_pipe_read(iocb, to); 486 if (ret > 0) 487 file_accessed(iocb->ki_filp); 488 return ret; 489 } 490 491 static inline int is_packetized(struct file *file) 492 { 493 return (file->f_flags & O_DIRECT) != 0; 494 } 495 496 /* Done while waiting without holding the pipe lock - thus the READ_ONCE() */ 497 static inline bool pipe_writable(const struct pipe_inode_info *pipe) 498 { 499 union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) }; 500 unsigned int max_usage = READ_ONCE(pipe->max_usage); 501 502 return !pipe_full(idx.head, idx.tail, max_usage) || 503 !READ_ONCE(pipe->readers); 504 } 505 506 static ssize_t 507 anon_pipe_write(struct kiocb *iocb, struct iov_iter *from) 508 { 509 struct file *filp = iocb->ki_filp; 510 struct pipe_inode_info *pipe = filp->private_data; 511 unsigned int head; 512 ssize_t ret = 0; 513 size_t total_len = iov_iter_count(from); 514 ssize_t chars; 515 bool was_empty = false; 516 bool wake_next_writer = false; 517 518 /* 519 * Reject writing to watch queue pipes before the point where we lock 520 * the pipe. 521 * Otherwise, lockdep would be unhappy if the caller already has another 522 * pipe locked. 523 * If we had to support locking a normal pipe and a notification pipe at 524 * the same time, we could set up lockdep annotations for that, but 525 * since we don't actually need that, it's simpler to just bail here. 526 */ 527 if (pipe_has_watch_queue(pipe)) 528 return -EXDEV; 529 530 /* Null write succeeds. */ 531 if (unlikely(total_len == 0)) 532 return 0; 533 534 anon_pipe_prefill_and_lock(pipe, total_len); 535 536 if (!pipe->readers) { 537 if ((iocb->ki_flags & IOCB_NOSIGNAL) == 0) 538 send_sig(SIGPIPE, current, 0); 539 ret = -EPIPE; 540 goto out; 541 } 542 543 /* 544 * If it wasn't empty we try to merge new data into 545 * the last buffer. 546 * 547 * That naturally merges small writes, but it also 548 * page-aligns the rest of the writes for large writes 549 * spanning multiple pages. 550 */ 551 head = pipe->head; 552 was_empty = pipe_empty(head, pipe->tail); 553 chars = total_len & (PAGE_SIZE-1); 554 if (chars && !was_empty) { 555 struct pipe_buffer *buf = pipe_buf(pipe, head - 1); 556 int offset = buf->offset + buf->len; 557 558 if ((buf->flags & PIPE_BUF_FLAG_CAN_MERGE) && 559 offset + chars <= PAGE_SIZE) { 560 ret = pipe_buf_confirm(pipe, buf); 561 if (ret) 562 goto out; 563 564 ret = copy_page_from_iter(buf->page, offset, chars, from); 565 if (unlikely(ret < chars)) { 566 ret = -EFAULT; 567 goto out; 568 } 569 570 buf->len += ret; 571 if (!iov_iter_count(from)) 572 goto out; 573 } 574 } 575 576 for (;;) { 577 if (!pipe->readers) { 578 if ((iocb->ki_flags & IOCB_NOSIGNAL) == 0) 579 send_sig(SIGPIPE, current, 0); 580 if (!ret) 581 ret = -EPIPE; 582 break; 583 } 584 585 head = pipe->head; 586 if (!pipe_full(head, pipe->tail, pipe->max_usage)) { 587 struct pipe_buffer *buf; 588 struct page *page; 589 int copied; 590 591 page = anon_pipe_get_page(pipe); 592 if (unlikely(!page)) { 593 if (!ret) 594 ret = -ENOMEM; 595 break; 596 } 597 598 copied = copy_page_from_iter(page, 0, PAGE_SIZE, from); 599 if (unlikely(copied < PAGE_SIZE && iov_iter_count(from))) { 600 anon_pipe_put_page(pipe, page); 601 if (!ret) 602 ret = -EFAULT; 603 break; 604 } 605 606 pipe->head = head + 1; 607 /* Insert it into the buffer array */ 608 buf = pipe_buf(pipe, head); 609 buf->page = page; 610 buf->ops = &anon_pipe_buf_ops; 611 buf->offset = 0; 612 if (is_packetized(filp)) 613 buf->flags = PIPE_BUF_FLAG_PACKET; 614 else 615 buf->flags = PIPE_BUF_FLAG_CAN_MERGE; 616 617 buf->len = copied; 618 ret += copied; 619 620 if (!iov_iter_count(from)) 621 break; 622 623 continue; 624 } 625 626 /* Wait for buffer space to become available. */ 627 if ((filp->f_flags & O_NONBLOCK) || 628 (iocb->ki_flags & IOCB_NOWAIT)) { 629 if (!ret) 630 ret = -EAGAIN; 631 break; 632 } 633 if (signal_pending(current)) { 634 if (!ret) 635 ret = -ERESTARTSYS; 636 break; 637 } 638 639 /* 640 * We're going to release the pipe lock and wait for more 641 * space. We wake up any readers if necessary, and then 642 * after waiting we need to re-check whether the pipe 643 * become empty while we dropped the lock. 644 */ 645 mutex_unlock(&pipe->mutex); 646 if (was_empty) 647 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM); 648 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); 649 wait_event_interruptible_exclusive(pipe->wr_wait, pipe_writable(pipe)); 650 mutex_lock(&pipe->mutex); 651 was_empty = pipe_is_empty(pipe); 652 wake_next_writer = true; 653 } 654 out: 655 if (pipe_is_full(pipe)) 656 wake_next_writer = false; 657 anon_pipe_trim_and_unlock(pipe); 658 659 /* 660 * If we do do a wakeup event, we do a 'sync' wakeup, because we 661 * want the reader to start processing things asap, rather than 662 * leave the data pending. 663 * 664 * This is particularly important for small writes, because of 665 * how (for example) the GNU make jobserver uses small writes to 666 * wake up pending jobs 667 * 668 * ->pseudo_edgetrigger enables per-write wakeups, see pipe_poll() 669 */ 670 if (was_empty || READ_ONCE(pipe->pseudo_edgetrigger)) 671 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM); 672 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); 673 if (wake_next_writer) 674 wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM); 675 return ret; 676 } 677 678 static ssize_t 679 fifo_pipe_write(struct kiocb *iocb, struct iov_iter *from) 680 { 681 int ret = anon_pipe_write(iocb, from); 682 if (ret > 0) { 683 struct file *filp = iocb->ki_filp; 684 if (sb_start_write_trylock(file_inode(filp)->i_sb)) { 685 int err = file_update_time(filp); 686 if (err) 687 ret = err; 688 sb_end_write(file_inode(filp)->i_sb); 689 } 690 } 691 return ret; 692 } 693 694 static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) 695 { 696 struct pipe_inode_info *pipe = filp->private_data; 697 unsigned int count, head, tail; 698 699 switch (cmd) { 700 case FIONREAD: 701 mutex_lock(&pipe->mutex); 702 count = 0; 703 head = pipe->head; 704 tail = pipe->tail; 705 706 while (!pipe_empty(head, tail)) { 707 count += pipe_buf(pipe, tail)->len; 708 tail++; 709 } 710 mutex_unlock(&pipe->mutex); 711 712 return put_user(count, (int __user *)arg); 713 714 #ifdef CONFIG_WATCH_QUEUE 715 case IOC_WATCH_QUEUE_SET_SIZE: { 716 int ret; 717 mutex_lock(&pipe->mutex); 718 ret = watch_queue_set_size(pipe, arg); 719 mutex_unlock(&pipe->mutex); 720 return ret; 721 } 722 723 case IOC_WATCH_QUEUE_SET_FILTER: 724 return watch_queue_set_filter( 725 pipe, (struct watch_notification_filter __user *)arg); 726 #endif 727 728 default: 729 return -ENOIOCTLCMD; 730 } 731 } 732 733 static __poll_t 734 pipe_poll(struct file *filp, poll_table *wait) 735 { 736 __poll_t mask; 737 struct pipe_inode_info *pipe = filp->private_data; 738 union pipe_index idx; 739 740 /* 741 * Legacy epoll(EPOLLET) users depend on historical per-write wakeups, 742 * see 3a34b13a88ca ("pipe: make pipe writes always wake up readers") 743 * and the ->pseudo_edgetrigger check in anon_pipe_write(). 744 * Currently io_uring sets EPOLLET for multishot polls, so it gets the 745 * same behaviour. 746 */ 747 if ((filp->f_mode & FMODE_READ) && 748 wait && (wait->_key & EPOLLET) && 749 unlikely(!READ_ONCE(pipe->pseudo_edgetrigger))) 750 WRITE_ONCE(pipe->pseudo_edgetrigger, true); 751 752 /* 753 * Reading pipe state only -- no need for acquiring the semaphore. 754 * 755 * But because this is racy, the code has to add the 756 * entry to the poll table _first_ .. 757 */ 758 if (filp->f_mode & FMODE_READ) 759 poll_wait(filp, &pipe->rd_wait, wait); 760 if (filp->f_mode & FMODE_WRITE) 761 poll_wait(filp, &pipe->wr_wait, wait); 762 763 /* 764 * .. and only then can you do the racy tests. That way, 765 * if something changes and you got it wrong, the poll 766 * table entry will wake you up and fix it. 767 */ 768 idx.head_tail = READ_ONCE(pipe->head_tail); 769 770 mask = 0; 771 if (filp->f_mode & FMODE_READ) { 772 if (!pipe_empty(idx.head, idx.tail)) 773 mask |= EPOLLIN | EPOLLRDNORM; 774 if (!pipe->writers && filp->f_pipe != pipe->w_counter) 775 mask |= EPOLLHUP; 776 } 777 778 if (filp->f_mode & FMODE_WRITE) { 779 if (!pipe_full(idx.head, idx.tail, pipe->max_usage)) 780 mask |= EPOLLOUT | EPOLLWRNORM; 781 /* 782 * Most Unices do not set EPOLLERR for FIFOs but on Linux they 783 * behave exactly like pipes for poll(). 784 */ 785 if (!pipe->readers) 786 mask |= EPOLLERR; 787 } 788 789 return mask; 790 } 791 792 static void put_pipe_info(struct inode *inode, struct pipe_inode_info *pipe) 793 { 794 int kill = 0; 795 796 spin_lock(&inode->i_lock); 797 if (!--pipe->files) { 798 inode->i_pipe = NULL; 799 kill = 1; 800 } 801 spin_unlock(&inode->i_lock); 802 803 if (kill) 804 free_pipe_info(pipe); 805 } 806 807 static int 808 pipe_release(struct inode *inode, struct file *file) 809 { 810 struct pipe_inode_info *pipe = file->private_data; 811 812 mutex_lock(&pipe->mutex); 813 if (file->f_mode & FMODE_READ) 814 pipe->readers--; 815 if (file->f_mode & FMODE_WRITE) 816 pipe->writers--; 817 818 /* Was that the last reader or writer, but not the other side? */ 819 if (!pipe->readers != !pipe->writers) { 820 wake_up_interruptible_all(&pipe->rd_wait); 821 wake_up_interruptible_all(&pipe->wr_wait); 822 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); 823 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT); 824 } 825 mutex_unlock(&pipe->mutex); 826 827 put_pipe_info(inode, pipe); 828 return 0; 829 } 830 831 static int 832 pipe_fasync(int fd, struct file *filp, int on) 833 { 834 struct pipe_inode_info *pipe = filp->private_data; 835 int retval = 0; 836 837 mutex_lock(&pipe->mutex); 838 if (filp->f_mode & FMODE_READ) 839 retval = fasync_helper(fd, filp, on, &pipe->fasync_readers); 840 if ((filp->f_mode & FMODE_WRITE) && retval >= 0) { 841 retval = fasync_helper(fd, filp, on, &pipe->fasync_writers); 842 if (retval < 0 && (filp->f_mode & FMODE_READ)) 843 /* this can happen only if on == T */ 844 fasync_helper(-1, filp, 0, &pipe->fasync_readers); 845 } 846 mutex_unlock(&pipe->mutex); 847 return retval; 848 } 849 850 unsigned long account_pipe_buffers(struct user_struct *user, 851 unsigned long old, unsigned long new) 852 { 853 return atomic_long_add_return(new - old, &user->pipe_bufs); 854 } 855 856 bool too_many_pipe_buffers_soft(unsigned long user_bufs) 857 { 858 unsigned long soft_limit = READ_ONCE(pipe_user_pages_soft); 859 860 return soft_limit && user_bufs > soft_limit; 861 } 862 863 bool too_many_pipe_buffers_hard(unsigned long user_bufs) 864 { 865 unsigned long hard_limit = READ_ONCE(pipe_user_pages_hard); 866 867 return hard_limit && user_bufs > hard_limit; 868 } 869 870 bool pipe_is_unprivileged_user(void) 871 { 872 return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN); 873 } 874 875 struct pipe_inode_info *alloc_pipe_info(void) 876 { 877 struct pipe_inode_info *pipe; 878 unsigned long pipe_bufs = PIPE_DEF_BUFFERS; 879 struct user_struct *user = get_current_user(); 880 unsigned long user_bufs; 881 unsigned int max_size = READ_ONCE(pipe_max_size); 882 883 pipe = kzalloc_obj(struct pipe_inode_info, GFP_KERNEL_ACCOUNT); 884 if (pipe == NULL) 885 goto out_free_uid; 886 887 if (pipe_bufs * PAGE_SIZE > max_size && !capable(CAP_SYS_RESOURCE)) 888 pipe_bufs = max_size >> PAGE_SHIFT; 889 890 user_bufs = account_pipe_buffers(user, 0, pipe_bufs); 891 892 if (too_many_pipe_buffers_soft(user_bufs) && pipe_is_unprivileged_user()) { 893 user_bufs = account_pipe_buffers(user, pipe_bufs, PIPE_MIN_DEF_BUFFERS); 894 pipe_bufs = PIPE_MIN_DEF_BUFFERS; 895 } 896 897 if (too_many_pipe_buffers_hard(user_bufs) && pipe_is_unprivileged_user()) 898 goto out_revert_acct; 899 900 pipe->bufs = kzalloc_objs(struct pipe_buffer, pipe_bufs, 901 GFP_KERNEL_ACCOUNT); 902 903 if (pipe->bufs) { 904 init_waitqueue_head(&pipe->rd_wait); 905 init_waitqueue_head(&pipe->wr_wait); 906 pipe->r_counter = pipe->w_counter = 1; 907 pipe->max_usage = pipe_bufs; 908 pipe->ring_size = pipe_bufs; 909 pipe->nr_accounted = pipe_bufs; 910 pipe->user = user; 911 mutex_init(&pipe->mutex); 912 lock_set_cmp_fn(&pipe->mutex, pipe_lock_cmp_fn, NULL); 913 return pipe; 914 } 915 916 out_revert_acct: 917 (void) account_pipe_buffers(user, pipe_bufs, 0); 918 kfree(pipe); 919 out_free_uid: 920 free_uid(user); 921 return NULL; 922 } 923 924 void free_pipe_info(struct pipe_inode_info *pipe) 925 { 926 unsigned int i; 927 928 #ifdef CONFIG_WATCH_QUEUE 929 if (pipe->watch_queue) 930 watch_queue_clear(pipe->watch_queue); 931 #endif 932 933 (void) account_pipe_buffers(pipe->user, pipe->nr_accounted, 0); 934 free_uid(pipe->user); 935 for (i = 0; i < pipe->ring_size; i++) { 936 struct pipe_buffer *buf = pipe->bufs + i; 937 if (buf->ops) 938 pipe_buf_release(pipe, buf); 939 } 940 #ifdef CONFIG_WATCH_QUEUE 941 if (pipe->watch_queue) 942 put_watch_queue(pipe->watch_queue); 943 #endif 944 for (i = 0; i < pipe->prealloc.count; i++) 945 __free_page(pipe->prealloc.pages[i]); 946 kfree(pipe->bufs); 947 kfree(pipe); 948 } 949 950 static struct vfsmount *pipe_mnt __ro_after_init; 951 952 /* 953 * pipefs_dname() is called from d_path(). 954 */ 955 static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen) 956 { 957 return dynamic_dname(buffer, buflen, "pipe:[%llu]", 958 d_inode(dentry)->i_ino); 959 } 960 961 static const struct dentry_operations pipefs_dentry_operations = { 962 .d_dname = pipefs_dname, 963 }; 964 965 static const struct file_operations pipeanon_fops; 966 967 static struct inode * get_pipe_inode(void) 968 { 969 struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb); 970 struct pipe_inode_info *pipe; 971 972 if (!inode) 973 goto fail_inode; 974 975 inode->i_ino = get_next_ino(); 976 977 pipe = alloc_pipe_info(); 978 if (!pipe) 979 goto fail_iput; 980 981 inode->i_pipe = pipe; 982 pipe->files = 2; 983 pipe->readers = pipe->writers = 1; 984 inode->i_fop = &pipeanon_fops; 985 986 /* 987 * Mark the inode dirty from the very beginning, 988 * that way it will never be moved to the dirty 989 * list because "mark_inode_dirty()" will think 990 * that it already _is_ on the dirty list. 991 */ 992 inode_state_assign_raw(inode, I_DIRTY); 993 inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR; 994 inode->i_uid = current_fsuid(); 995 inode->i_gid = current_fsgid(); 996 simple_inode_init_ts(inode); 997 998 return inode; 999 1000 fail_iput: 1001 iput(inode); 1002 1003 fail_inode: 1004 return NULL; 1005 } 1006 1007 int create_pipe_files(struct file **res, int flags) 1008 { 1009 struct inode *inode = get_pipe_inode(); 1010 struct file *f; 1011 int error; 1012 1013 if (!inode) 1014 return -ENFILE; 1015 1016 if (flags & O_NOTIFICATION_PIPE) { 1017 error = watch_queue_init(inode->i_pipe); 1018 if (error) { 1019 free_pipe_info(inode->i_pipe); 1020 iput(inode); 1021 return error; 1022 } 1023 } 1024 1025 f = alloc_file_pseudo(inode, pipe_mnt, "", 1026 O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)), 1027 &pipeanon_fops); 1028 if (IS_ERR(f)) { 1029 free_pipe_info(inode->i_pipe); 1030 iput(inode); 1031 return PTR_ERR(f); 1032 } 1033 1034 f->private_data = inode->i_pipe; 1035 f->f_pipe = 0; 1036 1037 res[0] = alloc_file_clone(f, O_RDONLY | (flags & O_NONBLOCK), 1038 &pipeanon_fops); 1039 if (IS_ERR(res[0])) { 1040 put_pipe_info(inode, inode->i_pipe); 1041 fput(f); 1042 return PTR_ERR(res[0]); 1043 } 1044 res[0]->private_data = inode->i_pipe; 1045 res[0]->f_pipe = 0; 1046 res[1] = f; 1047 stream_open(inode, res[0]); 1048 stream_open(inode, res[1]); 1049 1050 /* pipe groks IOCB_NOWAIT */ 1051 res[0]->f_mode |= FMODE_NOWAIT; 1052 res[1]->f_mode |= FMODE_NOWAIT; 1053 1054 /* 1055 * Disable permission and pre-content events, but enable legacy 1056 * inotify events for legacy users. 1057 */ 1058 file_set_fsnotify_mode(res[0], FMODE_NONOTIFY_PERM); 1059 file_set_fsnotify_mode(res[1], FMODE_NONOTIFY_PERM); 1060 return 0; 1061 } 1062 1063 static int __do_pipe_flags(int *fd, struct file **files, int flags) 1064 { 1065 int error; 1066 int fdw, fdr; 1067 1068 if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT | O_NOTIFICATION_PIPE)) 1069 return -EINVAL; 1070 1071 error = create_pipe_files(files, flags); 1072 if (error) 1073 return error; 1074 1075 error = get_unused_fd_flags(flags); 1076 if (error < 0) 1077 goto err_read_pipe; 1078 fdr = error; 1079 1080 error = get_unused_fd_flags(flags); 1081 if (error < 0) 1082 goto err_fdr; 1083 fdw = error; 1084 1085 audit_fd_pair(fdr, fdw); 1086 fd[0] = fdr; 1087 fd[1] = fdw; 1088 return 0; 1089 1090 err_fdr: 1091 put_unused_fd(fdr); 1092 err_read_pipe: 1093 fput(files[0]); 1094 fput(files[1]); 1095 return error; 1096 } 1097 1098 int do_pipe_flags(int *fd, int flags) 1099 { 1100 struct file *files[2]; 1101 int error = __do_pipe_flags(fd, files, flags); 1102 if (!error) { 1103 fd_install(fd[0], files[0]); 1104 fd_install(fd[1], files[1]); 1105 } 1106 return error; 1107 } 1108 1109 /* 1110 * sys_pipe() is the normal C calling standard for creating 1111 * a pipe. It's not the way Unix traditionally does this, though. 1112 */ 1113 static int do_pipe2(int __user *fildes, int flags) 1114 { 1115 struct file *files[2]; 1116 int fd[2]; 1117 int error; 1118 1119 error = __do_pipe_flags(fd, files, flags); 1120 if (!error) { 1121 if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) { 1122 fput(files[0]); 1123 fput(files[1]); 1124 put_unused_fd(fd[0]); 1125 put_unused_fd(fd[1]); 1126 error = -EFAULT; 1127 } else { 1128 fd_install(fd[0], files[0]); 1129 fd_install(fd[1], files[1]); 1130 } 1131 } 1132 return error; 1133 } 1134 1135 SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags) 1136 { 1137 return do_pipe2(fildes, flags); 1138 } 1139 1140 SYSCALL_DEFINE1(pipe, int __user *, fildes) 1141 { 1142 return do_pipe2(fildes, 0); 1143 } 1144 1145 /* 1146 * This is the stupid "wait for pipe to be readable or writable" 1147 * model. 1148 * 1149 * See pipe_read/write() for the proper kind of exclusive wait, 1150 * but that requires that we wake up any other readers/writers 1151 * if we then do not end up reading everything (ie the whole 1152 * "wake_next_reader/writer" logic in pipe_read/write()). 1153 */ 1154 void pipe_wait_readable(struct pipe_inode_info *pipe) 1155 { 1156 pipe_unlock(pipe); 1157 wait_event_interruptible(pipe->rd_wait, pipe_readable(pipe)); 1158 pipe_lock(pipe); 1159 } 1160 1161 void pipe_wait_writable(struct pipe_inode_info *pipe) 1162 { 1163 pipe_unlock(pipe); 1164 wait_event_interruptible(pipe->wr_wait, pipe_writable(pipe)); 1165 pipe_lock(pipe); 1166 } 1167 1168 /* 1169 * This depends on both the wait (here) and the wakeup (wake_up_partner) 1170 * holding the pipe lock, so "*cnt" is stable and we know a wakeup cannot 1171 * race with the count check and waitqueue prep. 1172 * 1173 * Normally in order to avoid races, you'd do the prepare_to_wait() first, 1174 * then check the condition you're waiting for, and only then sleep. But 1175 * because of the pipe lock, we can check the condition before being on 1176 * the wait queue. 1177 * 1178 * We use the 'rd_wait' waitqueue for pipe partner waiting. 1179 */ 1180 static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt) 1181 { 1182 DEFINE_WAIT(rdwait); 1183 int cur = *cnt; 1184 1185 while (cur == *cnt) { 1186 prepare_to_wait(&pipe->rd_wait, &rdwait, TASK_INTERRUPTIBLE); 1187 pipe_unlock(pipe); 1188 schedule(); 1189 finish_wait(&pipe->rd_wait, &rdwait); 1190 pipe_lock(pipe); 1191 if (signal_pending(current)) 1192 break; 1193 } 1194 return cur == *cnt ? -ERESTARTSYS : 0; 1195 } 1196 1197 static void wake_up_partner(struct pipe_inode_info *pipe) 1198 { 1199 wake_up_interruptible_all(&pipe->rd_wait); 1200 } 1201 1202 static int fifo_open(struct inode *inode, struct file *filp) 1203 { 1204 bool is_pipe = inode->i_fop == &pipeanon_fops; 1205 struct pipe_inode_info *pipe; 1206 int ret; 1207 1208 filp->f_pipe = 0; 1209 1210 spin_lock(&inode->i_lock); 1211 if (inode->i_pipe) { 1212 pipe = inode->i_pipe; 1213 pipe->files++; 1214 spin_unlock(&inode->i_lock); 1215 } else { 1216 spin_unlock(&inode->i_lock); 1217 pipe = alloc_pipe_info(); 1218 if (!pipe) 1219 return -ENOMEM; 1220 pipe->files = 1; 1221 spin_lock(&inode->i_lock); 1222 if (unlikely(inode->i_pipe)) { 1223 inode->i_pipe->files++; 1224 spin_unlock(&inode->i_lock); 1225 free_pipe_info(pipe); 1226 pipe = inode->i_pipe; 1227 } else { 1228 inode->i_pipe = pipe; 1229 spin_unlock(&inode->i_lock); 1230 } 1231 } 1232 filp->private_data = pipe; 1233 /* OK, we have a pipe and it's pinned down */ 1234 1235 mutex_lock(&pipe->mutex); 1236 1237 /* We can only do regular read/write on fifos */ 1238 stream_open(inode, filp); 1239 1240 switch (filp->f_mode & (FMODE_READ | FMODE_WRITE)) { 1241 case FMODE_READ: 1242 /* 1243 * O_RDONLY 1244 * POSIX.1 says that O_NONBLOCK means return with the FIFO 1245 * opened, even when there is no process writing the FIFO. 1246 */ 1247 pipe->r_counter++; 1248 if (pipe->readers++ == 0) 1249 wake_up_partner(pipe); 1250 1251 if (!is_pipe && !pipe->writers) { 1252 if ((filp->f_flags & O_NONBLOCK)) { 1253 /* suppress EPOLLHUP until we have 1254 * seen a writer */ 1255 filp->f_pipe = pipe->w_counter; 1256 } else { 1257 if (wait_for_partner(pipe, &pipe->w_counter)) 1258 goto err_rd; 1259 } 1260 } 1261 break; 1262 1263 case FMODE_WRITE: 1264 /* 1265 * O_WRONLY 1266 * POSIX.1 says that O_NONBLOCK means return -1 with 1267 * errno=ENXIO when there is no process reading the FIFO. 1268 */ 1269 ret = -ENXIO; 1270 if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers) 1271 goto err; 1272 1273 pipe->w_counter++; 1274 if (!pipe->writers++) 1275 wake_up_partner(pipe); 1276 1277 if (!is_pipe && !pipe->readers) { 1278 if (wait_for_partner(pipe, &pipe->r_counter)) 1279 goto err_wr; 1280 } 1281 break; 1282 1283 case FMODE_READ | FMODE_WRITE: 1284 /* 1285 * O_RDWR 1286 * POSIX.1 leaves this case "undefined" when O_NONBLOCK is set. 1287 * This implementation will NEVER block on a O_RDWR open, since 1288 * the process can at least talk to itself. 1289 */ 1290 1291 pipe->readers++; 1292 pipe->writers++; 1293 pipe->r_counter++; 1294 pipe->w_counter++; 1295 if (pipe->readers == 1 || pipe->writers == 1) 1296 wake_up_partner(pipe); 1297 break; 1298 1299 default: 1300 ret = -EINVAL; 1301 goto err; 1302 } 1303 1304 /* Ok! */ 1305 mutex_unlock(&pipe->mutex); 1306 return 0; 1307 1308 err_rd: 1309 if (!--pipe->readers) 1310 wake_up_interruptible(&pipe->wr_wait); 1311 ret = -ERESTARTSYS; 1312 goto err; 1313 1314 err_wr: 1315 if (!--pipe->writers) 1316 wake_up_interruptible_all(&pipe->rd_wait); 1317 ret = -ERESTARTSYS; 1318 goto err; 1319 1320 err: 1321 mutex_unlock(&pipe->mutex); 1322 1323 put_pipe_info(inode, pipe); 1324 return ret; 1325 } 1326 1327 const struct file_operations pipefifo_fops = { 1328 .open = fifo_open, 1329 .read_iter = fifo_pipe_read, 1330 .write_iter = fifo_pipe_write, 1331 .poll = pipe_poll, 1332 .unlocked_ioctl = pipe_ioctl, 1333 .release = pipe_release, 1334 .fasync = pipe_fasync, 1335 .splice_write = iter_file_splice_write, 1336 }; 1337 1338 static const struct file_operations pipeanon_fops = { 1339 .open = fifo_open, 1340 .read_iter = anon_pipe_read, 1341 .write_iter = anon_pipe_write, 1342 .poll = pipe_poll, 1343 .unlocked_ioctl = pipe_ioctl, 1344 .release = pipe_release, 1345 .fasync = pipe_fasync, 1346 .splice_write = iter_file_splice_write, 1347 }; 1348 1349 /* 1350 * Currently we rely on the pipe array holding a power-of-2 number 1351 * of pages. Returns 0 on error. 1352 */ 1353 unsigned int round_pipe_size(unsigned int size) 1354 { 1355 if (size > (1U << 31)) 1356 return 0; 1357 1358 /* Minimum pipe size, as required by POSIX */ 1359 if (size < PAGE_SIZE) 1360 return PAGE_SIZE; 1361 1362 return roundup_pow_of_two(size); 1363 } 1364 1365 /* 1366 * Resize the pipe ring to a number of slots. 1367 * 1368 * Note the pipe can be reduced in capacity, but only if the current 1369 * occupancy doesn't exceed nr_slots; if it does, EBUSY will be 1370 * returned instead. 1371 */ 1372 int pipe_resize_ring(struct pipe_inode_info *pipe, unsigned int nr_slots) 1373 { 1374 struct pipe_buffer *bufs; 1375 unsigned int head, tail, mask, n; 1376 1377 /* nr_slots larger than limits of pipe->{head,tail} */ 1378 if (unlikely(nr_slots > (pipe_index_t)-1u)) 1379 return -EINVAL; 1380 1381 bufs = kzalloc_objs(*bufs, nr_slots, GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 1382 if (unlikely(!bufs)) 1383 return -ENOMEM; 1384 1385 spin_lock_irq(&pipe->rd_wait.lock); 1386 mask = pipe->ring_size - 1; 1387 head = pipe->head; 1388 tail = pipe->tail; 1389 1390 n = pipe_occupancy(head, tail); 1391 if (nr_slots < n) { 1392 spin_unlock_irq(&pipe->rd_wait.lock); 1393 kfree(bufs); 1394 return -EBUSY; 1395 } 1396 1397 /* 1398 * The pipe array wraps around, so just start the new one at zero 1399 * and adjust the indices. 1400 */ 1401 if (n > 0) { 1402 unsigned int h = head & mask; 1403 unsigned int t = tail & mask; 1404 if (h > t) { 1405 memcpy(bufs, pipe->bufs + t, 1406 n * sizeof(struct pipe_buffer)); 1407 } else { 1408 unsigned int tsize = pipe->ring_size - t; 1409 if (h > 0) 1410 memcpy(bufs + tsize, pipe->bufs, 1411 h * sizeof(struct pipe_buffer)); 1412 memcpy(bufs, pipe->bufs + t, 1413 tsize * sizeof(struct pipe_buffer)); 1414 } 1415 } 1416 1417 head = n; 1418 tail = 0; 1419 1420 kfree(pipe->bufs); 1421 pipe->bufs = bufs; 1422 pipe->ring_size = nr_slots; 1423 if (pipe->max_usage > nr_slots) 1424 pipe->max_usage = nr_slots; 1425 pipe->tail = tail; 1426 pipe->head = head; 1427 1428 if (!pipe_has_watch_queue(pipe)) { 1429 pipe->max_usage = nr_slots; 1430 pipe->nr_accounted = nr_slots; 1431 } 1432 1433 spin_unlock_irq(&pipe->rd_wait.lock); 1434 1435 /* This might have made more room for writers */ 1436 wake_up_interruptible(&pipe->wr_wait); 1437 return 0; 1438 } 1439 1440 /* 1441 * Allocate a new array of pipe buffers and copy the info over. Returns the 1442 * pipe size if successful, or return -ERROR on error. 1443 */ 1444 static long pipe_set_size(struct pipe_inode_info *pipe, unsigned int arg) 1445 { 1446 unsigned long user_bufs; 1447 unsigned int nr_slots, size; 1448 long ret = 0; 1449 1450 if (pipe_has_watch_queue(pipe)) 1451 return -EBUSY; 1452 1453 size = round_pipe_size(arg); 1454 nr_slots = size >> PAGE_SHIFT; 1455 1456 if (!nr_slots) 1457 return -EINVAL; 1458 1459 /* 1460 * If trying to increase the pipe capacity, check that an 1461 * unprivileged user is not trying to exceed various limits 1462 * (soft limit check here, hard limit check just below). 1463 * Decreasing the pipe capacity is always permitted, even 1464 * if the user is currently over a limit. 1465 */ 1466 if (nr_slots > pipe->max_usage && 1467 size > pipe_max_size && !capable(CAP_SYS_RESOURCE)) 1468 return -EPERM; 1469 1470 user_bufs = account_pipe_buffers(pipe->user, pipe->nr_accounted, nr_slots); 1471 1472 if (nr_slots > pipe->max_usage && 1473 (too_many_pipe_buffers_hard(user_bufs) || 1474 too_many_pipe_buffers_soft(user_bufs)) && 1475 pipe_is_unprivileged_user()) { 1476 ret = -EPERM; 1477 goto out_revert_acct; 1478 } 1479 1480 ret = pipe_resize_ring(pipe, nr_slots); 1481 if (ret < 0) 1482 goto out_revert_acct; 1483 1484 return pipe->max_usage * PAGE_SIZE; 1485 1486 out_revert_acct: 1487 (void) account_pipe_buffers(pipe->user, nr_slots, pipe->nr_accounted); 1488 return ret; 1489 } 1490 1491 /* 1492 * Note that i_pipe and i_cdev share the same location, so checking ->i_pipe is 1493 * not enough to verify that this is a pipe. 1494 */ 1495 struct pipe_inode_info *get_pipe_info(struct file *file, bool for_splice) 1496 { 1497 struct pipe_inode_info *pipe = file->private_data; 1498 1499 if (!pipe) 1500 return NULL; 1501 if (file->f_op != &pipefifo_fops && file->f_op != &pipeanon_fops) 1502 return NULL; 1503 if (for_splice && pipe_has_watch_queue(pipe)) 1504 return NULL; 1505 return pipe; 1506 } 1507 1508 long pipe_fcntl(struct file *file, unsigned int cmd, unsigned int arg) 1509 { 1510 struct pipe_inode_info *pipe; 1511 long ret; 1512 1513 pipe = get_pipe_info(file, false); 1514 if (!pipe) 1515 return -EBADF; 1516 1517 mutex_lock(&pipe->mutex); 1518 1519 switch (cmd) { 1520 case F_SETPIPE_SZ: 1521 ret = pipe_set_size(pipe, arg); 1522 break; 1523 case F_GETPIPE_SZ: 1524 ret = pipe->max_usage * PAGE_SIZE; 1525 break; 1526 default: 1527 ret = -EINVAL; 1528 break; 1529 } 1530 1531 mutex_unlock(&pipe->mutex); 1532 return ret; 1533 } 1534 1535 static const struct super_operations pipefs_ops = { 1536 .destroy_inode = free_inode_nonrcu, 1537 .statfs = simple_statfs, 1538 }; 1539 1540 /* 1541 * pipefs should _never_ be mounted by userland - too much of security hassle, 1542 * no real gain from having the whole file system mounted. So we don't need 1543 * any operations on the root directory. However, we need a non-trivial 1544 * d_name - pipe: will go nicely and kill the special-casing in procfs. 1545 */ 1546 1547 static int pipefs_init_fs_context(struct fs_context *fc) 1548 { 1549 struct pseudo_fs_context *ctx = init_pseudo(fc, PIPEFS_MAGIC); 1550 if (!ctx) 1551 return -ENOMEM; 1552 ctx->ops = &pipefs_ops; 1553 ctx->dops = &pipefs_dentry_operations; 1554 return 0; 1555 } 1556 1557 static struct file_system_type pipe_fs_type = { 1558 .name = "pipefs", 1559 .init_fs_context = pipefs_init_fs_context, 1560 .kill_sb = kill_anon_super, 1561 }; 1562 1563 #ifdef CONFIG_SYSCTL 1564 1565 static ulong round_pipe_size_ul(ulong size) 1566 { 1567 return round_pipe_size(size); 1568 } 1569 1570 static int u2k_pipe_maxsz(const ulong *u_ptr, uint *k_ptr) 1571 { 1572 return proc_uint_u2k_conv_uop(u_ptr, k_ptr, round_pipe_size_ul); 1573 } 1574 1575 static int do_proc_uint_conv_pipe_maxsz(ulong *u_ptr, uint *k_ptr, 1576 int dir, const struct ctl_table *table) 1577 { 1578 return proc_uint_conv(u_ptr, k_ptr, dir, table, true, 1579 u2k_pipe_maxsz, 1580 proc_uint_k2u_conv); 1581 } 1582 1583 static int proc_dopipe_max_size(const struct ctl_table *table, int write, 1584 void *buffer, size_t *lenp, loff_t *ppos) 1585 { 1586 return proc_douintvec_conv(table, write, buffer, lenp, ppos, 1587 do_proc_uint_conv_pipe_maxsz); 1588 } 1589 1590 static const struct ctl_table fs_pipe_sysctls[] = { 1591 { 1592 .procname = "pipe-max-size", 1593 .data = &pipe_max_size, 1594 .maxlen = sizeof(pipe_max_size), 1595 .mode = 0644, 1596 .proc_handler = proc_dopipe_max_size, 1597 .extra1 = SYSCTL_ONE, 1598 }, 1599 { 1600 .procname = "pipe-user-pages-hard", 1601 .data = &pipe_user_pages_hard, 1602 .maxlen = sizeof(pipe_user_pages_hard), 1603 .mode = 0644, 1604 .proc_handler = proc_doulongvec_minmax, 1605 }, 1606 { 1607 .procname = "pipe-user-pages-soft", 1608 .data = &pipe_user_pages_soft, 1609 .maxlen = sizeof(pipe_user_pages_soft), 1610 .mode = 0644, 1611 .proc_handler = proc_doulongvec_minmax, 1612 }, 1613 }; 1614 #endif 1615 1616 static int __init init_pipe_fs(void) 1617 { 1618 int err = register_filesystem(&pipe_fs_type); 1619 1620 if (!err) { 1621 pipe_mnt = kern_mount(&pipe_fs_type); 1622 if (IS_ERR(pipe_mnt)) { 1623 err = PTR_ERR(pipe_mnt); 1624 unregister_filesystem(&pipe_fs_type); 1625 } 1626 } 1627 #ifdef CONFIG_SYSCTL 1628 register_sysctl_init("fs", fs_pipe_sysctls); 1629 #endif 1630 return err; 1631 } 1632 1633 fs_initcall(init_pipe_fs); 1634