1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 1991, 1992, 1999 Linus Torvalds
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>
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>
31 #include <linux/uaccess.h>
32 #include <asm/ioctls.h>
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/.
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
49 #define PIPE_MIN_DEF_BUFFERS 2
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
55 static unsigned int pipe_max_size = 1048576;
57 /* Maximum allocatable pages per user. Hard limit is unset by default, soft
58 * matches default values.
60 static unsigned long pipe_user_pages_hard;
61 static unsigned long pipe_user_pages_soft = PIPE_DEF_BUFFERS * INR_OPEN_CUR;
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
68 * -- David Howells 2019-09-23.
70 * Reads with count = 0 should always return 0.
71 * -- Julian Bradfield 1999-06-07.
73 * FIFOs and Pipes now generate SIGIO for both readers and writers.
74 * -- Jeremy Elson <jelson@circlemud.org> 2001-08-16
76 * pipe_read & write cleanup
77 * -- Manfred Spraul <manfred@colorfullife.com> 2002-05-09
80 #ifdef CONFIG_PROVE_LOCKING
81 static int pipe_lock_cmp_fn(const struct lockdep_map *a,
82 const struct lockdep_map *b)
84 return cmp_int((unsigned long) a, (unsigned long) b);
88 void pipe_lock(struct pipe_inode_info *pipe)
91 mutex_lock(&pipe->mutex);
93 EXPORT_SYMBOL(pipe_lock);
95 void pipe_unlock(struct pipe_inode_info *pipe)
98 mutex_unlock(&pipe->mutex);
100 EXPORT_SYMBOL(pipe_unlock);
102 void pipe_double_lock(struct pipe_inode_info *pipe1,
103 struct pipe_inode_info *pipe2)
105 BUG_ON(pipe1 == pipe2);
114 static struct page *anon_pipe_get_page(struct pipe_inode_info *pipe)
116 for (int i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {
117 if (pipe->tmp_page[i]) {
118 struct page *page = pipe->tmp_page[i];
119 pipe->tmp_page[i] = NULL;
124 return alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT);
127 static void anon_pipe_put_page(struct pipe_inode_info *pipe,
130 if (page_count(page) == 1) {
131 for (int i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {
132 if (!pipe->tmp_page[i]) {
133 pipe->tmp_page[i] = page;
142 static void anon_pipe_buf_release(struct pipe_inode_info *pipe,
143 struct pipe_buffer *buf)
145 struct page *page = buf->page;
147 anon_pipe_put_page(pipe, page);
150 static bool anon_pipe_buf_try_steal(struct pipe_inode_info *pipe,
151 struct pipe_buffer *buf)
153 struct page *page = buf->page;
155 if (page_count(page) != 1)
157 memcg_kmem_uncharge_page(page, 0);
158 __SetPageLocked(page);
163 * generic_pipe_buf_try_steal - attempt to take ownership of a &pipe_buffer
164 * @pipe: the pipe that the buffer belongs to
165 * @buf: the buffer to attempt to steal
168 * This function attempts to steal the &struct page attached to
169 * @buf. If successful, this function returns 0 and returns with
170 * the page locked. The caller may then reuse the page for whatever
171 * he wishes; the typical use is insertion into a different file
174 bool generic_pipe_buf_try_steal(struct pipe_inode_info *pipe,
175 struct pipe_buffer *buf)
177 struct page *page = buf->page;
180 * A reference of one is golden, that means that the owner of this
181 * page is the only one holding a reference to it. lock the page
184 if (page_count(page) == 1) {
190 EXPORT_SYMBOL(generic_pipe_buf_try_steal);
193 * generic_pipe_buf_get - get a reference to a &struct pipe_buffer
194 * @pipe: the pipe that the buffer belongs to
195 * @buf: the buffer to get a reference to
198 * This function grabs an extra reference to @buf. It's used in
199 * the tee() system call, when we duplicate the buffers in one
202 bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
204 return try_get_page(buf->page);
206 EXPORT_SYMBOL(generic_pipe_buf_get);
209 * generic_pipe_buf_release - put a reference to a &struct pipe_buffer
210 * @pipe: the pipe that the buffer belongs to
211 * @buf: the buffer to put a reference to
214 * This function releases a reference to @buf.
216 void generic_pipe_buf_release(struct pipe_inode_info *pipe,
217 struct pipe_buffer *buf)
221 EXPORT_SYMBOL(generic_pipe_buf_release);
223 static const struct pipe_buf_operations anon_pipe_buf_ops = {
224 .release = anon_pipe_buf_release,
225 .try_steal = anon_pipe_buf_try_steal,
226 .get = generic_pipe_buf_get,
229 /* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
230 static inline bool pipe_readable(const struct pipe_inode_info *pipe)
232 union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };
233 unsigned int writers = READ_ONCE(pipe->writers);
235 return !pipe_empty(idx.head, idx.tail) || !writers;
238 static inline unsigned int pipe_update_tail(struct pipe_inode_info *pipe,
239 struct pipe_buffer *buf,
242 pipe_buf_release(pipe, buf);
245 * If the pipe has a watch_queue, we need additional protection
246 * by the spinlock because notifications get posted with only
247 * this spinlock, no mutex
249 if (pipe_has_watch_queue(pipe)) {
250 spin_lock_irq(&pipe->rd_wait.lock);
251 #ifdef CONFIG_WATCH_QUEUE
252 if (buf->flags & PIPE_BUF_FLAG_LOSS)
253 pipe->note_loss = true;
256 spin_unlock_irq(&pipe->rd_wait.lock);
261 * Without a watch_queue, we can simply increment the tail
262 * without the spinlock - the mutex is enough.
269 anon_pipe_read(struct kiocb *iocb, struct iov_iter *to)
271 size_t total_len = iov_iter_count(to);
272 struct file *filp = iocb->ki_filp;
273 struct pipe_inode_info *pipe = filp->private_data;
274 bool wake_writer = false, wake_next_reader = false;
277 /* Null read succeeds. */
278 if (unlikely(total_len == 0))
282 mutex_lock(&pipe->mutex);
285 * We only wake up writers if the pipe was full when we started reading
286 * and it is no longer full after reading to avoid unnecessary wakeups.
288 * But when we do wake up writers, we do so using a sync wakeup
289 * (WF_SYNC), because we want them to get going and generate more
293 /* Read ->head with a barrier vs post_one_notification() */
294 unsigned int head = smp_load_acquire(&pipe->head);
295 unsigned int tail = pipe->tail;
297 #ifdef CONFIG_WATCH_QUEUE
298 if (pipe->note_loss) {
299 struct watch_notification n;
307 n.type = WATCH_TYPE_META;
308 n.subtype = WATCH_META_LOSS_NOTIFICATION;
309 n.info = watch_sizeof(n);
310 if (copy_to_iter(&n, sizeof(n), to) != sizeof(n)) {
316 total_len -= sizeof(n);
317 pipe->note_loss = false;
321 if (!pipe_empty(head, tail)) {
322 struct pipe_buffer *buf = pipe_buf(pipe, tail);
323 size_t chars = buf->len;
327 if (chars > total_len) {
328 if (buf->flags & PIPE_BUF_FLAG_WHOLE) {
336 error = pipe_buf_confirm(pipe, buf);
343 written = copy_page_to_iter(buf->page, buf->offset, chars, to);
344 if (unlikely(written < chars)) {
350 buf->offset += chars;
353 /* Was it a packet buffer? Clean up and exit */
354 if (buf->flags & PIPE_BUF_FLAG_PACKET) {
360 wake_writer |= pipe_full(head, tail, pipe->max_usage);
361 tail = pipe_update_tail(pipe, buf, tail);
365 break; /* common path: read succeeded */
366 if (!pipe_empty(head, tail)) /* More to do? */
374 if ((filp->f_flags & O_NONBLOCK) ||
375 (iocb->ki_flags & IOCB_NOWAIT)) {
379 mutex_unlock(&pipe->mutex);
381 * We only get here if we didn't actually read anything.
383 * But because we didn't read anything, at this point we can
384 * just return directly with -ERESTARTSYS if we're interrupted,
385 * since we've done any required wakeups and there's no need
386 * to mark anything accessed. And we've dropped the lock.
388 if (wait_event_interruptible_exclusive(pipe->rd_wait, pipe_readable(pipe)) < 0)
391 wake_next_reader = true;
392 mutex_lock(&pipe->mutex);
394 if (pipe_is_empty(pipe))
395 wake_next_reader = false;
396 mutex_unlock(&pipe->mutex);
399 wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM);
400 if (wake_next_reader)
401 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
402 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
407 fifo_pipe_read(struct kiocb *iocb, struct iov_iter *to)
409 int ret = anon_pipe_read(iocb, to);
411 file_accessed(iocb->ki_filp);
415 static inline int is_packetized(struct file *file)
417 return (file->f_flags & O_DIRECT) != 0;
420 /* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
421 static inline bool pipe_writable(const struct pipe_inode_info *pipe)
423 union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };
424 unsigned int max_usage = READ_ONCE(pipe->max_usage);
426 return !pipe_full(idx.head, idx.tail, max_usage) ||
427 !READ_ONCE(pipe->readers);
431 anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)
433 struct file *filp = iocb->ki_filp;
434 struct pipe_inode_info *pipe = filp->private_data;
437 size_t total_len = iov_iter_count(from);
439 bool was_empty = false;
440 bool wake_next_writer = false;
443 * Reject writing to watch queue pipes before the point where we lock
445 * Otherwise, lockdep would be unhappy if the caller already has another
447 * If we had to support locking a normal pipe and a notification pipe at
448 * the same time, we could set up lockdep annotations for that, but
449 * since we don't actually need that, it's simpler to just bail here.
451 if (pipe_has_watch_queue(pipe))
454 /* Null write succeeds. */
455 if (unlikely(total_len == 0))
458 mutex_lock(&pipe->mutex);
460 if (!pipe->readers) {
461 send_sig(SIGPIPE, current, 0);
467 * If it wasn't empty we try to merge new data into
470 * That naturally merges small writes, but it also
471 * page-aligns the rest of the writes for large writes
472 * spanning multiple pages.
475 was_empty = pipe_empty(head, pipe->tail);
476 chars = total_len & (PAGE_SIZE-1);
477 if (chars && !was_empty) {
478 struct pipe_buffer *buf = pipe_buf(pipe, head - 1);
479 int offset = buf->offset + buf->len;
481 if ((buf->flags & PIPE_BUF_FLAG_CAN_MERGE) &&
482 offset + chars <= PAGE_SIZE) {
483 ret = pipe_buf_confirm(pipe, buf);
487 ret = copy_page_from_iter(buf->page, offset, chars, from);
488 if (unlikely(ret < chars)) {
494 if (!iov_iter_count(from))
500 if (!pipe->readers) {
501 send_sig(SIGPIPE, current, 0);
508 if (!pipe_full(head, pipe->tail, pipe->max_usage)) {
509 struct pipe_buffer *buf;
513 page = anon_pipe_get_page(pipe);
514 if (unlikely(!page)) {
520 copied = copy_page_from_iter(page, 0, PAGE_SIZE, from);
521 if (unlikely(copied < PAGE_SIZE && iov_iter_count(from))) {
522 anon_pipe_put_page(pipe, page);
528 pipe->head = head + 1;
529 /* Insert it into the buffer array */
530 buf = pipe_buf(pipe, head);
532 buf->ops = &anon_pipe_buf_ops;
534 if (is_packetized(filp))
535 buf->flags = PIPE_BUF_FLAG_PACKET;
537 buf->flags = PIPE_BUF_FLAG_CAN_MERGE;
542 if (!iov_iter_count(from))
548 /* Wait for buffer space to become available. */
549 if ((filp->f_flags & O_NONBLOCK) ||
550 (iocb->ki_flags & IOCB_NOWAIT)) {
555 if (signal_pending(current)) {
562 * We're going to release the pipe lock and wait for more
563 * space. We wake up any readers if necessary, and then
564 * after waiting we need to re-check whether the pipe
565 * become empty while we dropped the lock.
567 mutex_unlock(&pipe->mutex);
569 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
570 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
571 wait_event_interruptible_exclusive(pipe->wr_wait, pipe_writable(pipe));
572 mutex_lock(&pipe->mutex);
573 was_empty = pipe_is_empty(pipe);
574 wake_next_writer = true;
577 if (pipe_is_full(pipe))
578 wake_next_writer = false;
579 mutex_unlock(&pipe->mutex);
582 * If we do do a wakeup event, we do a 'sync' wakeup, because we
583 * want the reader to start processing things asap, rather than
584 * leave the data pending.
586 * This is particularly important for small writes, because of
587 * how (for example) the GNU make jobserver uses small writes to
588 * wake up pending jobs
590 * Epoll nonsensically wants a wakeup whether the pipe
591 * was already empty or not.
593 if (was_empty || pipe->poll_usage)
594 wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
595 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
596 if (wake_next_writer)
597 wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM);
602 fifo_pipe_write(struct kiocb *iocb, struct iov_iter *from)
604 int ret = anon_pipe_write(iocb, from);
606 struct file *filp = iocb->ki_filp;
607 if (sb_start_write_trylock(file_inode(filp)->i_sb)) {
608 int err = file_update_time(filp);
611 sb_end_write(file_inode(filp)->i_sb);
617 static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
619 struct pipe_inode_info *pipe = filp->private_data;
620 unsigned int count, head, tail;
624 mutex_lock(&pipe->mutex);
629 while (!pipe_empty(head, tail)) {
630 count += pipe_buf(pipe, tail)->len;
633 mutex_unlock(&pipe->mutex);
635 return put_user(count, (int __user *)arg);
637 #ifdef CONFIG_WATCH_QUEUE
638 case IOC_WATCH_QUEUE_SET_SIZE: {
640 mutex_lock(&pipe->mutex);
641 ret = watch_queue_set_size(pipe, arg);
642 mutex_unlock(&pipe->mutex);
646 case IOC_WATCH_QUEUE_SET_FILTER:
647 return watch_queue_set_filter(
648 pipe, (struct watch_notification_filter __user *)arg);
656 /* No kernel lock held - fine */
658 pipe_poll(struct file *filp, poll_table *wait)
661 struct pipe_inode_info *pipe = filp->private_data;
662 union pipe_index idx;
664 /* Epoll has some historical nasty semantics, this enables them */
665 WRITE_ONCE(pipe->poll_usage, true);
668 * Reading pipe state only -- no need for acquiring the semaphore.
670 * But because this is racy, the code has to add the
671 * entry to the poll table _first_ ..
673 if (filp->f_mode & FMODE_READ)
674 poll_wait(filp, &pipe->rd_wait, wait);
675 if (filp->f_mode & FMODE_WRITE)
676 poll_wait(filp, &pipe->wr_wait, wait);
679 * .. and only then can you do the racy tests. That way,
680 * if something changes and you got it wrong, the poll
681 * table entry will wake you up and fix it.
683 idx.head_tail = READ_ONCE(pipe->head_tail);
686 if (filp->f_mode & FMODE_READ) {
687 if (!pipe_empty(idx.head, idx.tail))
688 mask |= EPOLLIN | EPOLLRDNORM;
689 if (!pipe->writers && filp->f_pipe != pipe->w_counter)
693 if (filp->f_mode & FMODE_WRITE) {
694 if (!pipe_full(idx.head, idx.tail, pipe->max_usage))
695 mask |= EPOLLOUT | EPOLLWRNORM;
697 * Most Unices do not set EPOLLERR for FIFOs but on Linux they
698 * behave exactly like pipes for poll().
707 static void put_pipe_info(struct inode *inode, struct pipe_inode_info *pipe)
711 spin_lock(&inode->i_lock);
712 if (!--pipe->files) {
713 inode->i_pipe = NULL;
716 spin_unlock(&inode->i_lock);
719 free_pipe_info(pipe);
723 pipe_release(struct inode *inode, struct file *file)
725 struct pipe_inode_info *pipe = file->private_data;
727 mutex_lock(&pipe->mutex);
728 if (file->f_mode & FMODE_READ)
730 if (file->f_mode & FMODE_WRITE)
733 /* Was that the last reader or writer, but not the other side? */
734 if (!pipe->readers != !pipe->writers) {
735 wake_up_interruptible_all(&pipe->rd_wait);
736 wake_up_interruptible_all(&pipe->wr_wait);
737 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
738 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
740 mutex_unlock(&pipe->mutex);
742 put_pipe_info(inode, pipe);
747 pipe_fasync(int fd, struct file *filp, int on)
749 struct pipe_inode_info *pipe = filp->private_data;
752 mutex_lock(&pipe->mutex);
753 if (filp->f_mode & FMODE_READ)
754 retval = fasync_helper(fd, filp, on, &pipe->fasync_readers);
755 if ((filp->f_mode & FMODE_WRITE) && retval >= 0) {
756 retval = fasync_helper(fd, filp, on, &pipe->fasync_writers);
757 if (retval < 0 && (filp->f_mode & FMODE_READ))
758 /* this can happen only if on == T */
759 fasync_helper(-1, filp, 0, &pipe->fasync_readers);
761 mutex_unlock(&pipe->mutex);
765 unsigned long account_pipe_buffers(struct user_struct *user,
766 unsigned long old, unsigned long new)
768 return atomic_long_add_return(new - old, &user->pipe_bufs);
771 bool too_many_pipe_buffers_soft(unsigned long user_bufs)
773 unsigned long soft_limit = READ_ONCE(pipe_user_pages_soft);
775 return soft_limit && user_bufs > soft_limit;
778 bool too_many_pipe_buffers_hard(unsigned long user_bufs)
780 unsigned long hard_limit = READ_ONCE(pipe_user_pages_hard);
782 return hard_limit && user_bufs > hard_limit;
785 bool pipe_is_unprivileged_user(void)
787 return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN);
790 struct pipe_inode_info *alloc_pipe_info(void)
792 struct pipe_inode_info *pipe;
793 unsigned long pipe_bufs = PIPE_DEF_BUFFERS;
794 struct user_struct *user = get_current_user();
795 unsigned long user_bufs;
796 unsigned int max_size = READ_ONCE(pipe_max_size);
798 pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL_ACCOUNT);
802 if (pipe_bufs * PAGE_SIZE > max_size && !capable(CAP_SYS_RESOURCE))
803 pipe_bufs = max_size >> PAGE_SHIFT;
805 user_bufs = account_pipe_buffers(user, 0, pipe_bufs);
807 if (too_many_pipe_buffers_soft(user_bufs) && pipe_is_unprivileged_user()) {
808 user_bufs = account_pipe_buffers(user, pipe_bufs, PIPE_MIN_DEF_BUFFERS);
809 pipe_bufs = PIPE_MIN_DEF_BUFFERS;
812 if (too_many_pipe_buffers_hard(user_bufs) && pipe_is_unprivileged_user())
813 goto out_revert_acct;
815 pipe->bufs = kcalloc(pipe_bufs, sizeof(struct pipe_buffer),
819 init_waitqueue_head(&pipe->rd_wait);
820 init_waitqueue_head(&pipe->wr_wait);
821 pipe->r_counter = pipe->w_counter = 1;
822 pipe->max_usage = pipe_bufs;
823 pipe->ring_size = pipe_bufs;
824 pipe->nr_accounted = pipe_bufs;
826 mutex_init(&pipe->mutex);
827 lock_set_cmp_fn(&pipe->mutex, pipe_lock_cmp_fn, NULL);
832 (void) account_pipe_buffers(user, pipe_bufs, 0);
839 void free_pipe_info(struct pipe_inode_info *pipe)
843 #ifdef CONFIG_WATCH_QUEUE
844 if (pipe->watch_queue)
845 watch_queue_clear(pipe->watch_queue);
848 (void) account_pipe_buffers(pipe->user, pipe->nr_accounted, 0);
849 free_uid(pipe->user);
850 for (i = 0; i < pipe->ring_size; i++) {
851 struct pipe_buffer *buf = pipe->bufs + i;
853 pipe_buf_release(pipe, buf);
855 #ifdef CONFIG_WATCH_QUEUE
856 if (pipe->watch_queue)
857 put_watch_queue(pipe->watch_queue);
859 for (i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {
860 if (pipe->tmp_page[i])
861 __free_page(pipe->tmp_page[i]);
867 static struct vfsmount *pipe_mnt __ro_after_init;
870 * pipefs_dname() is called from d_path().
872 static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen)
874 return dynamic_dname(buffer, buflen, "pipe:[%lu]",
875 d_inode(dentry)->i_ino);
878 static const struct dentry_operations pipefs_dentry_operations = {
879 .d_dname = pipefs_dname,
882 static const struct file_operations pipeanon_fops;
884 static struct inode * get_pipe_inode(void)
886 struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb);
887 struct pipe_inode_info *pipe;
892 inode->i_ino = get_next_ino();
894 pipe = alloc_pipe_info();
898 inode->i_pipe = pipe;
900 pipe->readers = pipe->writers = 1;
901 inode->i_fop = &pipeanon_fops;
904 * Mark the inode dirty from the very beginning,
905 * that way it will never be moved to the dirty
906 * list because "mark_inode_dirty()" will think
907 * that it already _is_ on the dirty list.
909 inode->i_state = I_DIRTY;
910 inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR;
911 inode->i_uid = current_fsuid();
912 inode->i_gid = current_fsgid();
913 simple_inode_init_ts(inode);
924 int create_pipe_files(struct file **res, int flags)
926 struct inode *inode = get_pipe_inode();
933 if (flags & O_NOTIFICATION_PIPE) {
934 error = watch_queue_init(inode->i_pipe);
936 free_pipe_info(inode->i_pipe);
942 f = alloc_file_pseudo(inode, pipe_mnt, "",
943 O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)),
946 free_pipe_info(inode->i_pipe);
951 f->private_data = inode->i_pipe;
954 res[0] = alloc_file_clone(f, O_RDONLY | (flags & O_NONBLOCK),
956 if (IS_ERR(res[0])) {
957 put_pipe_info(inode, inode->i_pipe);
959 return PTR_ERR(res[0]);
961 res[0]->private_data = inode->i_pipe;
964 stream_open(inode, res[0]);
965 stream_open(inode, res[1]);
967 /* pipe groks IOCB_NOWAIT */
968 res[0]->f_mode |= FMODE_NOWAIT;
969 res[1]->f_mode |= FMODE_NOWAIT;
972 * Disable permission and pre-content events, but enable legacy
973 * inotify events for legacy users.
975 file_set_fsnotify_mode(res[0], FMODE_NONOTIFY_PERM);
976 file_set_fsnotify_mode(res[1], FMODE_NONOTIFY_PERM);
980 static int __do_pipe_flags(int *fd, struct file **files, int flags)
985 if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT | O_NOTIFICATION_PIPE))
988 error = create_pipe_files(files, flags);
992 error = get_unused_fd_flags(flags);
997 error = get_unused_fd_flags(flags);
1002 audit_fd_pair(fdr, fdw);
1015 int do_pipe_flags(int *fd, int flags)
1017 struct file *files[2];
1018 int error = __do_pipe_flags(fd, files, flags);
1020 fd_install(fd[0], files[0]);
1021 fd_install(fd[1], files[1]);
1027 * sys_pipe() is the normal C calling standard for creating
1028 * a pipe. It's not the way Unix traditionally does this, though.
1030 static int do_pipe2(int __user *fildes, int flags)
1032 struct file *files[2];
1036 error = __do_pipe_flags(fd, files, flags);
1038 if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) {
1041 put_unused_fd(fd[0]);
1042 put_unused_fd(fd[1]);
1045 fd_install(fd[0], files[0]);
1046 fd_install(fd[1], files[1]);
1052 SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags)
1054 return do_pipe2(fildes, flags);
1057 SYSCALL_DEFINE1(pipe, int __user *, fildes)
1059 return do_pipe2(fildes, 0);
1063 * This is the stupid "wait for pipe to be readable or writable"
1066 * See pipe_read/write() for the proper kind of exclusive wait,
1067 * but that requires that we wake up any other readers/writers
1068 * if we then do not end up reading everything (ie the whole
1069 * "wake_next_reader/writer" logic in pipe_read/write()).
1071 void pipe_wait_readable(struct pipe_inode_info *pipe)
1074 wait_event_interruptible(pipe->rd_wait, pipe_readable(pipe));
1078 void pipe_wait_writable(struct pipe_inode_info *pipe)
1081 wait_event_interruptible(pipe->wr_wait, pipe_writable(pipe));
1086 * This depends on both the wait (here) and the wakeup (wake_up_partner)
1087 * holding the pipe lock, so "*cnt" is stable and we know a wakeup cannot
1088 * race with the count check and waitqueue prep.
1090 * Normally in order to avoid races, you'd do the prepare_to_wait() first,
1091 * then check the condition you're waiting for, and only then sleep. But
1092 * because of the pipe lock, we can check the condition before being on
1095 * We use the 'rd_wait' waitqueue for pipe partner waiting.
1097 static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt)
1099 DEFINE_WAIT(rdwait);
1102 while (cur == *cnt) {
1103 prepare_to_wait(&pipe->rd_wait, &rdwait, TASK_INTERRUPTIBLE);
1106 finish_wait(&pipe->rd_wait, &rdwait);
1108 if (signal_pending(current))
1111 return cur == *cnt ? -ERESTARTSYS : 0;
1114 static void wake_up_partner(struct pipe_inode_info *pipe)
1116 wake_up_interruptible_all(&pipe->rd_wait);
1119 static int fifo_open(struct inode *inode, struct file *filp)
1121 bool is_pipe = inode->i_fop == &pipeanon_fops;
1122 struct pipe_inode_info *pipe;
1127 spin_lock(&inode->i_lock);
1128 if (inode->i_pipe) {
1129 pipe = inode->i_pipe;
1131 spin_unlock(&inode->i_lock);
1133 spin_unlock(&inode->i_lock);
1134 pipe = alloc_pipe_info();
1138 spin_lock(&inode->i_lock);
1139 if (unlikely(inode->i_pipe)) {
1140 inode->i_pipe->files++;
1141 spin_unlock(&inode->i_lock);
1142 free_pipe_info(pipe);
1143 pipe = inode->i_pipe;
1145 inode->i_pipe = pipe;
1146 spin_unlock(&inode->i_lock);
1149 filp->private_data = pipe;
1150 /* OK, we have a pipe and it's pinned down */
1152 mutex_lock(&pipe->mutex);
1154 /* We can only do regular read/write on fifos */
1155 stream_open(inode, filp);
1157 switch (filp->f_mode & (FMODE_READ | FMODE_WRITE)) {
1161 * POSIX.1 says that O_NONBLOCK means return with the FIFO
1162 * opened, even when there is no process writing the FIFO.
1165 if (pipe->readers++ == 0)
1166 wake_up_partner(pipe);
1168 if (!is_pipe && !pipe->writers) {
1169 if ((filp->f_flags & O_NONBLOCK)) {
1170 /* suppress EPOLLHUP until we have
1172 filp->f_pipe = pipe->w_counter;
1174 if (wait_for_partner(pipe, &pipe->w_counter))
1183 * POSIX.1 says that O_NONBLOCK means return -1 with
1184 * errno=ENXIO when there is no process reading the FIFO.
1187 if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers)
1191 if (!pipe->writers++)
1192 wake_up_partner(pipe);
1194 if (!is_pipe && !pipe->readers) {
1195 if (wait_for_partner(pipe, &pipe->r_counter))
1200 case FMODE_READ | FMODE_WRITE:
1203 * POSIX.1 leaves this case "undefined" when O_NONBLOCK is set.
1204 * This implementation will NEVER block on a O_RDWR open, since
1205 * the process can at least talk to itself.
1212 if (pipe->readers == 1 || pipe->writers == 1)
1213 wake_up_partner(pipe);
1222 mutex_unlock(&pipe->mutex);
1226 if (!--pipe->readers)
1227 wake_up_interruptible(&pipe->wr_wait);
1232 if (!--pipe->writers)
1233 wake_up_interruptible_all(&pipe->rd_wait);
1238 mutex_unlock(&pipe->mutex);
1240 put_pipe_info(inode, pipe);
1244 const struct file_operations pipefifo_fops = {
1246 .read_iter = fifo_pipe_read,
1247 .write_iter = fifo_pipe_write,
1249 .unlocked_ioctl = pipe_ioctl,
1250 .release = pipe_release,
1251 .fasync = pipe_fasync,
1252 .splice_write = iter_file_splice_write,
1255 static const struct file_operations pipeanon_fops = {
1257 .read_iter = anon_pipe_read,
1258 .write_iter = anon_pipe_write,
1260 .unlocked_ioctl = pipe_ioctl,
1261 .release = pipe_release,
1262 .fasync = pipe_fasync,
1263 .splice_write = iter_file_splice_write,
1267 * Currently we rely on the pipe array holding a power-of-2 number
1268 * of pages. Returns 0 on error.
1270 unsigned int round_pipe_size(unsigned int size)
1272 if (size > (1U << 31))
1275 /* Minimum pipe size, as required by POSIX */
1276 if (size < PAGE_SIZE)
1279 return roundup_pow_of_two(size);
1283 * Resize the pipe ring to a number of slots.
1285 * Note the pipe can be reduced in capacity, but only if the current
1286 * occupancy doesn't exceed nr_slots; if it does, EBUSY will be
1289 int pipe_resize_ring(struct pipe_inode_info *pipe, unsigned int nr_slots)
1291 struct pipe_buffer *bufs;
1292 unsigned int head, tail, mask, n;
1294 /* nr_slots larger than limits of pipe->{head,tail} */
1295 if (unlikely(nr_slots > (pipe_index_t)-1u))
1298 bufs = kcalloc(nr_slots, sizeof(*bufs),
1299 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
1300 if (unlikely(!bufs))
1303 spin_lock_irq(&pipe->rd_wait.lock);
1304 mask = pipe->ring_size - 1;
1308 n = pipe_occupancy(head, tail);
1310 spin_unlock_irq(&pipe->rd_wait.lock);
1316 * The pipe array wraps around, so just start the new one at zero
1317 * and adjust the indices.
1320 unsigned int h = head & mask;
1321 unsigned int t = tail & mask;
1323 memcpy(bufs, pipe->bufs + t,
1324 n * sizeof(struct pipe_buffer));
1326 unsigned int tsize = pipe->ring_size - t;
1328 memcpy(bufs + tsize, pipe->bufs,
1329 h * sizeof(struct pipe_buffer));
1330 memcpy(bufs, pipe->bufs + t,
1331 tsize * sizeof(struct pipe_buffer));
1340 pipe->ring_size = nr_slots;
1341 if (pipe->max_usage > nr_slots)
1342 pipe->max_usage = nr_slots;
1346 if (!pipe_has_watch_queue(pipe)) {
1347 pipe->max_usage = nr_slots;
1348 pipe->nr_accounted = nr_slots;
1351 spin_unlock_irq(&pipe->rd_wait.lock);
1353 /* This might have made more room for writers */
1354 wake_up_interruptible(&pipe->wr_wait);
1359 * Allocate a new array of pipe buffers and copy the info over. Returns the
1360 * pipe size if successful, or return -ERROR on error.
1362 static long pipe_set_size(struct pipe_inode_info *pipe, unsigned int arg)
1364 unsigned long user_bufs;
1365 unsigned int nr_slots, size;
1368 if (pipe_has_watch_queue(pipe))
1371 size = round_pipe_size(arg);
1372 nr_slots = size >> PAGE_SHIFT;
1378 * If trying to increase the pipe capacity, check that an
1379 * unprivileged user is not trying to exceed various limits
1380 * (soft limit check here, hard limit check just below).
1381 * Decreasing the pipe capacity is always permitted, even
1382 * if the user is currently over a limit.
1384 if (nr_slots > pipe->max_usage &&
1385 size > pipe_max_size && !capable(CAP_SYS_RESOURCE))
1388 user_bufs = account_pipe_buffers(pipe->user, pipe->nr_accounted, nr_slots);
1390 if (nr_slots > pipe->max_usage &&
1391 (too_many_pipe_buffers_hard(user_bufs) ||
1392 too_many_pipe_buffers_soft(user_bufs)) &&
1393 pipe_is_unprivileged_user()) {
1395 goto out_revert_acct;
1398 ret = pipe_resize_ring(pipe, nr_slots);
1400 goto out_revert_acct;
1402 return pipe->max_usage * PAGE_SIZE;
1405 (void) account_pipe_buffers(pipe->user, nr_slots, pipe->nr_accounted);
1410 * Note that i_pipe and i_cdev share the same location, so checking ->i_pipe is
1411 * not enough to verify that this is a pipe.
1413 struct pipe_inode_info *get_pipe_info(struct file *file, bool for_splice)
1415 struct pipe_inode_info *pipe = file->private_data;
1419 if (file->f_op != &pipefifo_fops && file->f_op != &pipeanon_fops)
1421 if (for_splice && pipe_has_watch_queue(pipe))
1426 long pipe_fcntl(struct file *file, unsigned int cmd, unsigned int arg)
1428 struct pipe_inode_info *pipe;
1431 pipe = get_pipe_info(file, false);
1435 mutex_lock(&pipe->mutex);
1439 ret = pipe_set_size(pipe, arg);
1442 ret = pipe->max_usage * PAGE_SIZE;
1449 mutex_unlock(&pipe->mutex);
1453 static const struct super_operations pipefs_ops = {
1454 .destroy_inode = free_inode_nonrcu,
1455 .statfs = simple_statfs,
1459 * pipefs should _never_ be mounted by userland - too much of security hassle,
1460 * no real gain from having the whole file system mounted. So we don't need
1461 * any operations on the root directory. However, we need a non-trivial
1462 * d_name - pipe: will go nicely and kill the special-casing in procfs.
1465 static int pipefs_init_fs_context(struct fs_context *fc)
1467 struct pseudo_fs_context *ctx = init_pseudo(fc, PIPEFS_MAGIC);
1470 ctx->ops = &pipefs_ops;
1471 ctx->dops = &pipefs_dentry_operations;
1475 static struct file_system_type pipe_fs_type = {
1477 .init_fs_context = pipefs_init_fs_context,
1478 .kill_sb = kill_anon_super,
1481 #ifdef CONFIG_SYSCTL
1482 static int do_proc_dopipe_max_size_conv(unsigned long *lvalp,
1484 int write, void *data)
1489 val = round_pipe_size(*lvalp);
1495 unsigned int val = *valp;
1496 *lvalp = (unsigned long) val;
1502 static int proc_dopipe_max_size(const struct ctl_table *table, int write,
1503 void *buffer, size_t *lenp, loff_t *ppos)
1505 return do_proc_douintvec(table, write, buffer, lenp, ppos,
1506 do_proc_dopipe_max_size_conv, NULL);
1509 static const struct ctl_table fs_pipe_sysctls[] = {
1511 .procname = "pipe-max-size",
1512 .data = &pipe_max_size,
1513 .maxlen = sizeof(pipe_max_size),
1515 .proc_handler = proc_dopipe_max_size,
1518 .procname = "pipe-user-pages-hard",
1519 .data = &pipe_user_pages_hard,
1520 .maxlen = sizeof(pipe_user_pages_hard),
1522 .proc_handler = proc_doulongvec_minmax,
1525 .procname = "pipe-user-pages-soft",
1526 .data = &pipe_user_pages_soft,
1527 .maxlen = sizeof(pipe_user_pages_soft),
1529 .proc_handler = proc_doulongvec_minmax,
1534 static int __init init_pipe_fs(void)
1536 int err = register_filesystem(&pipe_fs_type);
1539 pipe_mnt = kern_mount(&pipe_fs_type);
1540 if (IS_ERR(pipe_mnt)) {
1541 err = PTR_ERR(pipe_mnt);
1542 unregister_filesystem(&pipe_fs_type);
1545 #ifdef CONFIG_SYSCTL
1546 register_sysctl_init("fs", fs_pipe_sysctls);
1551 fs_initcall(init_pipe_fs);