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 int read_ret = retval; 842 843 retval = fasync_helper(fd, filp, on, &pipe->fasync_writers); 844 /* Undo only a reader entry added by this call. */ 845 if (retval < 0 && read_ret > 0) 846 fasync_helper(-1, filp, 0, &pipe->fasync_readers); 847 } 848 mutex_unlock(&pipe->mutex); 849 return retval; 850 } 851 852 unsigned long account_pipe_buffers(struct user_struct *user, 853 unsigned long old, unsigned long new) 854 { 855 return atomic_long_add_return(new - old, &user->pipe_bufs); 856 } 857 858 bool too_many_pipe_buffers_soft(unsigned long user_bufs) 859 { 860 unsigned long soft_limit = READ_ONCE(pipe_user_pages_soft); 861 862 return soft_limit && user_bufs > soft_limit; 863 } 864 865 bool too_many_pipe_buffers_hard(unsigned long user_bufs) 866 { 867 unsigned long hard_limit = READ_ONCE(pipe_user_pages_hard); 868 869 return hard_limit && user_bufs > hard_limit; 870 } 871 872 bool pipe_is_unprivileged_user(void) 873 { 874 return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN); 875 } 876 877 struct pipe_inode_info *alloc_pipe_info(void) 878 { 879 struct pipe_inode_info *pipe; 880 unsigned long pipe_bufs = PIPE_DEF_BUFFERS; 881 struct user_struct *user = get_current_user(); 882 unsigned long user_bufs; 883 unsigned int max_size = READ_ONCE(pipe_max_size); 884 885 pipe = kzalloc_obj(struct pipe_inode_info, GFP_KERNEL_ACCOUNT); 886 if (pipe == NULL) 887 goto out_free_uid; 888 889 if (pipe_bufs * PAGE_SIZE > max_size && !capable(CAP_SYS_RESOURCE)) 890 pipe_bufs = max_size >> PAGE_SHIFT; 891 892 user_bufs = account_pipe_buffers(user, 0, pipe_bufs); 893 894 if (too_many_pipe_buffers_soft(user_bufs) && pipe_is_unprivileged_user()) { 895 user_bufs = account_pipe_buffers(user, pipe_bufs, PIPE_MIN_DEF_BUFFERS); 896 pipe_bufs = PIPE_MIN_DEF_BUFFERS; 897 } 898 899 if (too_many_pipe_buffers_hard(user_bufs) && pipe_is_unprivileged_user()) 900 goto out_revert_acct; 901 902 pipe->bufs = kzalloc_objs(struct pipe_buffer, pipe_bufs, 903 GFP_KERNEL_ACCOUNT); 904 905 if (pipe->bufs) { 906 init_waitqueue_head(&pipe->rd_wait); 907 init_waitqueue_head(&pipe->wr_wait); 908 pipe->r_counter = pipe->w_counter = 1; 909 pipe->max_usage = pipe_bufs; 910 pipe->ring_size = pipe_bufs; 911 pipe->nr_accounted = pipe_bufs; 912 pipe->user = user; 913 mutex_init(&pipe->mutex); 914 lock_set_cmp_fn(&pipe->mutex, pipe_lock_cmp_fn, NULL); 915 return pipe; 916 } 917 918 out_revert_acct: 919 (void) account_pipe_buffers(user, pipe_bufs, 0); 920 kfree(pipe); 921 out_free_uid: 922 free_uid(user); 923 return NULL; 924 } 925 926 void free_pipe_info(struct pipe_inode_info *pipe) 927 { 928 unsigned int i; 929 930 #ifdef CONFIG_WATCH_QUEUE 931 if (pipe->watch_queue) 932 watch_queue_clear(pipe->watch_queue); 933 #endif 934 935 (void) account_pipe_buffers(pipe->user, pipe->nr_accounted, 0); 936 free_uid(pipe->user); 937 for (i = 0; i < pipe->ring_size; i++) { 938 struct pipe_buffer *buf = pipe->bufs + i; 939 if (buf->ops) 940 pipe_buf_release(pipe, buf); 941 } 942 #ifdef CONFIG_WATCH_QUEUE 943 if (pipe->watch_queue) 944 put_watch_queue(pipe->watch_queue); 945 #endif 946 for (i = 0; i < pipe->prealloc.count; i++) 947 __free_page(pipe->prealloc.pages[i]); 948 kfree(pipe->bufs); 949 kfree(pipe); 950 } 951 952 static struct vfsmount *pipe_mnt __ro_after_init; 953 954 /* 955 * pipefs_dname() is called from d_path(). 956 */ 957 static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen) 958 { 959 return dynamic_dname(buffer, buflen, "pipe:[%llu]", 960 d_inode(dentry)->i_ino); 961 } 962 963 static const struct dentry_operations pipefs_dentry_operations = { 964 .d_dname = pipefs_dname, 965 }; 966 967 static const struct file_operations pipeanon_fops; 968 969 static struct inode * get_pipe_inode(void) 970 { 971 struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb); 972 struct pipe_inode_info *pipe; 973 974 if (!inode) 975 goto fail_inode; 976 977 inode->i_ino = get_next_ino(); 978 979 pipe = alloc_pipe_info(); 980 if (!pipe) 981 goto fail_iput; 982 983 inode->i_pipe = pipe; 984 pipe->files = 2; 985 pipe->readers = pipe->writers = 1; 986 inode->i_fop = &pipeanon_fops; 987 988 /* 989 * Mark the inode dirty from the very beginning, 990 * that way it will never be moved to the dirty 991 * list because "mark_inode_dirty()" will think 992 * that it already _is_ on the dirty list. 993 */ 994 inode_state_assign_raw(inode, I_DIRTY); 995 inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR; 996 inode->i_uid = current_fsuid(); 997 inode->i_gid = current_fsgid(); 998 simple_inode_init_ts(inode); 999 1000 return inode; 1001 1002 fail_iput: 1003 iput(inode); 1004 1005 fail_inode: 1006 return NULL; 1007 } 1008 1009 int create_pipe_files(struct file **res, int flags) 1010 { 1011 struct inode *inode = get_pipe_inode(); 1012 struct file *f; 1013 int error; 1014 1015 if (!inode) 1016 return -ENFILE; 1017 1018 if (flags & O_NOTIFICATION_PIPE) { 1019 error = watch_queue_init(inode->i_pipe); 1020 if (error) { 1021 free_pipe_info(inode->i_pipe); 1022 iput(inode); 1023 return error; 1024 } 1025 } 1026 1027 f = alloc_file_pseudo(inode, pipe_mnt, "", 1028 O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)), 1029 &pipeanon_fops); 1030 if (IS_ERR(f)) { 1031 free_pipe_info(inode->i_pipe); 1032 iput(inode); 1033 return PTR_ERR(f); 1034 } 1035 1036 f->private_data = inode->i_pipe; 1037 f->f_pipe = 0; 1038 1039 res[0] = alloc_file_clone(f, O_RDONLY | (flags & O_NONBLOCK), 1040 &pipeanon_fops); 1041 if (IS_ERR(res[0])) { 1042 put_pipe_info(inode, inode->i_pipe); 1043 fput(f); 1044 return PTR_ERR(res[0]); 1045 } 1046 res[0]->private_data = inode->i_pipe; 1047 res[0]->f_pipe = 0; 1048 res[1] = f; 1049 stream_open(inode, res[0]); 1050 stream_open(inode, res[1]); 1051 1052 /* pipe groks IOCB_NOWAIT */ 1053 res[0]->f_mode |= FMODE_NOWAIT; 1054 res[1]->f_mode |= FMODE_NOWAIT; 1055 1056 /* 1057 * Disable permission and pre-content events, but enable legacy 1058 * inotify events for legacy users. 1059 */ 1060 file_set_fsnotify_mode(res[0], FMODE_NONOTIFY_PERM); 1061 file_set_fsnotify_mode(res[1], FMODE_NONOTIFY_PERM); 1062 return 0; 1063 } 1064 1065 static int __do_pipe_flags(int *fd, struct file **files, int flags) 1066 { 1067 int error; 1068 int fdw, fdr; 1069 1070 if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT | O_NOTIFICATION_PIPE)) 1071 return -EINVAL; 1072 1073 error = create_pipe_files(files, flags); 1074 if (error) 1075 return error; 1076 1077 error = get_unused_fd_flags(flags); 1078 if (error < 0) 1079 goto err_read_pipe; 1080 fdr = error; 1081 1082 error = get_unused_fd_flags(flags); 1083 if (error < 0) 1084 goto err_fdr; 1085 fdw = error; 1086 1087 audit_fd_pair(fdr, fdw); 1088 fd[0] = fdr; 1089 fd[1] = fdw; 1090 return 0; 1091 1092 err_fdr: 1093 put_unused_fd(fdr); 1094 err_read_pipe: 1095 fput(files[0]); 1096 fput(files[1]); 1097 return error; 1098 } 1099 1100 int do_pipe_flags(int *fd, int flags) 1101 { 1102 struct file *files[2]; 1103 int error = __do_pipe_flags(fd, files, flags); 1104 if (!error) { 1105 fd_install(fd[0], files[0]); 1106 fd_install(fd[1], files[1]); 1107 } 1108 return error; 1109 } 1110 1111 /* 1112 * sys_pipe() is the normal C calling standard for creating 1113 * a pipe. It's not the way Unix traditionally does this, though. 1114 */ 1115 static int do_pipe2(int __user *fildes, int flags) 1116 { 1117 struct file *files[2]; 1118 int fd[2]; 1119 int error; 1120 1121 error = __do_pipe_flags(fd, files, flags); 1122 if (!error) { 1123 if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) { 1124 fput(files[0]); 1125 fput(files[1]); 1126 put_unused_fd(fd[0]); 1127 put_unused_fd(fd[1]); 1128 error = -EFAULT; 1129 } else { 1130 fd_install(fd[0], files[0]); 1131 fd_install(fd[1], files[1]); 1132 } 1133 } 1134 return error; 1135 } 1136 1137 SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags) 1138 { 1139 return do_pipe2(fildes, flags); 1140 } 1141 1142 SYSCALL_DEFINE1(pipe, int __user *, fildes) 1143 { 1144 return do_pipe2(fildes, 0); 1145 } 1146 1147 /* 1148 * This is the stupid "wait for pipe to be readable or writable" 1149 * model. 1150 * 1151 * See pipe_read/write() for the proper kind of exclusive wait, 1152 * but that requires that we wake up any other readers/writers 1153 * if we then do not end up reading everything (ie the whole 1154 * "wake_next_reader/writer" logic in pipe_read/write()). 1155 */ 1156 void pipe_wait_readable(struct pipe_inode_info *pipe) 1157 { 1158 pipe_unlock(pipe); 1159 wait_event_interruptible(pipe->rd_wait, pipe_readable(pipe)); 1160 pipe_lock(pipe); 1161 } 1162 1163 void pipe_wait_writable(struct pipe_inode_info *pipe) 1164 { 1165 pipe_unlock(pipe); 1166 wait_event_interruptible(pipe->wr_wait, pipe_writable(pipe)); 1167 pipe_lock(pipe); 1168 } 1169 1170 /* 1171 * This depends on both the wait (here) and the wakeup (wake_up_partner) 1172 * holding the pipe lock, so "*cnt" is stable and we know a wakeup cannot 1173 * race with the count check and waitqueue prep. 1174 * 1175 * Normally in order to avoid races, you'd do the prepare_to_wait() first, 1176 * then check the condition you're waiting for, and only then sleep. But 1177 * because of the pipe lock, we can check the condition before being on 1178 * the wait queue. 1179 * 1180 * We use the 'rd_wait' waitqueue for pipe partner waiting. 1181 */ 1182 static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt) 1183 { 1184 DEFINE_WAIT(rdwait); 1185 int cur = *cnt; 1186 1187 while (cur == *cnt) { 1188 prepare_to_wait(&pipe->rd_wait, &rdwait, TASK_INTERRUPTIBLE); 1189 pipe_unlock(pipe); 1190 schedule(); 1191 finish_wait(&pipe->rd_wait, &rdwait); 1192 pipe_lock(pipe); 1193 if (signal_pending(current)) 1194 break; 1195 } 1196 return cur == *cnt ? -ERESTARTSYS : 0; 1197 } 1198 1199 static void wake_up_partner(struct pipe_inode_info *pipe) 1200 { 1201 wake_up_interruptible_all(&pipe->rd_wait); 1202 } 1203 1204 static int fifo_open(struct inode *inode, struct file *filp) 1205 { 1206 bool is_pipe = inode->i_fop == &pipeanon_fops; 1207 struct pipe_inode_info *pipe; 1208 int ret; 1209 1210 filp->f_pipe = 0; 1211 1212 spin_lock(&inode->i_lock); 1213 if (inode->i_pipe) { 1214 pipe = inode->i_pipe; 1215 pipe->files++; 1216 spin_unlock(&inode->i_lock); 1217 } else { 1218 spin_unlock(&inode->i_lock); 1219 pipe = alloc_pipe_info(); 1220 if (!pipe) 1221 return -ENOMEM; 1222 pipe->files = 1; 1223 spin_lock(&inode->i_lock); 1224 if (unlikely(inode->i_pipe)) { 1225 inode->i_pipe->files++; 1226 spin_unlock(&inode->i_lock); 1227 free_pipe_info(pipe); 1228 pipe = inode->i_pipe; 1229 } else { 1230 inode->i_pipe = pipe; 1231 spin_unlock(&inode->i_lock); 1232 } 1233 } 1234 filp->private_data = pipe; 1235 /* OK, we have a pipe and it's pinned down */ 1236 1237 mutex_lock(&pipe->mutex); 1238 1239 /* We can only do regular read/write on fifos */ 1240 stream_open(inode, filp); 1241 1242 switch (filp->f_mode & (FMODE_READ | FMODE_WRITE)) { 1243 case FMODE_READ: 1244 /* 1245 * O_RDONLY 1246 * POSIX.1 says that O_NONBLOCK means return with the FIFO 1247 * opened, even when there is no process writing the FIFO. 1248 */ 1249 pipe->r_counter++; 1250 if (pipe->readers++ == 0) 1251 wake_up_partner(pipe); 1252 1253 if (!is_pipe && !pipe->writers) { 1254 if ((filp->f_flags & O_NONBLOCK)) { 1255 /* suppress EPOLLHUP until we have 1256 * seen a writer */ 1257 filp->f_pipe = pipe->w_counter; 1258 } else { 1259 if (wait_for_partner(pipe, &pipe->w_counter)) 1260 goto err_rd; 1261 } 1262 } 1263 break; 1264 1265 case FMODE_WRITE: 1266 /* 1267 * O_WRONLY 1268 * POSIX.1 says that O_NONBLOCK means return -1 with 1269 * errno=ENXIO when there is no process reading the FIFO. 1270 */ 1271 ret = -ENXIO; 1272 if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers) 1273 goto err; 1274 1275 pipe->w_counter++; 1276 if (!pipe->writers++) 1277 wake_up_partner(pipe); 1278 1279 if (!is_pipe && !pipe->readers) { 1280 if (wait_for_partner(pipe, &pipe->r_counter)) 1281 goto err_wr; 1282 } 1283 break; 1284 1285 case FMODE_READ | FMODE_WRITE: 1286 /* 1287 * O_RDWR 1288 * POSIX.1 leaves this case "undefined" when O_NONBLOCK is set. 1289 * This implementation will NEVER block on a O_RDWR open, since 1290 * the process can at least talk to itself. 1291 */ 1292 1293 pipe->readers++; 1294 pipe->writers++; 1295 pipe->r_counter++; 1296 pipe->w_counter++; 1297 if (pipe->readers == 1 || pipe->writers == 1) 1298 wake_up_partner(pipe); 1299 break; 1300 1301 default: 1302 ret = -EINVAL; 1303 goto err; 1304 } 1305 1306 /* Ok! */ 1307 mutex_unlock(&pipe->mutex); 1308 return 0; 1309 1310 err_rd: 1311 if (!--pipe->readers) 1312 wake_up_interruptible(&pipe->wr_wait); 1313 ret = -ERESTARTSYS; 1314 goto err; 1315 1316 err_wr: 1317 if (!--pipe->writers) 1318 wake_up_interruptible_all(&pipe->rd_wait); 1319 ret = -ERESTARTSYS; 1320 goto err; 1321 1322 err: 1323 mutex_unlock(&pipe->mutex); 1324 1325 put_pipe_info(inode, pipe); 1326 return ret; 1327 } 1328 1329 const struct file_operations pipefifo_fops = { 1330 .open = fifo_open, 1331 .read_iter = fifo_pipe_read, 1332 .write_iter = fifo_pipe_write, 1333 .poll = pipe_poll, 1334 .unlocked_ioctl = pipe_ioctl, 1335 .release = pipe_release, 1336 .fasync = pipe_fasync, 1337 .splice_write = iter_file_splice_write, 1338 }; 1339 1340 static const struct file_operations pipeanon_fops = { 1341 .open = fifo_open, 1342 .read_iter = anon_pipe_read, 1343 .write_iter = anon_pipe_write, 1344 .poll = pipe_poll, 1345 .unlocked_ioctl = pipe_ioctl, 1346 .release = pipe_release, 1347 .fasync = pipe_fasync, 1348 .splice_write = iter_file_splice_write, 1349 }; 1350 1351 /* 1352 * Currently we rely on the pipe array holding a power-of-2 number 1353 * of pages. Returns 0 on error. 1354 */ 1355 unsigned int round_pipe_size(unsigned int size) 1356 { 1357 if (size > (1U << 31)) 1358 return 0; 1359 1360 /* Minimum pipe size, as required by POSIX */ 1361 if (size < PAGE_SIZE) 1362 return PAGE_SIZE; 1363 1364 return roundup_pow_of_two(size); 1365 } 1366 1367 /* 1368 * Resize the pipe ring to a number of slots. 1369 * 1370 * Note the pipe can be reduced in capacity, but only if the current 1371 * occupancy doesn't exceed nr_slots; if it does, EBUSY will be 1372 * returned instead. 1373 */ 1374 int pipe_resize_ring(struct pipe_inode_info *pipe, unsigned int nr_slots) 1375 { 1376 struct pipe_buffer *bufs; 1377 unsigned int head, tail, mask, n; 1378 1379 /* nr_slots larger than limits of pipe->{head,tail} */ 1380 if (unlikely(nr_slots > (pipe_index_t)-1u)) 1381 return -EINVAL; 1382 1383 bufs = kzalloc_objs(*bufs, nr_slots, GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 1384 if (unlikely(!bufs)) 1385 return -ENOMEM; 1386 1387 spin_lock_irq(&pipe->rd_wait.lock); 1388 mask = pipe->ring_size - 1; 1389 head = pipe->head; 1390 tail = pipe->tail; 1391 1392 n = pipe_occupancy(head, tail); 1393 if (nr_slots < n) { 1394 spin_unlock_irq(&pipe->rd_wait.lock); 1395 kfree(bufs); 1396 return -EBUSY; 1397 } 1398 1399 /* 1400 * The pipe array wraps around, so just start the new one at zero 1401 * and adjust the indices. 1402 */ 1403 if (n > 0) { 1404 unsigned int h = head & mask; 1405 unsigned int t = tail & mask; 1406 if (h > t) { 1407 memcpy(bufs, pipe->bufs + t, 1408 n * sizeof(struct pipe_buffer)); 1409 } else { 1410 unsigned int tsize = pipe->ring_size - t; 1411 if (h > 0) 1412 memcpy(bufs + tsize, pipe->bufs, 1413 h * sizeof(struct pipe_buffer)); 1414 memcpy(bufs, pipe->bufs + t, 1415 tsize * sizeof(struct pipe_buffer)); 1416 } 1417 } 1418 1419 head = n; 1420 tail = 0; 1421 1422 kfree(pipe->bufs); 1423 pipe->bufs = bufs; 1424 pipe->ring_size = nr_slots; 1425 if (pipe->max_usage > nr_slots) 1426 pipe->max_usage = nr_slots; 1427 pipe->tail = tail; 1428 pipe->head = head; 1429 1430 if (!pipe_has_watch_queue(pipe)) { 1431 pipe->max_usage = nr_slots; 1432 pipe->nr_accounted = nr_slots; 1433 } 1434 1435 spin_unlock_irq(&pipe->rd_wait.lock); 1436 1437 /* This might have made more room for writers */ 1438 wake_up_interruptible(&pipe->wr_wait); 1439 return 0; 1440 } 1441 1442 /* 1443 * Allocate a new array of pipe buffers and copy the info over. Returns the 1444 * pipe size if successful, or return -ERROR on error. 1445 */ 1446 static long pipe_set_size(struct pipe_inode_info *pipe, unsigned int arg) 1447 { 1448 unsigned long user_bufs; 1449 unsigned int nr_slots, size; 1450 long ret = 0; 1451 1452 if (pipe_has_watch_queue(pipe)) 1453 return -EBUSY; 1454 1455 size = round_pipe_size(arg); 1456 nr_slots = size >> PAGE_SHIFT; 1457 1458 if (!nr_slots) 1459 return -EINVAL; 1460 1461 /* 1462 * If trying to increase the pipe capacity, check that an 1463 * unprivileged user is not trying to exceed various limits 1464 * (soft limit check here, hard limit check just below). 1465 * Decreasing the pipe capacity is always permitted, even 1466 * if the user is currently over a limit. 1467 */ 1468 if (nr_slots > pipe->max_usage && 1469 size > pipe_max_size && !capable(CAP_SYS_RESOURCE)) 1470 return -EPERM; 1471 1472 user_bufs = account_pipe_buffers(pipe->user, pipe->nr_accounted, nr_slots); 1473 1474 if (nr_slots > pipe->max_usage && 1475 (too_many_pipe_buffers_hard(user_bufs) || 1476 too_many_pipe_buffers_soft(user_bufs)) && 1477 pipe_is_unprivileged_user()) { 1478 ret = -EPERM; 1479 goto out_revert_acct; 1480 } 1481 1482 ret = pipe_resize_ring(pipe, nr_slots); 1483 if (ret < 0) 1484 goto out_revert_acct; 1485 1486 return pipe->max_usage * PAGE_SIZE; 1487 1488 out_revert_acct: 1489 (void) account_pipe_buffers(pipe->user, nr_slots, pipe->nr_accounted); 1490 return ret; 1491 } 1492 1493 /* 1494 * Note that i_pipe and i_cdev share the same location, so checking ->i_pipe is 1495 * not enough to verify that this is a pipe. 1496 */ 1497 struct pipe_inode_info *get_pipe_info(struct file *file, bool for_splice) 1498 { 1499 struct pipe_inode_info *pipe = file->private_data; 1500 1501 if (!pipe) 1502 return NULL; 1503 if (file->f_op != &pipefifo_fops && file->f_op != &pipeanon_fops) 1504 return NULL; 1505 if (for_splice && pipe_has_watch_queue(pipe)) 1506 return NULL; 1507 return pipe; 1508 } 1509 1510 long pipe_fcntl(struct file *file, unsigned int cmd, unsigned int arg) 1511 { 1512 struct pipe_inode_info *pipe; 1513 long ret; 1514 1515 pipe = get_pipe_info(file, false); 1516 if (!pipe) 1517 return -EBADF; 1518 1519 mutex_lock(&pipe->mutex); 1520 1521 switch (cmd) { 1522 case F_SETPIPE_SZ: 1523 ret = pipe_set_size(pipe, arg); 1524 break; 1525 case F_GETPIPE_SZ: 1526 ret = pipe->max_usage * PAGE_SIZE; 1527 break; 1528 default: 1529 ret = -EINVAL; 1530 break; 1531 } 1532 1533 mutex_unlock(&pipe->mutex); 1534 return ret; 1535 } 1536 1537 static const struct super_operations pipefs_ops = { 1538 .destroy_inode = free_inode_nonrcu, 1539 .statfs = simple_statfs, 1540 }; 1541 1542 /* 1543 * pipefs should _never_ be mounted by userland - too much of security hassle, 1544 * no real gain from having the whole file system mounted. So we don't need 1545 * any operations on the root directory. However, we need a non-trivial 1546 * d_name - pipe: will go nicely and kill the special-casing in procfs. 1547 */ 1548 1549 static int pipefs_init_fs_context(struct fs_context *fc) 1550 { 1551 struct pseudo_fs_context *ctx = init_pseudo(fc, PIPEFS_MAGIC); 1552 if (!ctx) 1553 return -ENOMEM; 1554 ctx->ops = &pipefs_ops; 1555 ctx->dops = &pipefs_dentry_operations; 1556 return 0; 1557 } 1558 1559 static struct file_system_type pipe_fs_type = { 1560 .name = "pipefs", 1561 .init_fs_context = pipefs_init_fs_context, 1562 .kill_sb = kill_anon_super, 1563 }; 1564 1565 #ifdef CONFIG_SYSCTL 1566 1567 static ulong round_pipe_size_ul(ulong size) 1568 { 1569 return round_pipe_size(size); 1570 } 1571 1572 static int u2k_pipe_maxsz(const ulong *u_ptr, uint *k_ptr) 1573 { 1574 return proc_uint_u2k_conv_uop(u_ptr, k_ptr, round_pipe_size_ul); 1575 } 1576 1577 static int do_proc_uint_conv_pipe_maxsz(bool *negp, ulong *u_ptr, uint *k_ptr, 1578 int dir, const struct ctl_table *table) 1579 { 1580 return proc_uint_conv(u_ptr, k_ptr, dir, table, true, 1581 u2k_pipe_maxsz, 1582 proc_uint_k2u_conv); 1583 } 1584 1585 static int proc_dopipe_max_size(const struct ctl_table *table, int write, 1586 void *buffer, size_t *lenp, loff_t *ppos) 1587 { 1588 return proc_douintvec_conv(table, write, buffer, lenp, ppos, 1589 do_proc_uint_conv_pipe_maxsz); 1590 } 1591 1592 static const struct ctl_table fs_pipe_sysctls[] = { 1593 { 1594 .procname = "pipe-max-size", 1595 .data = &pipe_max_size, 1596 .maxlen = sizeof(pipe_max_size), 1597 .mode = 0644, 1598 .proc_handler = proc_dopipe_max_size, 1599 .extra1 = SYSCTL_ONE, 1600 }, 1601 { 1602 .procname = "pipe-user-pages-hard", 1603 .data = &pipe_user_pages_hard, 1604 .maxlen = sizeof(pipe_user_pages_hard), 1605 .mode = 0644, 1606 .proc_handler = proc_doulongvec_minmax, 1607 }, 1608 { 1609 .procname = "pipe-user-pages-soft", 1610 .data = &pipe_user_pages_soft, 1611 .maxlen = sizeof(pipe_user_pages_soft), 1612 .mode = 0644, 1613 .proc_handler = proc_doulongvec_minmax, 1614 }, 1615 }; 1616 #endif 1617 1618 static int __init init_pipe_fs(void) 1619 { 1620 int err = register_filesystem(&pipe_fs_type); 1621 1622 if (!err) { 1623 pipe_mnt = kern_mount(&pipe_fs_type); 1624 if (IS_ERR(pipe_mnt)) { 1625 err = PTR_ERR(pipe_mnt); 1626 unregister_filesystem(&pipe_fs_type); 1627 } 1628 } 1629 #ifdef CONFIG_SYSCTL 1630 register_sysctl_init("fs", fs_pipe_sysctls); 1631 #endif 1632 return err; 1633 } 1634 1635 fs_initcall(init_pipe_fs); 1636