pipe: fix and clarify pipe read wakeup logic
[linux-2.6-microblaze.git] / fs / pipe.c
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
28 #include <linux/uaccess.h>
29 #include <asm/ioctls.h>
30
31 #include "internal.h"
32
33 /*
34  * The max size that a non-root user is allowed to grow the pipe. Can
35  * be set by root in /proc/sys/fs/pipe-max-size
36  */
37 unsigned int pipe_max_size = 1048576;
38
39 /* Maximum allocatable pages per user. Hard limit is unset by default, soft
40  * matches default values.
41  */
42 unsigned long pipe_user_pages_hard;
43 unsigned long pipe_user_pages_soft = PIPE_DEF_BUFFERS * INR_OPEN_CUR;
44
45 /*
46  * We use head and tail indices that aren't masked off, except at the point of
47  * dereference, but rather they're allowed to wrap naturally.  This means there
48  * isn't a dead spot in the buffer, but the ring has to be a power of two and
49  * <= 2^31.
50  * -- David Howells 2019-09-23.
51  *
52  * Reads with count = 0 should always return 0.
53  * -- Julian Bradfield 1999-06-07.
54  *
55  * FIFOs and Pipes now generate SIGIO for both readers and writers.
56  * -- Jeremy Elson <jelson@circlemud.org> 2001-08-16
57  *
58  * pipe_read & write cleanup
59  * -- Manfred Spraul <manfred@colorfullife.com> 2002-05-09
60  */
61
62 static void pipe_lock_nested(struct pipe_inode_info *pipe, int subclass)
63 {
64         if (pipe->files)
65                 mutex_lock_nested(&pipe->mutex, subclass);
66 }
67
68 void pipe_lock(struct pipe_inode_info *pipe)
69 {
70         /*
71          * pipe_lock() nests non-pipe inode locks (for writing to a file)
72          */
73         pipe_lock_nested(pipe, I_MUTEX_PARENT);
74 }
75 EXPORT_SYMBOL(pipe_lock);
76
77 void pipe_unlock(struct pipe_inode_info *pipe)
78 {
79         if (pipe->files)
80                 mutex_unlock(&pipe->mutex);
81 }
82 EXPORT_SYMBOL(pipe_unlock);
83
84 static inline void __pipe_lock(struct pipe_inode_info *pipe)
85 {
86         mutex_lock_nested(&pipe->mutex, I_MUTEX_PARENT);
87 }
88
89 static inline void __pipe_unlock(struct pipe_inode_info *pipe)
90 {
91         mutex_unlock(&pipe->mutex);
92 }
93
94 void pipe_double_lock(struct pipe_inode_info *pipe1,
95                       struct pipe_inode_info *pipe2)
96 {
97         BUG_ON(pipe1 == pipe2);
98
99         if (pipe1 < pipe2) {
100                 pipe_lock_nested(pipe1, I_MUTEX_PARENT);
101                 pipe_lock_nested(pipe2, I_MUTEX_CHILD);
102         } else {
103                 pipe_lock_nested(pipe2, I_MUTEX_PARENT);
104                 pipe_lock_nested(pipe1, I_MUTEX_CHILD);
105         }
106 }
107
108 /* Drop the inode semaphore and wait for a pipe event, atomically */
109 void pipe_wait(struct pipe_inode_info *pipe)
110 {
111         DEFINE_WAIT(wait);
112
113         /*
114          * Pipes are system-local resources, so sleeping on them
115          * is considered a noninteractive wait:
116          */
117         prepare_to_wait(&pipe->wait, &wait, TASK_INTERRUPTIBLE);
118         pipe_unlock(pipe);
119         schedule();
120         finish_wait(&pipe->wait, &wait);
121         pipe_lock(pipe);
122 }
123
124 static void anon_pipe_buf_release(struct pipe_inode_info *pipe,
125                                   struct pipe_buffer *buf)
126 {
127         struct page *page = buf->page;
128
129         /*
130          * If nobody else uses this page, and we don't already have a
131          * temporary page, let's keep track of it as a one-deep
132          * allocation cache. (Otherwise just release our reference to it)
133          */
134         if (page_count(page) == 1 && !pipe->tmp_page)
135                 pipe->tmp_page = page;
136         else
137                 put_page(page);
138 }
139
140 static int anon_pipe_buf_steal(struct pipe_inode_info *pipe,
141                                struct pipe_buffer *buf)
142 {
143         struct page *page = buf->page;
144
145         if (page_count(page) == 1) {
146                 memcg_kmem_uncharge(page, 0);
147                 __SetPageLocked(page);
148                 return 0;
149         }
150         return 1;
151 }
152
153 /**
154  * generic_pipe_buf_steal - attempt to take ownership of a &pipe_buffer
155  * @pipe:       the pipe that the buffer belongs to
156  * @buf:        the buffer to attempt to steal
157  *
158  * Description:
159  *      This function attempts to steal the &struct page attached to
160  *      @buf. If successful, this function returns 0 and returns with
161  *      the page locked. The caller may then reuse the page for whatever
162  *      he wishes; the typical use is insertion into a different file
163  *      page cache.
164  */
165 int generic_pipe_buf_steal(struct pipe_inode_info *pipe,
166                            struct pipe_buffer *buf)
167 {
168         struct page *page = buf->page;
169
170         /*
171          * A reference of one is golden, that means that the owner of this
172          * page is the only one holding a reference to it. lock the page
173          * and return OK.
174          */
175         if (page_count(page) == 1) {
176                 lock_page(page);
177                 return 0;
178         }
179
180         return 1;
181 }
182 EXPORT_SYMBOL(generic_pipe_buf_steal);
183
184 /**
185  * generic_pipe_buf_get - get a reference to a &struct pipe_buffer
186  * @pipe:       the pipe that the buffer belongs to
187  * @buf:        the buffer to get a reference to
188  *
189  * Description:
190  *      This function grabs an extra reference to @buf. It's used in
191  *      in the tee() system call, when we duplicate the buffers in one
192  *      pipe into another.
193  */
194 bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
195 {
196         return try_get_page(buf->page);
197 }
198 EXPORT_SYMBOL(generic_pipe_buf_get);
199
200 /**
201  * generic_pipe_buf_confirm - verify contents of the pipe buffer
202  * @info:       the pipe that the buffer belongs to
203  * @buf:        the buffer to confirm
204  *
205  * Description:
206  *      This function does nothing, because the generic pipe code uses
207  *      pages that are always good when inserted into the pipe.
208  */
209 int generic_pipe_buf_confirm(struct pipe_inode_info *info,
210                              struct pipe_buffer *buf)
211 {
212         return 0;
213 }
214 EXPORT_SYMBOL(generic_pipe_buf_confirm);
215
216 /**
217  * generic_pipe_buf_release - put a reference to a &struct pipe_buffer
218  * @pipe:       the pipe that the buffer belongs to
219  * @buf:        the buffer to put a reference to
220  *
221  * Description:
222  *      This function releases a reference to @buf.
223  */
224 void generic_pipe_buf_release(struct pipe_inode_info *pipe,
225                               struct pipe_buffer *buf)
226 {
227         put_page(buf->page);
228 }
229 EXPORT_SYMBOL(generic_pipe_buf_release);
230
231 /* New data written to a pipe may be appended to a buffer with this type. */
232 static const struct pipe_buf_operations anon_pipe_buf_ops = {
233         .confirm = generic_pipe_buf_confirm,
234         .release = anon_pipe_buf_release,
235         .steal = anon_pipe_buf_steal,
236         .get = generic_pipe_buf_get,
237 };
238
239 static const struct pipe_buf_operations anon_pipe_buf_nomerge_ops = {
240         .confirm = generic_pipe_buf_confirm,
241         .release = anon_pipe_buf_release,
242         .steal = anon_pipe_buf_steal,
243         .get = generic_pipe_buf_get,
244 };
245
246 static const struct pipe_buf_operations packet_pipe_buf_ops = {
247         .confirm = generic_pipe_buf_confirm,
248         .release = anon_pipe_buf_release,
249         .steal = anon_pipe_buf_steal,
250         .get = generic_pipe_buf_get,
251 };
252
253 /**
254  * pipe_buf_mark_unmergeable - mark a &struct pipe_buffer as unmergeable
255  * @buf:        the buffer to mark
256  *
257  * Description:
258  *      This function ensures that no future writes will be merged into the
259  *      given &struct pipe_buffer. This is necessary when multiple pipe buffers
260  *      share the same backing page.
261  */
262 void pipe_buf_mark_unmergeable(struct pipe_buffer *buf)
263 {
264         if (buf->ops == &anon_pipe_buf_ops)
265                 buf->ops = &anon_pipe_buf_nomerge_ops;
266 }
267
268 static bool pipe_buf_can_merge(struct pipe_buffer *buf)
269 {
270         return buf->ops == &anon_pipe_buf_ops;
271 }
272
273 static ssize_t
274 pipe_read(struct kiocb *iocb, struct iov_iter *to)
275 {
276         size_t total_len = iov_iter_count(to);
277         struct file *filp = iocb->ki_filp;
278         struct pipe_inode_info *pipe = filp->private_data;
279         bool was_full;
280         ssize_t ret;
281
282         /* Null read succeeds. */
283         if (unlikely(total_len == 0))
284                 return 0;
285
286         ret = 0;
287         __pipe_lock(pipe);
288
289         /*
290          * We only wake up writers if the pipe was full when we started
291          * reading in order to avoid unnecessary wakeups.
292          *
293          * But when we do wake up writers, we do so using a sync wakeup
294          * (WF_SYNC), because we want them to get going and generate more
295          * data for us.
296          */
297         was_full = pipe_full(pipe->head, pipe->tail, pipe->max_usage);
298         for (;;) {
299                 unsigned int head = pipe->head;
300                 unsigned int tail = pipe->tail;
301                 unsigned int mask = pipe->ring_size - 1;
302
303                 if (!pipe_empty(head, tail)) {
304                         struct pipe_buffer *buf = &pipe->bufs[tail & mask];
305                         size_t chars = buf->len;
306                         size_t written;
307                         int error;
308
309                         if (chars > total_len)
310                                 chars = total_len;
311
312                         error = pipe_buf_confirm(pipe, buf);
313                         if (error) {
314                                 if (!ret)
315                                         ret = error;
316                                 break;
317                         }
318
319                         written = copy_page_to_iter(buf->page, buf->offset, chars, to);
320                         if (unlikely(written < chars)) {
321                                 if (!ret)
322                                         ret = -EFAULT;
323                                 break;
324                         }
325                         ret += chars;
326                         buf->offset += chars;
327                         buf->len -= chars;
328
329                         /* Was it a packet buffer? Clean up and exit */
330                         if (buf->flags & PIPE_BUF_FLAG_PACKET) {
331                                 total_len = chars;
332                                 buf->len = 0;
333                         }
334
335                         if (!buf->len) {
336                                 pipe_buf_release(pipe, buf);
337                                 spin_lock_irq(&pipe->wait.lock);
338                                 tail++;
339                                 pipe->tail = tail;
340                                 spin_unlock_irq(&pipe->wait.lock);
341                         }
342                         total_len -= chars;
343                         if (!total_len)
344                                 break;  /* common path: read succeeded */
345                         if (!pipe_empty(head, tail))    /* More to do? */
346                                 continue;
347                 }
348
349                 if (!pipe->writers)
350                         break;
351                 if (!pipe->waiting_writers) {
352                         /* syscall merging: Usually we must not sleep
353                          * if O_NONBLOCK is set, or if we got some data.
354                          * But if a writer sleeps in kernel space, then
355                          * we can wait for that data without violating POSIX.
356                          */
357                         if (ret)
358                                 break;
359                         if (filp->f_flags & O_NONBLOCK) {
360                                 ret = -EAGAIN;
361                                 break;
362                         }
363                 }
364                 if (signal_pending(current)) {
365                         if (!ret)
366                                 ret = -ERESTARTSYS;
367                         break;
368                 }
369                 if (was_full) {
370                         wake_up_interruptible_sync_poll(&pipe->wait, EPOLLOUT | EPOLLWRNORM);
371                         kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
372                 }
373                 pipe_wait(pipe);
374                 was_full = pipe_full(pipe->head, pipe->tail, pipe->max_usage);
375         }
376         __pipe_unlock(pipe);
377
378         if (was_full) {
379                 wake_up_interruptible_sync_poll(&pipe->wait, EPOLLOUT | EPOLLWRNORM);
380                 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
381         }
382         if (ret > 0)
383                 file_accessed(filp);
384         return ret;
385 }
386
387 static inline int is_packetized(struct file *file)
388 {
389         return (file->f_flags & O_DIRECT) != 0;
390 }
391
392 static ssize_t
393 pipe_write(struct kiocb *iocb, struct iov_iter *from)
394 {
395         struct file *filp = iocb->ki_filp;
396         struct pipe_inode_info *pipe = filp->private_data;
397         unsigned int head;
398         ssize_t ret = 0;
399         size_t total_len = iov_iter_count(from);
400         ssize_t chars;
401         bool was_empty = false;
402
403         /* Null write succeeds. */
404         if (unlikely(total_len == 0))
405                 return 0;
406
407         __pipe_lock(pipe);
408
409         if (!pipe->readers) {
410                 send_sig(SIGPIPE, current, 0);
411                 ret = -EPIPE;
412                 goto out;
413         }
414
415         /*
416          * Only wake up if the pipe started out empty, since
417          * otherwise there should be no readers waiting.
418          *
419          * If it wasn't empty we try to merge new data into
420          * the last buffer.
421          *
422          * That naturally merges small writes, but it also
423          * page-aligs the rest of the writes for large writes
424          * spanning multiple pages.
425          */
426         head = pipe->head;
427         was_empty = pipe_empty(head, pipe->tail);
428         chars = total_len & (PAGE_SIZE-1);
429         if (chars && !was_empty) {
430                 unsigned int mask = pipe->ring_size - 1;
431                 struct pipe_buffer *buf = &pipe->bufs[(head - 1) & mask];
432                 int offset = buf->offset + buf->len;
433
434                 if (pipe_buf_can_merge(buf) && offset + chars <= PAGE_SIZE) {
435                         ret = pipe_buf_confirm(pipe, buf);
436                         if (ret)
437                                 goto out;
438
439                         ret = copy_page_from_iter(buf->page, offset, chars, from);
440                         if (unlikely(ret < chars)) {
441                                 ret = -EFAULT;
442                                 goto out;
443                         }
444
445                         buf->len += ret;
446                         if (!iov_iter_count(from))
447                                 goto out;
448                 }
449         }
450
451         for (;;) {
452                 if (!pipe->readers) {
453                         send_sig(SIGPIPE, current, 0);
454                         if (!ret)
455                                 ret = -EPIPE;
456                         break;
457                 }
458
459                 head = pipe->head;
460                 if (!pipe_full(head, pipe->tail, pipe->max_usage)) {
461                         unsigned int mask = pipe->ring_size - 1;
462                         struct pipe_buffer *buf = &pipe->bufs[head & mask];
463                         struct page *page = pipe->tmp_page;
464                         int copied;
465
466                         if (!page) {
467                                 page = alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT);
468                                 if (unlikely(!page)) {
469                                         ret = ret ? : -ENOMEM;
470                                         break;
471                                 }
472                                 pipe->tmp_page = page;
473                         }
474
475                         /* Allocate a slot in the ring in advance and attach an
476                          * empty buffer.  If we fault or otherwise fail to use
477                          * it, either the reader will consume it or it'll still
478                          * be there for the next write.
479                          */
480                         spin_lock_irq(&pipe->wait.lock);
481
482                         head = pipe->head;
483                         if (pipe_full(head, pipe->tail, pipe->max_usage)) {
484                                 spin_unlock_irq(&pipe->wait.lock);
485                                 continue;
486                         }
487
488                         pipe->head = head + 1;
489                         spin_unlock_irq(&pipe->wait.lock);
490
491                         /* Insert it into the buffer array */
492                         buf = &pipe->bufs[head & mask];
493                         buf->page = page;
494                         buf->ops = &anon_pipe_buf_ops;
495                         buf->offset = 0;
496                         buf->len = 0;
497                         buf->flags = 0;
498                         if (is_packetized(filp)) {
499                                 buf->ops = &packet_pipe_buf_ops;
500                                 buf->flags = PIPE_BUF_FLAG_PACKET;
501                         }
502                         pipe->tmp_page = NULL;
503
504                         copied = copy_page_from_iter(page, 0, PAGE_SIZE, from);
505                         if (unlikely(copied < PAGE_SIZE && iov_iter_count(from))) {
506                                 if (!ret)
507                                         ret = -EFAULT;
508                                 break;
509                         }
510                         ret += copied;
511                         buf->offset = 0;
512                         buf->len = copied;
513
514                         if (!iov_iter_count(from))
515                                 break;
516                 }
517
518                 if (!pipe_full(head, pipe->tail, pipe->max_usage))
519                         continue;
520
521                 /* Wait for buffer space to become available. */
522                 if (filp->f_flags & O_NONBLOCK) {
523                         if (!ret)
524                                 ret = -EAGAIN;
525                         break;
526                 }
527                 if (signal_pending(current)) {
528                         if (!ret)
529                                 ret = -ERESTARTSYS;
530                         break;
531                 }
532
533                 /*
534                  * We're going to release the pipe lock and wait for more
535                  * space. We wake up any readers if necessary, and then
536                  * after waiting we need to re-check whether the pipe
537                  * become empty while we dropped the lock.
538                  */
539                 if (was_empty) {
540                         wake_up_interruptible_sync_poll(&pipe->wait, EPOLLIN | EPOLLRDNORM);
541                         kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
542                 }
543                 pipe->waiting_writers++;
544                 pipe_wait(pipe);
545                 pipe->waiting_writers--;
546
547                 was_empty = pipe_empty(head, pipe->tail);
548         }
549 out:
550         __pipe_unlock(pipe);
551
552         /*
553          * If we do do a wakeup event, we do a 'sync' wakeup, because we
554          * want the reader to start processing things asap, rather than
555          * leave the data pending.
556          *
557          * This is particularly important for small writes, because of
558          * how (for example) the GNU make jobserver uses small writes to
559          * wake up pending jobs
560          */
561         if (was_empty) {
562                 wake_up_interruptible_sync_poll(&pipe->wait, EPOLLIN | EPOLLRDNORM);
563                 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
564         }
565         if (ret > 0 && sb_start_write_trylock(file_inode(filp)->i_sb)) {
566                 int err = file_update_time(filp);
567                 if (err)
568                         ret = err;
569                 sb_end_write(file_inode(filp)->i_sb);
570         }
571         return ret;
572 }
573
574 static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
575 {
576         struct pipe_inode_info *pipe = filp->private_data;
577         int count, head, tail, mask;
578
579         switch (cmd) {
580                 case FIONREAD:
581                         __pipe_lock(pipe);
582                         count = 0;
583                         head = pipe->head;
584                         tail = pipe->tail;
585                         mask = pipe->ring_size - 1;
586
587                         while (tail != head) {
588                                 count += pipe->bufs[tail & mask].len;
589                                 tail++;
590                         }
591                         __pipe_unlock(pipe);
592
593                         return put_user(count, (int __user *)arg);
594                 default:
595                         return -ENOIOCTLCMD;
596         }
597 }
598
599 /* No kernel lock held - fine */
600 static __poll_t
601 pipe_poll(struct file *filp, poll_table *wait)
602 {
603         __poll_t mask;
604         struct pipe_inode_info *pipe = filp->private_data;
605         unsigned int head, tail;
606
607         /*
608          * Reading only -- no need for acquiring the semaphore.
609          *
610          * But because this is racy, the code has to add the
611          * entry to the poll table _first_ ..
612          */
613         poll_wait(filp, &pipe->wait, wait);
614
615         /*
616          * .. and only then can you do the racy tests. That way,
617          * if something changes and you got it wrong, the poll
618          * table entry will wake you up and fix it.
619          */
620         head = READ_ONCE(pipe->head);
621         tail = READ_ONCE(pipe->tail);
622
623         mask = 0;
624         if (filp->f_mode & FMODE_READ) {
625                 if (!pipe_empty(head, tail))
626                         mask |= EPOLLIN | EPOLLRDNORM;
627                 if (!pipe->writers && filp->f_version != pipe->w_counter)
628                         mask |= EPOLLHUP;
629         }
630
631         if (filp->f_mode & FMODE_WRITE) {
632                 if (!pipe_full(head, tail, pipe->max_usage))
633                         mask |= EPOLLOUT | EPOLLWRNORM;
634                 /*
635                  * Most Unices do not set EPOLLERR for FIFOs but on Linux they
636                  * behave exactly like pipes for poll().
637                  */
638                 if (!pipe->readers)
639                         mask |= EPOLLERR;
640         }
641
642         return mask;
643 }
644
645 static void put_pipe_info(struct inode *inode, struct pipe_inode_info *pipe)
646 {
647         int kill = 0;
648
649         spin_lock(&inode->i_lock);
650         if (!--pipe->files) {
651                 inode->i_pipe = NULL;
652                 kill = 1;
653         }
654         spin_unlock(&inode->i_lock);
655
656         if (kill)
657                 free_pipe_info(pipe);
658 }
659
660 static int
661 pipe_release(struct inode *inode, struct file *file)
662 {
663         struct pipe_inode_info *pipe = file->private_data;
664
665         __pipe_lock(pipe);
666         if (file->f_mode & FMODE_READ)
667                 pipe->readers--;
668         if (file->f_mode & FMODE_WRITE)
669                 pipe->writers--;
670
671         if (pipe->readers || pipe->writers) {
672                 wake_up_interruptible_sync_poll(&pipe->wait, EPOLLIN | EPOLLOUT | EPOLLRDNORM | EPOLLWRNORM | EPOLLERR | EPOLLHUP);
673                 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
674                 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
675         }
676         __pipe_unlock(pipe);
677
678         put_pipe_info(inode, pipe);
679         return 0;
680 }
681
682 static int
683 pipe_fasync(int fd, struct file *filp, int on)
684 {
685         struct pipe_inode_info *pipe = filp->private_data;
686         int retval = 0;
687
688         __pipe_lock(pipe);
689         if (filp->f_mode & FMODE_READ)
690                 retval = fasync_helper(fd, filp, on, &pipe->fasync_readers);
691         if ((filp->f_mode & FMODE_WRITE) && retval >= 0) {
692                 retval = fasync_helper(fd, filp, on, &pipe->fasync_writers);
693                 if (retval < 0 && (filp->f_mode & FMODE_READ))
694                         /* this can happen only if on == T */
695                         fasync_helper(-1, filp, 0, &pipe->fasync_readers);
696         }
697         __pipe_unlock(pipe);
698         return retval;
699 }
700
701 static unsigned long account_pipe_buffers(struct user_struct *user,
702                                  unsigned long old, unsigned long new)
703 {
704         return atomic_long_add_return(new - old, &user->pipe_bufs);
705 }
706
707 static bool too_many_pipe_buffers_soft(unsigned long user_bufs)
708 {
709         unsigned long soft_limit = READ_ONCE(pipe_user_pages_soft);
710
711         return soft_limit && user_bufs > soft_limit;
712 }
713
714 static bool too_many_pipe_buffers_hard(unsigned long user_bufs)
715 {
716         unsigned long hard_limit = READ_ONCE(pipe_user_pages_hard);
717
718         return hard_limit && user_bufs > hard_limit;
719 }
720
721 static bool is_unprivileged_user(void)
722 {
723         return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN);
724 }
725
726 struct pipe_inode_info *alloc_pipe_info(void)
727 {
728         struct pipe_inode_info *pipe;
729         unsigned long pipe_bufs = PIPE_DEF_BUFFERS;
730         struct user_struct *user = get_current_user();
731         unsigned long user_bufs;
732         unsigned int max_size = READ_ONCE(pipe_max_size);
733
734         pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL_ACCOUNT);
735         if (pipe == NULL)
736                 goto out_free_uid;
737
738         if (pipe_bufs * PAGE_SIZE > max_size && !capable(CAP_SYS_RESOURCE))
739                 pipe_bufs = max_size >> PAGE_SHIFT;
740
741         user_bufs = account_pipe_buffers(user, 0, pipe_bufs);
742
743         if (too_many_pipe_buffers_soft(user_bufs) && is_unprivileged_user()) {
744                 user_bufs = account_pipe_buffers(user, pipe_bufs, 1);
745                 pipe_bufs = 1;
746         }
747
748         if (too_many_pipe_buffers_hard(user_bufs) && is_unprivileged_user())
749                 goto out_revert_acct;
750
751         pipe->bufs = kcalloc(pipe_bufs, sizeof(struct pipe_buffer),
752                              GFP_KERNEL_ACCOUNT);
753
754         if (pipe->bufs) {
755                 init_waitqueue_head(&pipe->wait);
756                 pipe->r_counter = pipe->w_counter = 1;
757                 pipe->max_usage = pipe_bufs;
758                 pipe->ring_size = pipe_bufs;
759                 pipe->user = user;
760                 mutex_init(&pipe->mutex);
761                 return pipe;
762         }
763
764 out_revert_acct:
765         (void) account_pipe_buffers(user, pipe_bufs, 0);
766         kfree(pipe);
767 out_free_uid:
768         free_uid(user);
769         return NULL;
770 }
771
772 void free_pipe_info(struct pipe_inode_info *pipe)
773 {
774         int i;
775
776         (void) account_pipe_buffers(pipe->user, pipe->ring_size, 0);
777         free_uid(pipe->user);
778         for (i = 0; i < pipe->ring_size; i++) {
779                 struct pipe_buffer *buf = pipe->bufs + i;
780                 if (buf->ops)
781                         pipe_buf_release(pipe, buf);
782         }
783         if (pipe->tmp_page)
784                 __free_page(pipe->tmp_page);
785         kfree(pipe->bufs);
786         kfree(pipe);
787 }
788
789 static struct vfsmount *pipe_mnt __read_mostly;
790
791 /*
792  * pipefs_dname() is called from d_path().
793  */
794 static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen)
795 {
796         return dynamic_dname(dentry, buffer, buflen, "pipe:[%lu]",
797                                 d_inode(dentry)->i_ino);
798 }
799
800 static const struct dentry_operations pipefs_dentry_operations = {
801         .d_dname        = pipefs_dname,
802 };
803
804 static struct inode * get_pipe_inode(void)
805 {
806         struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb);
807         struct pipe_inode_info *pipe;
808
809         if (!inode)
810                 goto fail_inode;
811
812         inode->i_ino = get_next_ino();
813
814         pipe = alloc_pipe_info();
815         if (!pipe)
816                 goto fail_iput;
817
818         inode->i_pipe = pipe;
819         pipe->files = 2;
820         pipe->readers = pipe->writers = 1;
821         inode->i_fop = &pipefifo_fops;
822
823         /*
824          * Mark the inode dirty from the very beginning,
825          * that way it will never be moved to the dirty
826          * list because "mark_inode_dirty()" will think
827          * that it already _is_ on the dirty list.
828          */
829         inode->i_state = I_DIRTY;
830         inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR;
831         inode->i_uid = current_fsuid();
832         inode->i_gid = current_fsgid();
833         inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
834
835         return inode;
836
837 fail_iput:
838         iput(inode);
839
840 fail_inode:
841         return NULL;
842 }
843
844 int create_pipe_files(struct file **res, int flags)
845 {
846         struct inode *inode = get_pipe_inode();
847         struct file *f;
848
849         if (!inode)
850                 return -ENFILE;
851
852         f = alloc_file_pseudo(inode, pipe_mnt, "",
853                                 O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)),
854                                 &pipefifo_fops);
855         if (IS_ERR(f)) {
856                 free_pipe_info(inode->i_pipe);
857                 iput(inode);
858                 return PTR_ERR(f);
859         }
860
861         f->private_data = inode->i_pipe;
862
863         res[0] = alloc_file_clone(f, O_RDONLY | (flags & O_NONBLOCK),
864                                   &pipefifo_fops);
865         if (IS_ERR(res[0])) {
866                 put_pipe_info(inode, inode->i_pipe);
867                 fput(f);
868                 return PTR_ERR(res[0]);
869         }
870         res[0]->private_data = inode->i_pipe;
871         res[1] = f;
872         stream_open(inode, res[0]);
873         stream_open(inode, res[1]);
874         return 0;
875 }
876
877 static int __do_pipe_flags(int *fd, struct file **files, int flags)
878 {
879         int error;
880         int fdw, fdr;
881
882         if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT))
883                 return -EINVAL;
884
885         error = create_pipe_files(files, flags);
886         if (error)
887                 return error;
888
889         error = get_unused_fd_flags(flags);
890         if (error < 0)
891                 goto err_read_pipe;
892         fdr = error;
893
894         error = get_unused_fd_flags(flags);
895         if (error < 0)
896                 goto err_fdr;
897         fdw = error;
898
899         audit_fd_pair(fdr, fdw);
900         fd[0] = fdr;
901         fd[1] = fdw;
902         return 0;
903
904  err_fdr:
905         put_unused_fd(fdr);
906  err_read_pipe:
907         fput(files[0]);
908         fput(files[1]);
909         return error;
910 }
911
912 int do_pipe_flags(int *fd, int flags)
913 {
914         struct file *files[2];
915         int error = __do_pipe_flags(fd, files, flags);
916         if (!error) {
917                 fd_install(fd[0], files[0]);
918                 fd_install(fd[1], files[1]);
919         }
920         return error;
921 }
922
923 /*
924  * sys_pipe() is the normal C calling standard for creating
925  * a pipe. It's not the way Unix traditionally does this, though.
926  */
927 static int do_pipe2(int __user *fildes, int flags)
928 {
929         struct file *files[2];
930         int fd[2];
931         int error;
932
933         error = __do_pipe_flags(fd, files, flags);
934         if (!error) {
935                 if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) {
936                         fput(files[0]);
937                         fput(files[1]);
938                         put_unused_fd(fd[0]);
939                         put_unused_fd(fd[1]);
940                         error = -EFAULT;
941                 } else {
942                         fd_install(fd[0], files[0]);
943                         fd_install(fd[1], files[1]);
944                 }
945         }
946         return error;
947 }
948
949 SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags)
950 {
951         return do_pipe2(fildes, flags);
952 }
953
954 SYSCALL_DEFINE1(pipe, int __user *, fildes)
955 {
956         return do_pipe2(fildes, 0);
957 }
958
959 static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt)
960 {
961         int cur = *cnt;
962
963         while (cur == *cnt) {
964                 pipe_wait(pipe);
965                 if (signal_pending(current))
966                         break;
967         }
968         return cur == *cnt ? -ERESTARTSYS : 0;
969 }
970
971 static void wake_up_partner(struct pipe_inode_info *pipe)
972 {
973         wake_up_interruptible(&pipe->wait);
974 }
975
976 static int fifo_open(struct inode *inode, struct file *filp)
977 {
978         struct pipe_inode_info *pipe;
979         bool is_pipe = inode->i_sb->s_magic == PIPEFS_MAGIC;
980         int ret;
981
982         filp->f_version = 0;
983
984         spin_lock(&inode->i_lock);
985         if (inode->i_pipe) {
986                 pipe = inode->i_pipe;
987                 pipe->files++;
988                 spin_unlock(&inode->i_lock);
989         } else {
990                 spin_unlock(&inode->i_lock);
991                 pipe = alloc_pipe_info();
992                 if (!pipe)
993                         return -ENOMEM;
994                 pipe->files = 1;
995                 spin_lock(&inode->i_lock);
996                 if (unlikely(inode->i_pipe)) {
997                         inode->i_pipe->files++;
998                         spin_unlock(&inode->i_lock);
999                         free_pipe_info(pipe);
1000                         pipe = inode->i_pipe;
1001                 } else {
1002                         inode->i_pipe = pipe;
1003                         spin_unlock(&inode->i_lock);
1004                 }
1005         }
1006         filp->private_data = pipe;
1007         /* OK, we have a pipe and it's pinned down */
1008
1009         __pipe_lock(pipe);
1010
1011         /* We can only do regular read/write on fifos */
1012         stream_open(inode, filp);
1013
1014         switch (filp->f_mode & (FMODE_READ | FMODE_WRITE)) {
1015         case FMODE_READ:
1016         /*
1017          *  O_RDONLY
1018          *  POSIX.1 says that O_NONBLOCK means return with the FIFO
1019          *  opened, even when there is no process writing the FIFO.
1020          */
1021                 pipe->r_counter++;
1022                 if (pipe->readers++ == 0)
1023                         wake_up_partner(pipe);
1024
1025                 if (!is_pipe && !pipe->writers) {
1026                         if ((filp->f_flags & O_NONBLOCK)) {
1027                                 /* suppress EPOLLHUP until we have
1028                                  * seen a writer */
1029                                 filp->f_version = pipe->w_counter;
1030                         } else {
1031                                 if (wait_for_partner(pipe, &pipe->w_counter))
1032                                         goto err_rd;
1033                         }
1034                 }
1035                 break;
1036
1037         case FMODE_WRITE:
1038         /*
1039          *  O_WRONLY
1040          *  POSIX.1 says that O_NONBLOCK means return -1 with
1041          *  errno=ENXIO when there is no process reading the FIFO.
1042          */
1043                 ret = -ENXIO;
1044                 if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers)
1045                         goto err;
1046
1047                 pipe->w_counter++;
1048                 if (!pipe->writers++)
1049                         wake_up_partner(pipe);
1050
1051                 if (!is_pipe && !pipe->readers) {
1052                         if (wait_for_partner(pipe, &pipe->r_counter))
1053                                 goto err_wr;
1054                 }
1055                 break;
1056
1057         case FMODE_READ | FMODE_WRITE:
1058         /*
1059          *  O_RDWR
1060          *  POSIX.1 leaves this case "undefined" when O_NONBLOCK is set.
1061          *  This implementation will NEVER block on a O_RDWR open, since
1062          *  the process can at least talk to itself.
1063          */
1064
1065                 pipe->readers++;
1066                 pipe->writers++;
1067                 pipe->r_counter++;
1068                 pipe->w_counter++;
1069                 if (pipe->readers == 1 || pipe->writers == 1)
1070                         wake_up_partner(pipe);
1071                 break;
1072
1073         default:
1074                 ret = -EINVAL;
1075                 goto err;
1076         }
1077
1078         /* Ok! */
1079         __pipe_unlock(pipe);
1080         return 0;
1081
1082 err_rd:
1083         if (!--pipe->readers)
1084                 wake_up_interruptible(&pipe->wait);
1085         ret = -ERESTARTSYS;
1086         goto err;
1087
1088 err_wr:
1089         if (!--pipe->writers)
1090                 wake_up_interruptible(&pipe->wait);
1091         ret = -ERESTARTSYS;
1092         goto err;
1093
1094 err:
1095         __pipe_unlock(pipe);
1096
1097         put_pipe_info(inode, pipe);
1098         return ret;
1099 }
1100
1101 const struct file_operations pipefifo_fops = {
1102         .open           = fifo_open,
1103         .llseek         = no_llseek,
1104         .read_iter      = pipe_read,
1105         .write_iter     = pipe_write,
1106         .poll           = pipe_poll,
1107         .unlocked_ioctl = pipe_ioctl,
1108         .release        = pipe_release,
1109         .fasync         = pipe_fasync,
1110 };
1111
1112 /*
1113  * Currently we rely on the pipe array holding a power-of-2 number
1114  * of pages. Returns 0 on error.
1115  */
1116 unsigned int round_pipe_size(unsigned long size)
1117 {
1118         if (size > (1U << 31))
1119                 return 0;
1120
1121         /* Minimum pipe size, as required by POSIX */
1122         if (size < PAGE_SIZE)
1123                 return PAGE_SIZE;
1124
1125         return roundup_pow_of_two(size);
1126 }
1127
1128 /*
1129  * Allocate a new array of pipe buffers and copy the info over. Returns the
1130  * pipe size if successful, or return -ERROR on error.
1131  */
1132 static long pipe_set_size(struct pipe_inode_info *pipe, unsigned long arg)
1133 {
1134         struct pipe_buffer *bufs;
1135         unsigned int size, nr_slots, head, tail, mask, n;
1136         unsigned long user_bufs;
1137         long ret = 0;
1138
1139         size = round_pipe_size(arg);
1140         nr_slots = size >> PAGE_SHIFT;
1141
1142         if (!nr_slots)
1143                 return -EINVAL;
1144
1145         /*
1146          * If trying to increase the pipe capacity, check that an
1147          * unprivileged user is not trying to exceed various limits
1148          * (soft limit check here, hard limit check just below).
1149          * Decreasing the pipe capacity is always permitted, even
1150          * if the user is currently over a limit.
1151          */
1152         if (nr_slots > pipe->ring_size &&
1153                         size > pipe_max_size && !capable(CAP_SYS_RESOURCE))
1154                 return -EPERM;
1155
1156         user_bufs = account_pipe_buffers(pipe->user, pipe->ring_size, nr_slots);
1157
1158         if (nr_slots > pipe->ring_size &&
1159                         (too_many_pipe_buffers_hard(user_bufs) ||
1160                          too_many_pipe_buffers_soft(user_bufs)) &&
1161                         is_unprivileged_user()) {
1162                 ret = -EPERM;
1163                 goto out_revert_acct;
1164         }
1165
1166         /*
1167          * We can shrink the pipe, if arg is greater than the ring occupancy.
1168          * Since we don't expect a lot of shrink+grow operations, just free and
1169          * allocate again like we would do for growing.  If the pipe currently
1170          * contains more buffers than arg, then return busy.
1171          */
1172         mask = pipe->ring_size - 1;
1173         head = pipe->head;
1174         tail = pipe->tail;
1175         n = pipe_occupancy(pipe->head, pipe->tail);
1176         if (nr_slots < n) {
1177                 ret = -EBUSY;
1178                 goto out_revert_acct;
1179         }
1180
1181         bufs = kcalloc(nr_slots, sizeof(*bufs),
1182                        GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
1183         if (unlikely(!bufs)) {
1184                 ret = -ENOMEM;
1185                 goto out_revert_acct;
1186         }
1187
1188         /*
1189          * The pipe array wraps around, so just start the new one at zero
1190          * and adjust the indices.
1191          */
1192         if (n > 0) {
1193                 unsigned int h = head & mask;
1194                 unsigned int t = tail & mask;
1195                 if (h > t) {
1196                         memcpy(bufs, pipe->bufs + t,
1197                                n * sizeof(struct pipe_buffer));
1198                 } else {
1199                         unsigned int tsize = pipe->ring_size - t;
1200                         if (h > 0)
1201                                 memcpy(bufs + tsize, pipe->bufs,
1202                                        h * sizeof(struct pipe_buffer));
1203                         memcpy(bufs, pipe->bufs + t,
1204                                tsize * sizeof(struct pipe_buffer));
1205                 }
1206         }
1207
1208         head = n;
1209         tail = 0;
1210
1211         kfree(pipe->bufs);
1212         pipe->bufs = bufs;
1213         pipe->ring_size = nr_slots;
1214         pipe->max_usage = nr_slots;
1215         pipe->tail = tail;
1216         pipe->head = head;
1217         wake_up_interruptible_all(&pipe->wait);
1218         return pipe->max_usage * PAGE_SIZE;
1219
1220 out_revert_acct:
1221         (void) account_pipe_buffers(pipe->user, nr_slots, pipe->ring_size);
1222         return ret;
1223 }
1224
1225 /*
1226  * After the inode slimming patch, i_pipe/i_bdev/i_cdev share the same
1227  * location, so checking ->i_pipe is not enough to verify that this is a
1228  * pipe.
1229  */
1230 struct pipe_inode_info *get_pipe_info(struct file *file)
1231 {
1232         return file->f_op == &pipefifo_fops ? file->private_data : NULL;
1233 }
1234
1235 long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
1236 {
1237         struct pipe_inode_info *pipe;
1238         long ret;
1239
1240         pipe = get_pipe_info(file);
1241         if (!pipe)
1242                 return -EBADF;
1243
1244         __pipe_lock(pipe);
1245
1246         switch (cmd) {
1247         case F_SETPIPE_SZ:
1248                 ret = pipe_set_size(pipe, arg);
1249                 break;
1250         case F_GETPIPE_SZ:
1251                 ret = pipe->max_usage * PAGE_SIZE;
1252                 break;
1253         default:
1254                 ret = -EINVAL;
1255                 break;
1256         }
1257
1258         __pipe_unlock(pipe);
1259         return ret;
1260 }
1261
1262 static const struct super_operations pipefs_ops = {
1263         .destroy_inode = free_inode_nonrcu,
1264         .statfs = simple_statfs,
1265 };
1266
1267 /*
1268  * pipefs should _never_ be mounted by userland - too much of security hassle,
1269  * no real gain from having the whole whorehouse mounted. So we don't need
1270  * any operations on the root directory. However, we need a non-trivial
1271  * d_name - pipe: will go nicely and kill the special-casing in procfs.
1272  */
1273
1274 static int pipefs_init_fs_context(struct fs_context *fc)
1275 {
1276         struct pseudo_fs_context *ctx = init_pseudo(fc, PIPEFS_MAGIC);
1277         if (!ctx)
1278                 return -ENOMEM;
1279         ctx->ops = &pipefs_ops;
1280         ctx->dops = &pipefs_dentry_operations;
1281         return 0;
1282 }
1283
1284 static struct file_system_type pipe_fs_type = {
1285         .name           = "pipefs",
1286         .init_fs_context = pipefs_init_fs_context,
1287         .kill_sb        = kill_anon_super,
1288 };
1289
1290 static int __init init_pipe_fs(void)
1291 {
1292         int err = register_filesystem(&pipe_fs_type);
1293
1294         if (!err) {
1295                 pipe_mnt = kern_mount(&pipe_fs_type);
1296                 if (IS_ERR(pipe_mnt)) {
1297                         err = PTR_ERR(pipe_mnt);
1298                         unregister_filesystem(&pipe_fs_type);
1299                 }
1300         }
1301         return err;
1302 }
1303
1304 fs_initcall(init_pipe_fs);