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