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