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