pipe: Fix buffer offset after partially failed read
[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                         int offset;
399
400                         if (chars > total_len)
401                                 chars = total_len;
402
403                         error = ops->confirm(pipe, buf);
404                         if (error) {
405                                 if (!ret)
406                                         ret = error;
407                                 break;
408                         }
409
410                         atomic = !iov_fault_in_pages_write(iov, chars);
411                         remaining = chars;
412                         offset = buf->offset;
413 redo:
414                         addr = ops->map(pipe, buf, atomic);
415                         error = pipe_iov_copy_to_user(iov, addr, &offset,
416                                                       &remaining, atomic);
417                         ops->unmap(pipe, buf, addr);
418                         if (unlikely(error)) {
419                                 /*
420                                  * Just retry with the slow path if we failed.
421                                  */
422                                 if (atomic) {
423                                         atomic = 0;
424                                         goto redo;
425                                 }
426                                 if (!ret)
427                                         ret = error;
428                                 break;
429                         }
430                         ret += chars;
431                         buf->offset += chars;
432                         buf->len -= chars;
433
434                         /* Was it a packet buffer? Clean up and exit */
435                         if (buf->flags & PIPE_BUF_FLAG_PACKET) {
436                                 total_len = chars;
437                                 buf->len = 0;
438                         }
439
440                         if (!buf->len) {
441                                 buf->ops = NULL;
442                                 ops->release(pipe, buf);
443                                 curbuf = (curbuf + 1) & (pipe->buffers - 1);
444                                 pipe->curbuf = curbuf;
445                                 pipe->nrbufs = --bufs;
446                                 do_wakeup = 1;
447                         }
448                         total_len -= chars;
449                         if (!total_len)
450                                 break;  /* common path: read succeeded */
451                 }
452                 if (bufs)       /* More to do? */
453                         continue;
454                 if (!pipe->writers)
455                         break;
456                 if (!pipe->waiting_writers) {
457                         /* syscall merging: Usually we must not sleep
458                          * if O_NONBLOCK is set, or if we got some data.
459                          * But if a writer sleeps in kernel space, then
460                          * we can wait for that data without violating POSIX.
461                          */
462                         if (ret)
463                                 break;
464                         if (filp->f_flags & O_NONBLOCK) {
465                                 ret = -EAGAIN;
466                                 break;
467                         }
468                 }
469                 if (signal_pending(current)) {
470                         if (!ret)
471                                 ret = -ERESTARTSYS;
472                         break;
473                 }
474                 if (do_wakeup) {
475                         wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
476                         kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
477                 }
478                 pipe_wait(pipe);
479         }
480         mutex_unlock(&inode->i_mutex);
481
482         /* Signal writers asynchronously that there is more room. */
483         if (do_wakeup) {
484                 wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
485                 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
486         }
487         if (ret > 0)
488                 file_accessed(filp);
489         return ret;
490 }
491
492 static inline int is_packetized(struct file *file)
493 {
494         return (file->f_flags & O_DIRECT) != 0;
495 }
496
497 static ssize_t
498 pipe_write(struct kiocb *iocb, const struct iovec *_iov,
499             unsigned long nr_segs, loff_t ppos)
500 {
501         struct file *filp = iocb->ki_filp;
502         struct inode *inode = filp->f_path.dentry->d_inode;
503         struct pipe_inode_info *pipe;
504         ssize_t ret;
505         int do_wakeup;
506         struct iovec *iov = (struct iovec *)_iov;
507         size_t total_len;
508         ssize_t chars;
509
510         total_len = iov_length(iov, nr_segs);
511         /* Null write succeeds. */
512         if (unlikely(total_len == 0))
513                 return 0;
514
515         do_wakeup = 0;
516         ret = 0;
517         mutex_lock(&inode->i_mutex);
518         pipe = inode->i_pipe;
519
520         if (!pipe->readers) {
521                 send_sig(SIGPIPE, current, 0);
522                 ret = -EPIPE;
523                 goto out;
524         }
525
526         /* We try to merge small writes */
527         chars = total_len & (PAGE_SIZE-1); /* size of the last buffer */
528         if (pipe->nrbufs && chars != 0) {
529                 int lastbuf = (pipe->curbuf + pipe->nrbufs - 1) &
530                                                         (pipe->buffers - 1);
531                 struct pipe_buffer *buf = pipe->bufs + lastbuf;
532                 const struct pipe_buf_operations *ops = buf->ops;
533                 int offset = buf->offset + buf->len;
534
535                 if (ops->can_merge && offset + chars <= PAGE_SIZE) {
536                         int error, atomic = 1;
537                         void *addr;
538                         size_t remaining = chars;
539
540                         error = ops->confirm(pipe, buf);
541                         if (error)
542                                 goto out;
543
544                         iov_fault_in_pages_read(iov, chars);
545 redo1:
546                         addr = ops->map(pipe, buf, atomic);
547                         error = pipe_iov_copy_from_user(addr, &offset, iov,
548                                                         &remaining, atomic);
549                         ops->unmap(pipe, buf, addr);
550                         ret = error;
551                         do_wakeup = 1;
552                         if (error) {
553                                 if (atomic) {
554                                         atomic = 0;
555                                         goto redo1;
556                                 }
557                                 goto out;
558                         }
559                         buf->len += chars;
560                         total_len -= chars;
561                         ret = chars;
562                         if (!total_len)
563                                 goto out;
564                 }
565         }
566
567         for (;;) {
568                 int bufs;
569
570                 if (!pipe->readers) {
571                         send_sig(SIGPIPE, current, 0);
572                         if (!ret)
573                                 ret = -EPIPE;
574                         break;
575                 }
576                 bufs = pipe->nrbufs;
577                 if (bufs < pipe->buffers) {
578                         int newbuf = (pipe->curbuf + bufs) & (pipe->buffers-1);
579                         struct pipe_buffer *buf = pipe->bufs + newbuf;
580                         struct page *page = pipe->tmp_page;
581                         char *src;
582                         int error, atomic = 1;
583                         int offset = 0;
584                         size_t remaining;
585
586                         if (!page) {
587                                 page = alloc_page(GFP_HIGHUSER);
588                                 if (unlikely(!page)) {
589                                         ret = ret ? : -ENOMEM;
590                                         break;
591                                 }
592                                 pipe->tmp_page = page;
593                         }
594                         /* Always wake up, even if the copy fails. Otherwise
595                          * we lock up (O_NONBLOCK-)readers that sleep due to
596                          * syscall merging.
597                          * FIXME! Is this really true?
598                          */
599                         do_wakeup = 1;
600                         chars = PAGE_SIZE;
601                         if (chars > total_len)
602                                 chars = total_len;
603
604                         iov_fault_in_pages_read(iov, chars);
605                         remaining = chars;
606 redo2:
607                         if (atomic)
608                                 src = kmap_atomic(page, KM_USER0);
609                         else
610                                 src = kmap(page);
611
612                         error = pipe_iov_copy_from_user(src, &offset, iov,
613                                                         &remaining, atomic);
614                         if (atomic)
615                                 kunmap_atomic(src, KM_USER0);
616                         else
617                                 kunmap(page);
618
619                         if (unlikely(error)) {
620                                 if (atomic) {
621                                         atomic = 0;
622                                         goto redo2;
623                                 }
624                                 if (!ret)
625                                         ret = error;
626                                 break;
627                         }
628                         ret += chars;
629
630                         /* Insert it into the buffer array */
631                         buf->page = page;
632                         buf->ops = &anon_pipe_buf_ops;
633                         buf->offset = 0;
634                         buf->len = chars;
635                         buf->flags = 0;
636                         if (is_packetized(filp)) {
637                                 buf->ops = &packet_pipe_buf_ops;
638                                 buf->flags = PIPE_BUF_FLAG_PACKET;
639                         }
640                         pipe->nrbufs = ++bufs;
641                         pipe->tmp_page = NULL;
642
643                         total_len -= chars;
644                         if (!total_len)
645                                 break;
646                 }
647                 if (bufs < pipe->buffers)
648                         continue;
649                 if (filp->f_flags & O_NONBLOCK) {
650                         if (!ret)
651                                 ret = -EAGAIN;
652                         break;
653                 }
654                 if (signal_pending(current)) {
655                         if (!ret)
656                                 ret = -ERESTARTSYS;
657                         break;
658                 }
659                 if (do_wakeup) {
660                         wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM);
661                         kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
662                         do_wakeup = 0;
663                 }
664                 pipe->waiting_writers++;
665                 pipe_wait(pipe);
666                 pipe->waiting_writers--;
667         }
668 out:
669         mutex_unlock(&inode->i_mutex);
670         if (do_wakeup) {
671                 wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM);
672                 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
673         }
674         if (ret > 0)
675                 file_update_time(filp);
676         return ret;
677 }
678
679 static ssize_t
680 bad_pipe_r(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
681 {
682         return -EBADF;
683 }
684
685 static ssize_t
686 bad_pipe_w(struct file *filp, const char __user *buf, size_t count,
687            loff_t *ppos)
688 {
689         return -EBADF;
690 }
691
692 static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
693 {
694         struct inode *inode = filp->f_path.dentry->d_inode;
695         struct pipe_inode_info *pipe;
696         int count, buf, nrbufs;
697
698         switch (cmd) {
699                 case FIONREAD:
700                         mutex_lock(&inode->i_mutex);
701                         pipe = inode->i_pipe;
702                         count = 0;
703                         buf = pipe->curbuf;
704                         nrbufs = pipe->nrbufs;
705                         while (--nrbufs >= 0) {
706                                 count += pipe->bufs[buf].len;
707                                 buf = (buf+1) & (pipe->buffers - 1);
708                         }
709                         mutex_unlock(&inode->i_mutex);
710
711                         return put_user(count, (int __user *)arg);
712                 default:
713                         return -EINVAL;
714         }
715 }
716
717 /* No kernel lock held - fine */
718 static unsigned int
719 pipe_poll(struct file *filp, poll_table *wait)
720 {
721         unsigned int mask;
722         struct inode *inode = filp->f_path.dentry->d_inode;
723         struct pipe_inode_info *pipe = inode->i_pipe;
724         int nrbufs;
725
726         poll_wait(filp, &pipe->wait, wait);
727
728         /* Reading only -- no need for acquiring the semaphore.  */
729         nrbufs = pipe->nrbufs;
730         mask = 0;
731         if (filp->f_mode & FMODE_READ) {
732                 mask = (nrbufs > 0) ? POLLIN | POLLRDNORM : 0;
733                 if (!pipe->writers && filp->f_version != pipe->w_counter)
734                         mask |= POLLHUP;
735         }
736
737         if (filp->f_mode & FMODE_WRITE) {
738                 mask |= (nrbufs < pipe->buffers) ? POLLOUT | POLLWRNORM : 0;
739                 /*
740                  * Most Unices do not set POLLERR for FIFOs but on Linux they
741                  * behave exactly like pipes for poll().
742                  */
743                 if (!pipe->readers)
744                         mask |= POLLERR;
745         }
746
747         return mask;
748 }
749
750 static int
751 pipe_release(struct inode *inode, int decr, int decw)
752 {
753         struct pipe_inode_info *pipe;
754
755         mutex_lock(&inode->i_mutex);
756         pipe = inode->i_pipe;
757         pipe->readers -= decr;
758         pipe->writers -= decw;
759
760         if (!pipe->readers && !pipe->writers) {
761                 free_pipe_info(inode);
762         } else {
763                 wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM | POLLERR | POLLHUP);
764                 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
765                 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
766         }
767         mutex_unlock(&inode->i_mutex);
768
769         return 0;
770 }
771
772 static int
773 pipe_read_fasync(int fd, struct file *filp, int on)
774 {
775         struct inode *inode = filp->f_path.dentry->d_inode;
776         int retval;
777
778         mutex_lock(&inode->i_mutex);
779         retval = fasync_helper(fd, filp, on, &inode->i_pipe->fasync_readers);
780         mutex_unlock(&inode->i_mutex);
781
782         return retval;
783 }
784
785
786 static int
787 pipe_write_fasync(int fd, struct file *filp, int on)
788 {
789         struct inode *inode = filp->f_path.dentry->d_inode;
790         int retval;
791
792         mutex_lock(&inode->i_mutex);
793         retval = fasync_helper(fd, filp, on, &inode->i_pipe->fasync_writers);
794         mutex_unlock(&inode->i_mutex);
795
796         return retval;
797 }
798
799
800 static int
801 pipe_rdwr_fasync(int fd, struct file *filp, int on)
802 {
803         struct inode *inode = filp->f_path.dentry->d_inode;
804         struct pipe_inode_info *pipe = inode->i_pipe;
805         int retval;
806
807         mutex_lock(&inode->i_mutex);
808         retval = fasync_helper(fd, filp, on, &pipe->fasync_readers);
809         if (retval >= 0) {
810                 retval = fasync_helper(fd, filp, on, &pipe->fasync_writers);
811                 if (retval < 0) /* this can happen only if on == T */
812                         fasync_helper(-1, filp, 0, &pipe->fasync_readers);
813         }
814         mutex_unlock(&inode->i_mutex);
815         return retval;
816 }
817
818
819 static int
820 pipe_read_release(struct inode *inode, struct file *filp)
821 {
822         return pipe_release(inode, 1, 0);
823 }
824
825 static int
826 pipe_write_release(struct inode *inode, struct file *filp)
827 {
828         return pipe_release(inode, 0, 1);
829 }
830
831 static int
832 pipe_rdwr_release(struct inode *inode, struct file *filp)
833 {
834         int decr, decw;
835
836         decr = (filp->f_mode & FMODE_READ) != 0;
837         decw = (filp->f_mode & FMODE_WRITE) != 0;
838         return pipe_release(inode, decr, decw);
839 }
840
841 static int
842 pipe_read_open(struct inode *inode, struct file *filp)
843 {
844         int ret = -ENOENT;
845
846         mutex_lock(&inode->i_mutex);
847
848         if (inode->i_pipe) {
849                 ret = 0;
850                 inode->i_pipe->readers++;
851         }
852
853         mutex_unlock(&inode->i_mutex);
854
855         return ret;
856 }
857
858 static int
859 pipe_write_open(struct inode *inode, struct file *filp)
860 {
861         int ret = -ENOENT;
862
863         mutex_lock(&inode->i_mutex);
864
865         if (inode->i_pipe) {
866                 ret = 0;
867                 inode->i_pipe->writers++;
868         }
869
870         mutex_unlock(&inode->i_mutex);
871
872         return ret;
873 }
874
875 static int
876 pipe_rdwr_open(struct inode *inode, struct file *filp)
877 {
878         int ret = -ENOENT;
879
880         if (!(filp->f_mode & (FMODE_READ|FMODE_WRITE)))
881                 return -EINVAL;
882
883         mutex_lock(&inode->i_mutex);
884
885         if (inode->i_pipe) {
886                 ret = 0;
887                 if (filp->f_mode & FMODE_READ)
888                         inode->i_pipe->readers++;
889                 if (filp->f_mode & FMODE_WRITE)
890                         inode->i_pipe->writers++;
891         }
892
893         mutex_unlock(&inode->i_mutex);
894
895         return ret;
896 }
897
898 /*
899  * The file_operations structs are not static because they
900  * are also used in linux/fs/fifo.c to do operations on FIFOs.
901  *
902  * Pipes reuse fifos' file_operations structs.
903  */
904 const struct file_operations read_pipefifo_fops = {
905         .llseek         = no_llseek,
906         .read           = do_sync_read,
907         .aio_read       = pipe_read,
908         .write          = bad_pipe_w,
909         .poll           = pipe_poll,
910         .unlocked_ioctl = pipe_ioctl,
911         .open           = pipe_read_open,
912         .release        = pipe_read_release,
913         .fasync         = pipe_read_fasync,
914 };
915
916 const struct file_operations write_pipefifo_fops = {
917         .llseek         = no_llseek,
918         .read           = bad_pipe_r,
919         .write          = do_sync_write,
920         .aio_write      = pipe_write,
921         .poll           = pipe_poll,
922         .unlocked_ioctl = pipe_ioctl,
923         .open           = pipe_write_open,
924         .release        = pipe_write_release,
925         .fasync         = pipe_write_fasync,
926 };
927
928 const struct file_operations rdwr_pipefifo_fops = {
929         .llseek         = no_llseek,
930         .read           = do_sync_read,
931         .aio_read       = pipe_read,
932         .write          = do_sync_write,
933         .aio_write      = pipe_write,
934         .poll           = pipe_poll,
935         .unlocked_ioctl = pipe_ioctl,
936         .open           = pipe_rdwr_open,
937         .release        = pipe_rdwr_release,
938         .fasync         = pipe_rdwr_fasync,
939 };
940
941 static void account_pipe_buffers(struct pipe_inode_info *pipe,
942                                  unsigned long old, unsigned long new)
943 {
944         atomic_long_add(new - old, &pipe->user->pipe_bufs);
945 }
946
947 static bool too_many_pipe_buffers_soft(struct user_struct *user)
948 {
949         return pipe_user_pages_soft &&
950                atomic_long_read(&user->pipe_bufs) >= pipe_user_pages_soft;
951 }
952
953 static bool too_many_pipe_buffers_hard(struct user_struct *user)
954 {
955         return pipe_user_pages_hard &&
956                atomic_long_read(&user->pipe_bufs) >= pipe_user_pages_hard;
957 }
958
959 struct pipe_inode_info * alloc_pipe_info(struct inode *inode)
960 {
961         struct pipe_inode_info *pipe;
962
963         pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL);
964         if (pipe) {
965                 unsigned long pipe_bufs = PIPE_DEF_BUFFERS;
966                 struct user_struct *user = get_current_user();
967
968                 if (!too_many_pipe_buffers_hard(user)) {
969                         if (too_many_pipe_buffers_soft(user))
970                                 pipe_bufs = 1;
971                         pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * pipe_bufs, GFP_KERNEL);
972                 }
973
974                 if (pipe->bufs) {
975                         init_waitqueue_head(&pipe->wait);
976                         pipe->r_counter = pipe->w_counter = 1;
977                         pipe->inode = inode;
978                         pipe->buffers = pipe_bufs;
979                         pipe->user = user;
980                         account_pipe_buffers(pipe, 0, pipe_bufs);
981                         return pipe;
982                 }
983                 free_uid(user);
984                 kfree(pipe);
985         }
986
987         return NULL;
988 }
989
990 void __free_pipe_info(struct pipe_inode_info *pipe)
991 {
992         int i;
993
994         account_pipe_buffers(pipe, pipe->buffers, 0);
995         free_uid(pipe->user);
996         for (i = 0; i < pipe->buffers; i++) {
997                 struct pipe_buffer *buf = pipe->bufs + i;
998                 if (buf->ops)
999                         buf->ops->release(pipe, buf);
1000         }
1001         if (pipe->tmp_page)
1002                 __free_page(pipe->tmp_page);
1003         kfree(pipe->bufs);
1004         kfree(pipe);
1005 }
1006
1007 void free_pipe_info(struct inode *inode)
1008 {
1009         __free_pipe_info(inode->i_pipe);
1010         inode->i_pipe = NULL;
1011 }
1012
1013 static struct vfsmount *pipe_mnt __read_mostly;
1014
1015 /*
1016  * pipefs_dname() is called from d_path().
1017  */
1018 static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen)
1019 {
1020         return dynamic_dname(dentry, buffer, buflen, "pipe:[%lu]",
1021                                 dentry->d_inode->i_ino);
1022 }
1023
1024 static const struct dentry_operations pipefs_dentry_operations = {
1025         .d_dname        = pipefs_dname,
1026 };
1027
1028 static struct inode * get_pipe_inode(void)
1029 {
1030         struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb);
1031         struct pipe_inode_info *pipe;
1032
1033         if (!inode)
1034                 goto fail_inode;
1035
1036         inode->i_ino = get_next_ino();
1037
1038         pipe = alloc_pipe_info(inode);
1039         if (!pipe)
1040                 goto fail_iput;
1041         inode->i_pipe = pipe;
1042
1043         pipe->readers = pipe->writers = 1;
1044         inode->i_fop = &rdwr_pipefifo_fops;
1045
1046         /*
1047          * Mark the inode dirty from the very beginning,
1048          * that way it will never be moved to the dirty
1049          * list because "mark_inode_dirty()" will think
1050          * that it already _is_ on the dirty list.
1051          */
1052         inode->i_state = I_DIRTY;
1053         inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR;
1054         inode->i_uid = current_fsuid();
1055         inode->i_gid = current_fsgid();
1056         inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1057
1058         return inode;
1059
1060 fail_iput:
1061         iput(inode);
1062
1063 fail_inode:
1064         return NULL;
1065 }
1066
1067 struct file *create_write_pipe(int flags)
1068 {
1069         int err;
1070         struct inode *inode;
1071         struct file *f;
1072         struct path path;
1073         struct qstr name = { .name = "" };
1074
1075         err = -ENFILE;
1076         inode = get_pipe_inode();
1077         if (!inode)
1078                 goto err;
1079
1080         err = -ENOMEM;
1081         path.dentry = d_alloc_pseudo(pipe_mnt->mnt_sb, &name);
1082         if (!path.dentry)
1083                 goto err_inode;
1084         path.mnt = mntget(pipe_mnt);
1085
1086         d_instantiate(path.dentry, inode);
1087
1088         err = -ENFILE;
1089         f = alloc_file(&path, FMODE_WRITE, &write_pipefifo_fops);
1090         if (!f)
1091                 goto err_dentry;
1092         f->f_mapping = inode->i_mapping;
1093
1094         f->f_flags = O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT));
1095         f->f_version = 0;
1096
1097         return f;
1098
1099  err_dentry:
1100         free_pipe_info(inode);
1101         path_put(&path);
1102         return ERR_PTR(err);
1103
1104  err_inode:
1105         free_pipe_info(inode);
1106         iput(inode);
1107  err:
1108         return ERR_PTR(err);
1109 }
1110
1111 void free_write_pipe(struct file *f)
1112 {
1113         free_pipe_info(f->f_dentry->d_inode);
1114         path_put(&f->f_path);
1115         put_filp(f);
1116 }
1117
1118 struct file *create_read_pipe(struct file *wrf, int flags)
1119 {
1120         /* Grab pipe from the writer */
1121         struct file *f = alloc_file(&wrf->f_path, FMODE_READ,
1122                                     &read_pipefifo_fops);
1123         if (!f)
1124                 return ERR_PTR(-ENFILE);
1125
1126         path_get(&wrf->f_path);
1127         f->f_flags = O_RDONLY | (flags & O_NONBLOCK);
1128
1129         return f;
1130 }
1131
1132 int do_pipe_flags(int *fd, int flags)
1133 {
1134         struct file *fw, *fr;
1135         int error;
1136         int fdw, fdr;
1137
1138         if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT))
1139                 return -EINVAL;
1140
1141         fw = create_write_pipe(flags);
1142         if (IS_ERR(fw))
1143                 return PTR_ERR(fw);
1144         fr = create_read_pipe(fw, flags);
1145         error = PTR_ERR(fr);
1146         if (IS_ERR(fr))
1147                 goto err_write_pipe;
1148
1149         error = get_unused_fd_flags(flags);
1150         if (error < 0)
1151                 goto err_read_pipe;
1152         fdr = error;
1153
1154         error = get_unused_fd_flags(flags);
1155         if (error < 0)
1156                 goto err_fdr;
1157         fdw = error;
1158
1159         audit_fd_pair(fdr, fdw);
1160         fd_install(fdr, fr);
1161         fd_install(fdw, fw);
1162         fd[0] = fdr;
1163         fd[1] = fdw;
1164
1165         return 0;
1166
1167  err_fdr:
1168         put_unused_fd(fdr);
1169  err_read_pipe:
1170         path_put(&fr->f_path);
1171         put_filp(fr);
1172  err_write_pipe:
1173         free_write_pipe(fw);
1174         return error;
1175 }
1176
1177 /*
1178  * sys_pipe() is the normal C calling standard for creating
1179  * a pipe. It's not the way Unix traditionally does this, though.
1180  */
1181 SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags)
1182 {
1183         int fd[2];
1184         int error;
1185
1186         error = do_pipe_flags(fd, flags);
1187         if (!error) {
1188                 if (copy_to_user(fildes, fd, sizeof(fd))) {
1189                         sys_close(fd[0]);
1190                         sys_close(fd[1]);
1191                         error = -EFAULT;
1192                 }
1193         }
1194         return error;
1195 }
1196
1197 SYSCALL_DEFINE1(pipe, int __user *, fildes)
1198 {
1199         return sys_pipe2(fildes, 0);
1200 }
1201
1202 /*
1203  * Allocate a new array of pipe buffers and copy the info over. Returns the
1204  * pipe size if successful, or return -ERROR on error.
1205  */
1206 static long pipe_set_size(struct pipe_inode_info *pipe, unsigned long nr_pages)
1207 {
1208         struct pipe_buffer *bufs;
1209
1210         /*
1211          * We can shrink the pipe, if arg >= pipe->nrbufs. Since we don't
1212          * expect a lot of shrink+grow operations, just free and allocate
1213          * again like we would do for growing. If the pipe currently
1214          * contains more buffers than arg, then return busy.
1215          */
1216         if (nr_pages < pipe->nrbufs)
1217                 return -EBUSY;
1218
1219         bufs = kcalloc(nr_pages, sizeof(struct pipe_buffer), GFP_KERNEL);
1220         if (unlikely(!bufs))
1221                 return -ENOMEM;
1222
1223         /*
1224          * The pipe array wraps around, so just start the new one at zero
1225          * and adjust the indexes.
1226          */
1227         if (pipe->nrbufs) {
1228                 unsigned int tail;
1229                 unsigned int head;
1230
1231                 tail = pipe->curbuf + pipe->nrbufs;
1232                 if (tail < pipe->buffers)
1233                         tail = 0;
1234                 else
1235                         tail &= (pipe->buffers - 1);
1236
1237                 head = pipe->nrbufs - tail;
1238                 if (head)
1239                         memcpy(bufs, pipe->bufs + pipe->curbuf, head * sizeof(struct pipe_buffer));
1240                 if (tail)
1241                         memcpy(bufs + head, pipe->bufs, tail * sizeof(struct pipe_buffer));
1242         }
1243
1244         account_pipe_buffers(pipe, pipe->buffers, nr_pages);
1245         pipe->curbuf = 0;
1246         kfree(pipe->bufs);
1247         pipe->bufs = bufs;
1248         pipe->buffers = nr_pages;
1249         return nr_pages * PAGE_SIZE;
1250 }
1251
1252 /*
1253  * Currently we rely on the pipe array holding a power-of-2 number
1254  * of pages.
1255  */
1256 static inline unsigned int round_pipe_size(unsigned int size)
1257 {
1258         unsigned long nr_pages;
1259
1260         nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1261         return roundup_pow_of_two(nr_pages) << PAGE_SHIFT;
1262 }
1263
1264 /*
1265  * This should work even if CONFIG_PROC_FS isn't set, as proc_dointvec_minmax
1266  * will return an error.
1267  */
1268 int pipe_proc_fn(struct ctl_table *table, int write, void __user *buf,
1269                  size_t *lenp, loff_t *ppos)
1270 {
1271         int ret;
1272
1273         ret = proc_dointvec_minmax(table, write, buf, lenp, ppos);
1274         if (ret < 0 || !write)
1275                 return ret;
1276
1277         pipe_max_size = round_pipe_size(pipe_max_size);
1278         return ret;
1279 }
1280
1281 /*
1282  * After the inode slimming patch, i_pipe/i_bdev/i_cdev share the same
1283  * location, so checking ->i_pipe is not enough to verify that this is a
1284  * pipe.
1285  */
1286 struct pipe_inode_info *get_pipe_info(struct file *file)
1287 {
1288         struct inode *i = file->f_path.dentry->d_inode;
1289
1290         return S_ISFIFO(i->i_mode) ? i->i_pipe : NULL;
1291 }
1292
1293 long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
1294 {
1295         struct pipe_inode_info *pipe;
1296         long ret;
1297
1298         pipe = get_pipe_info(file);
1299         if (!pipe)
1300                 return -EBADF;
1301
1302         mutex_lock(&pipe->inode->i_mutex);
1303
1304         switch (cmd) {
1305         case F_SETPIPE_SZ: {
1306                 unsigned int size, nr_pages;
1307
1308                 size = round_pipe_size(arg);
1309                 nr_pages = size >> PAGE_SHIFT;
1310
1311                 ret = -EINVAL;
1312                 if (!nr_pages)
1313                         goto out;
1314
1315                 if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) {
1316                         ret = -EPERM;
1317                         goto out;
1318                 } else if ((too_many_pipe_buffers_hard(pipe->user) ||
1319                             too_many_pipe_buffers_soft(pipe->user)) &&
1320                            !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
1321                         ret = -EPERM;
1322                         goto out;
1323                 }
1324                 ret = pipe_set_size(pipe, nr_pages);
1325                 break;
1326                 }
1327         case F_GETPIPE_SZ:
1328                 ret = pipe->buffers * PAGE_SIZE;
1329                 break;
1330         default:
1331                 ret = -EINVAL;
1332                 break;
1333         }
1334
1335 out:
1336         mutex_unlock(&pipe->inode->i_mutex);
1337         return ret;
1338 }
1339
1340 static const struct super_operations pipefs_ops = {
1341         .destroy_inode = free_inode_nonrcu,
1342         .statfs = simple_statfs,
1343 };
1344
1345 /*
1346  * pipefs should _never_ be mounted by userland - too much of security hassle,
1347  * no real gain from having the whole whorehouse mounted. So we don't need
1348  * any operations on the root directory. However, we need a non-trivial
1349  * d_name - pipe: will go nicely and kill the special-casing in procfs.
1350  */
1351 static struct dentry *pipefs_mount(struct file_system_type *fs_type,
1352                          int flags, const char *dev_name, void *data)
1353 {
1354         return mount_pseudo(fs_type, "pipe:", &pipefs_ops,
1355                         &pipefs_dentry_operations, PIPEFS_MAGIC);
1356 }
1357
1358 static struct file_system_type pipe_fs_type = {
1359         .name           = "pipefs",
1360         .mount          = pipefs_mount,
1361         .kill_sb        = kill_anon_super,
1362 };
1363
1364 static int __init init_pipe_fs(void)
1365 {
1366         int err = register_filesystem(&pipe_fs_type);
1367
1368         if (!err) {
1369                 pipe_mnt = kern_mount(&pipe_fs_type);
1370                 if (IS_ERR(pipe_mnt)) {
1371                         err = PTR_ERR(pipe_mnt);
1372                         unregister_filesystem(&pipe_fs_type);
1373                 }
1374         }
1375         return err;
1376 }
1377
1378 static void __exit exit_pipe_fs(void)
1379 {
1380         kern_unmount(pipe_mnt);
1381         unregister_filesystem(&pipe_fs_type);
1382 }
1383
1384 fs_initcall(init_pipe_fs);
1385 module_exit(exit_pipe_fs);