pipe: allow passing around of ops private pointer
[safe/jmp/linux-2.6] / fs / splice.c
1 /*
2  * "splice": joining two ropes together by interweaving their strands.
3  *
4  * This is the "extended pipe" functionality, where a pipe is used as
5  * an arbitrary in-memory buffer. Think of a pipe as a small kernel
6  * buffer that you can use to transfer data from one end to the other.
7  *
8  * The traditional unix read/write is extended with a "splice()" operation
9  * that transfers data buffers to or from a pipe buffer.
10  *
11  * Named by Larry McVoy, original implementation from Linus, extended by
12  * Jens to support splicing to files, network, direct splicing, etc and
13  * fixing lots of bugs.
14  *
15  * Copyright (C) 2005-2006 Jens Axboe <axboe@kernel.dk>
16  * Copyright (C) 2005-2006 Linus Torvalds <torvalds@osdl.org>
17  * Copyright (C) 2006 Ingo Molnar <mingo@elte.hu>
18  *
19  */
20 #include <linux/fs.h>
21 #include <linux/file.h>
22 #include <linux/pagemap.h>
23 #include <linux/splice.h>
24 #include <linux/mm_inline.h>
25 #include <linux/swap.h>
26 #include <linux/writeback.h>
27 #include <linux/buffer_head.h>
28 #include <linux/module.h>
29 #include <linux/syscalls.h>
30 #include <linux/uio.h>
31
32 /*
33  * Attempt to steal a page from a pipe buffer. This should perhaps go into
34  * a vm helper function, it's already simplified quite a bit by the
35  * addition of remove_mapping(). If success is returned, the caller may
36  * attempt to reuse this page for another destination.
37  */
38 static int page_cache_pipe_buf_steal(struct pipe_inode_info *pipe,
39                                      struct pipe_buffer *buf)
40 {
41         struct page *page = buf->page;
42         struct address_space *mapping;
43
44         lock_page(page);
45
46         mapping = page_mapping(page);
47         if (mapping) {
48                 WARN_ON(!PageUptodate(page));
49
50                 /*
51                  * At least for ext2 with nobh option, we need to wait on
52                  * writeback completing on this page, since we'll remove it
53                  * from the pagecache.  Otherwise truncate wont wait on the
54                  * page, allowing the disk blocks to be reused by someone else
55                  * before we actually wrote our data to them. fs corruption
56                  * ensues.
57                  */
58                 wait_on_page_writeback(page);
59
60                 if (PagePrivate(page))
61                         try_to_release_page(page, GFP_KERNEL);
62
63                 /*
64                  * If we succeeded in removing the mapping, set LRU flag
65                  * and return good.
66                  */
67                 if (remove_mapping(mapping, page)) {
68                         buf->flags |= PIPE_BUF_FLAG_LRU;
69                         return 0;
70                 }
71         }
72
73         /*
74          * Raced with truncate or failed to remove page from current
75          * address space, unlock and return failure.
76          */
77         unlock_page(page);
78         return 1;
79 }
80
81 static void page_cache_pipe_buf_release(struct pipe_inode_info *pipe,
82                                         struct pipe_buffer *buf)
83 {
84         page_cache_release(buf->page);
85         buf->flags &= ~PIPE_BUF_FLAG_LRU;
86 }
87
88 static int page_cache_pipe_buf_pin(struct pipe_inode_info *pipe,
89                                    struct pipe_buffer *buf)
90 {
91         struct page *page = buf->page;
92         int err;
93
94         if (!PageUptodate(page)) {
95                 lock_page(page);
96
97                 /*
98                  * Page got truncated/unhashed. This will cause a 0-byte
99                  * splice, if this is the first page.
100                  */
101                 if (!page->mapping) {
102                         err = -ENODATA;
103                         goto error;
104                 }
105
106                 /*
107                  * Uh oh, read-error from disk.
108                  */
109                 if (!PageUptodate(page)) {
110                         err = -EIO;
111                         goto error;
112                 }
113
114                 /*
115                  * Page is ok afterall, we are done.
116                  */
117                 unlock_page(page);
118         }
119
120         return 0;
121 error:
122         unlock_page(page);
123         return err;
124 }
125
126 static const struct pipe_buf_operations page_cache_pipe_buf_ops = {
127         .can_merge = 0,
128         .map = generic_pipe_buf_map,
129         .unmap = generic_pipe_buf_unmap,
130         .pin = page_cache_pipe_buf_pin,
131         .release = page_cache_pipe_buf_release,
132         .steal = page_cache_pipe_buf_steal,
133         .get = generic_pipe_buf_get,
134 };
135
136 static int user_page_pipe_buf_steal(struct pipe_inode_info *pipe,
137                                     struct pipe_buffer *buf)
138 {
139         if (!(buf->flags & PIPE_BUF_FLAG_GIFT))
140                 return 1;
141
142         buf->flags |= PIPE_BUF_FLAG_LRU;
143         return generic_pipe_buf_steal(pipe, buf);
144 }
145
146 static const struct pipe_buf_operations user_page_pipe_buf_ops = {
147         .can_merge = 0,
148         .map = generic_pipe_buf_map,
149         .unmap = generic_pipe_buf_unmap,
150         .pin = generic_pipe_buf_pin,
151         .release = page_cache_pipe_buf_release,
152         .steal = user_page_pipe_buf_steal,
153         .get = generic_pipe_buf_get,
154 };
155
156 /*
157  * Pipe output worker. This fills a pipe with the information contained
158  * from splice_pipe_desc().
159  */
160 ssize_t splice_to_pipe(struct pipe_inode_info *pipe,
161                        struct splice_pipe_desc *spd)
162 {
163         unsigned int spd_pages = spd->nr_pages;
164         int ret, do_wakeup, page_nr;
165
166         ret = 0;
167         do_wakeup = 0;
168         page_nr = 0;
169
170         if (pipe->inode)
171                 mutex_lock(&pipe->inode->i_mutex);
172
173         for (;;) {
174                 if (!pipe->readers) {
175                         send_sig(SIGPIPE, current, 0);
176                         if (!ret)
177                                 ret = -EPIPE;
178                         break;
179                 }
180
181                 if (pipe->nrbufs < PIPE_BUFFERS) {
182                         int newbuf = (pipe->curbuf + pipe->nrbufs) & (PIPE_BUFFERS - 1);
183                         struct pipe_buffer *buf = pipe->bufs + newbuf;
184
185                         buf->page = spd->pages[page_nr];
186                         buf->offset = spd->partial[page_nr].offset;
187                         buf->len = spd->partial[page_nr].len;
188                         buf->private = spd->partial[page_nr].private;
189                         buf->ops = spd->ops;
190                         if (spd->flags & SPLICE_F_GIFT)
191                                 buf->flags |= PIPE_BUF_FLAG_GIFT;
192
193                         pipe->nrbufs++;
194                         page_nr++;
195                         ret += buf->len;
196
197                         if (pipe->inode)
198                                 do_wakeup = 1;
199
200                         if (!--spd->nr_pages)
201                                 break;
202                         if (pipe->nrbufs < PIPE_BUFFERS)
203                                 continue;
204
205                         break;
206                 }
207
208                 if (spd->flags & SPLICE_F_NONBLOCK) {
209                         if (!ret)
210                                 ret = -EAGAIN;
211                         break;
212                 }
213
214                 if (signal_pending(current)) {
215                         if (!ret)
216                                 ret = -ERESTARTSYS;
217                         break;
218                 }
219
220                 if (do_wakeup) {
221                         smp_mb();
222                         if (waitqueue_active(&pipe->wait))
223                                 wake_up_interruptible_sync(&pipe->wait);
224                         kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
225                         do_wakeup = 0;
226                 }
227
228                 pipe->waiting_writers++;
229                 pipe_wait(pipe);
230                 pipe->waiting_writers--;
231         }
232
233         if (pipe->inode) {
234                 mutex_unlock(&pipe->inode->i_mutex);
235
236                 if (do_wakeup) {
237                         smp_mb();
238                         if (waitqueue_active(&pipe->wait))
239                                 wake_up_interruptible(&pipe->wait);
240                         kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
241                 }
242         }
243
244         while (page_nr < spd_pages)
245                 page_cache_release(spd->pages[page_nr++]);
246
247         return ret;
248 }
249
250 static int
251 __generic_file_splice_read(struct file *in, loff_t *ppos,
252                            struct pipe_inode_info *pipe, size_t len,
253                            unsigned int flags)
254 {
255         struct address_space *mapping = in->f_mapping;
256         unsigned int loff, nr_pages;
257         struct page *pages[PIPE_BUFFERS];
258         struct partial_page partial[PIPE_BUFFERS];
259         struct page *page;
260         pgoff_t index, end_index;
261         loff_t isize;
262         int error, page_nr;
263         struct splice_pipe_desc spd = {
264                 .pages = pages,
265                 .partial = partial,
266                 .flags = flags,
267                 .ops = &page_cache_pipe_buf_ops,
268         };
269
270         index = *ppos >> PAGE_CACHE_SHIFT;
271         loff = *ppos & ~PAGE_CACHE_MASK;
272         nr_pages = (len + loff + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
273
274         if (nr_pages > PIPE_BUFFERS)
275                 nr_pages = PIPE_BUFFERS;
276
277         /*
278          * Don't try to 2nd guess the read-ahead logic, call into
279          * page_cache_readahead() like the page cache reads would do.
280          */
281         page_cache_readahead(mapping, &in->f_ra, in, index, nr_pages);
282
283         /*
284          * Now fill in the holes:
285          */
286         error = 0;
287
288         /*
289          * Lookup the (hopefully) full range of pages we need.
290          */
291         spd.nr_pages = find_get_pages_contig(mapping, index, nr_pages, pages);
292
293         /*
294          * If find_get_pages_contig() returned fewer pages than we needed,
295          * allocate the rest.
296          */
297         index += spd.nr_pages;
298         while (spd.nr_pages < nr_pages) {
299                 /*
300                  * Page could be there, find_get_pages_contig() breaks on
301                  * the first hole.
302                  */
303                 page = find_get_page(mapping, index);
304                 if (!page) {
305                         /*
306                          * Make sure the read-ahead engine is notified
307                          * about this failure.
308                          */
309                         handle_ra_miss(mapping, &in->f_ra, index);
310
311                         /*
312                          * page didn't exist, allocate one.
313                          */
314                         page = page_cache_alloc_cold(mapping);
315                         if (!page)
316                                 break;
317
318                         error = add_to_page_cache_lru(page, mapping, index,
319                                               GFP_KERNEL);
320                         if (unlikely(error)) {
321                                 page_cache_release(page);
322                                 if (error == -EEXIST)
323                                         continue;
324                                 break;
325                         }
326                         /*
327                          * add_to_page_cache() locks the page, unlock it
328                          * to avoid convoluting the logic below even more.
329                          */
330                         unlock_page(page);
331                 }
332
333                 pages[spd.nr_pages++] = page;
334                 index++;
335         }
336
337         /*
338          * Now loop over the map and see if we need to start IO on any
339          * pages, fill in the partial map, etc.
340          */
341         index = *ppos >> PAGE_CACHE_SHIFT;
342         nr_pages = spd.nr_pages;
343         spd.nr_pages = 0;
344         for (page_nr = 0; page_nr < nr_pages; page_nr++) {
345                 unsigned int this_len;
346
347                 if (!len)
348                         break;
349
350                 /*
351                  * this_len is the max we'll use from this page
352                  */
353                 this_len = min_t(unsigned long, len, PAGE_CACHE_SIZE - loff);
354                 page = pages[page_nr];
355
356                 /*
357                  * If the page isn't uptodate, we may need to start io on it
358                  */
359                 if (!PageUptodate(page)) {
360                         /*
361                          * If in nonblock mode then dont block on waiting
362                          * for an in-flight io page
363                          */
364                         if (flags & SPLICE_F_NONBLOCK) {
365                                 if (TestSetPageLocked(page))
366                                         break;
367                         } else
368                                 lock_page(page);
369
370                         /*
371                          * page was truncated, stop here. if this isn't the
372                          * first page, we'll just complete what we already
373                          * added
374                          */
375                         if (!page->mapping) {
376                                 unlock_page(page);
377                                 break;
378                         }
379                         /*
380                          * page was already under io and is now done, great
381                          */
382                         if (PageUptodate(page)) {
383                                 unlock_page(page);
384                                 goto fill_it;
385                         }
386
387                         /*
388                          * need to read in the page
389                          */
390                         error = mapping->a_ops->readpage(in, page);
391                         if (unlikely(error)) {
392                                 /*
393                                  * We really should re-lookup the page here,
394                                  * but it complicates things a lot. Instead
395                                  * lets just do what we already stored, and
396                                  * we'll get it the next time we are called.
397                                  */
398                                 if (error == AOP_TRUNCATED_PAGE)
399                                         error = 0;
400
401                                 break;
402                         }
403                 }
404 fill_it:
405                 /*
406                  * i_size must be checked after PageUptodate.
407                  */
408                 isize = i_size_read(mapping->host);
409                 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
410                 if (unlikely(!isize || index > end_index))
411                         break;
412
413                 /*
414                  * if this is the last page, see if we need to shrink
415                  * the length and stop
416                  */
417                 if (end_index == index) {
418                         unsigned int plen;
419
420                         /*
421                          * max good bytes in this page
422                          */
423                         plen = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
424                         if (plen <= loff)
425                                 break;
426
427                         /*
428                          * force quit after adding this page
429                          */
430                         this_len = min(this_len, plen - loff);
431                         len = this_len;
432                 }
433
434                 partial[page_nr].offset = loff;
435                 partial[page_nr].len = this_len;
436                 len -= this_len;
437                 loff = 0;
438                 spd.nr_pages++;
439                 index++;
440         }
441
442         /*
443          * Release any pages at the end, if we quit early. 'page_nr' is how far
444          * we got, 'nr_pages' is how many pages are in the map.
445          */
446         while (page_nr < nr_pages)
447                 page_cache_release(pages[page_nr++]);
448
449         if (spd.nr_pages)
450                 return splice_to_pipe(pipe, &spd);
451
452         return error;
453 }
454
455 /**
456  * generic_file_splice_read - splice data from file to a pipe
457  * @in:         file to splice from
458  * @pipe:       pipe to splice to
459  * @len:        number of bytes to splice
460  * @flags:      splice modifier flags
461  *
462  * Will read pages from given file and fill them into a pipe.
463  */
464 ssize_t generic_file_splice_read(struct file *in, loff_t *ppos,
465                                  struct pipe_inode_info *pipe, size_t len,
466                                  unsigned int flags)
467 {
468         ssize_t spliced;
469         int ret;
470         loff_t isize, left;
471
472         isize = i_size_read(in->f_mapping->host);
473         if (unlikely(*ppos >= isize))
474                 return 0;
475
476         left = isize - *ppos;
477         if (unlikely(left < len))
478                 len = left;
479
480         ret = 0;
481         spliced = 0;
482         while (len) {
483                 ret = __generic_file_splice_read(in, ppos, pipe, len, flags);
484
485                 if (ret < 0)
486                         break;
487                 else if (!ret) {
488                         if (spliced)
489                                 break;
490                         if (flags & SPLICE_F_NONBLOCK) {
491                                 ret = -EAGAIN;
492                                 break;
493                         }
494                 }
495
496                 *ppos += ret;
497                 len -= ret;
498                 spliced += ret;
499         }
500
501         if (spliced)
502                 return spliced;
503
504         return ret;
505 }
506
507 EXPORT_SYMBOL(generic_file_splice_read);
508
509 /*
510  * Send 'sd->len' bytes to socket from 'sd->file' at position 'sd->pos'
511  * using sendpage(). Return the number of bytes sent.
512  */
513 static int pipe_to_sendpage(struct pipe_inode_info *pipe,
514                             struct pipe_buffer *buf, struct splice_desc *sd)
515 {
516         struct file *file = sd->u.file;
517         loff_t pos = sd->pos;
518         int ret, more;
519
520         ret = buf->ops->pin(pipe, buf);
521         if (!ret) {
522                 more = (sd->flags & SPLICE_F_MORE) || sd->len < sd->total_len;
523
524                 ret = file->f_op->sendpage(file, buf->page, buf->offset,
525                                            sd->len, &pos, more);
526         }
527
528         return ret;
529 }
530
531 /*
532  * This is a little more tricky than the file -> pipe splicing. There are
533  * basically three cases:
534  *
535  *      - Destination page already exists in the address space and there
536  *        are users of it. For that case we have no other option that
537  *        copying the data. Tough luck.
538  *      - Destination page already exists in the address space, but there
539  *        are no users of it. Make sure it's uptodate, then drop it. Fall
540  *        through to last case.
541  *      - Destination page does not exist, we can add the pipe page to
542  *        the page cache and avoid the copy.
543  *
544  * If asked to move pages to the output file (SPLICE_F_MOVE is set in
545  * sd->flags), we attempt to migrate pages from the pipe to the output
546  * file address space page cache. This is possible if no one else has
547  * the pipe page referenced outside of the pipe and page cache. If
548  * SPLICE_F_MOVE isn't set, or we cannot move the page, we simply create
549  * a new page in the output file page cache and fill/dirty that.
550  */
551 static int pipe_to_file(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
552                         struct splice_desc *sd)
553 {
554         struct file *file = sd->u.file;
555         struct address_space *mapping = file->f_mapping;
556         unsigned int offset, this_len;
557         struct page *page;
558         pgoff_t index;
559         int ret;
560
561         /*
562          * make sure the data in this buffer is uptodate
563          */
564         ret = buf->ops->pin(pipe, buf);
565         if (unlikely(ret))
566                 return ret;
567
568         index = sd->pos >> PAGE_CACHE_SHIFT;
569         offset = sd->pos & ~PAGE_CACHE_MASK;
570
571         this_len = sd->len;
572         if (this_len + offset > PAGE_CACHE_SIZE)
573                 this_len = PAGE_CACHE_SIZE - offset;
574
575 find_page:
576         page = find_lock_page(mapping, index);
577         if (!page) {
578                 ret = -ENOMEM;
579                 page = page_cache_alloc_cold(mapping);
580                 if (unlikely(!page))
581                         goto out_ret;
582
583                 /*
584                  * This will also lock the page
585                  */
586                 ret = add_to_page_cache_lru(page, mapping, index,
587                                             GFP_KERNEL);
588                 if (unlikely(ret))
589                         goto out;
590         }
591
592         ret = mapping->a_ops->prepare_write(file, page, offset, offset+this_len);
593         if (unlikely(ret)) {
594                 loff_t isize = i_size_read(mapping->host);
595
596                 if (ret != AOP_TRUNCATED_PAGE)
597                         unlock_page(page);
598                 page_cache_release(page);
599                 if (ret == AOP_TRUNCATED_PAGE)
600                         goto find_page;
601
602                 /*
603                  * prepare_write() may have instantiated a few blocks
604                  * outside i_size.  Trim these off again.
605                  */
606                 if (sd->pos + this_len > isize)
607                         vmtruncate(mapping->host, isize);
608
609                 goto out_ret;
610         }
611
612         if (buf->page != page) {
613                 /*
614                  * Careful, ->map() uses KM_USER0!
615                  */
616                 char *src = buf->ops->map(pipe, buf, 1);
617                 char *dst = kmap_atomic(page, KM_USER1);
618
619                 memcpy(dst + offset, src + buf->offset, this_len);
620                 flush_dcache_page(page);
621                 kunmap_atomic(dst, KM_USER1);
622                 buf->ops->unmap(pipe, buf, src);
623         }
624
625         ret = mapping->a_ops->commit_write(file, page, offset, offset+this_len);
626         if (ret) {
627                 if (ret == AOP_TRUNCATED_PAGE) {
628                         page_cache_release(page);
629                         goto find_page;
630                 }
631                 if (ret < 0)
632                         goto out;
633                 /*
634                  * Partial write has happened, so 'ret' already initialized by
635                  * number of bytes written, Where is nothing we have to do here.
636                  */
637         } else
638                 ret = this_len;
639         /*
640          * Return the number of bytes written and mark page as
641          * accessed, we are now done!
642          */
643         mark_page_accessed(page);
644 out:
645         page_cache_release(page);
646         unlock_page(page);
647 out_ret:
648         return ret;
649 }
650
651 /*
652  * Pipe input worker. Most of this logic works like a regular pipe, the
653  * key here is the 'actor' worker passed in that actually moves the data
654  * to the wanted destination. See pipe_to_file/pipe_to_sendpage above.
655  */
656 ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
657                            splice_actor *actor)
658 {
659         int ret, do_wakeup, err;
660
661         ret = 0;
662         do_wakeup = 0;
663
664         for (;;) {
665                 if (pipe->nrbufs) {
666                         struct pipe_buffer *buf = pipe->bufs + pipe->curbuf;
667                         const struct pipe_buf_operations *ops = buf->ops;
668
669                         sd->len = buf->len;
670                         if (sd->len > sd->total_len)
671                                 sd->len = sd->total_len;
672
673                         err = actor(pipe, buf, sd);
674                         if (err <= 0) {
675                                 if (!ret && err != -ENODATA)
676                                         ret = err;
677
678                                 break;
679                         }
680
681                         ret += err;
682                         buf->offset += err;
683                         buf->len -= err;
684
685                         sd->len -= err;
686                         sd->pos += err;
687                         sd->total_len -= err;
688                         if (sd->len)
689                                 continue;
690
691                         if (!buf->len) {
692                                 buf->ops = NULL;
693                                 ops->release(pipe, buf);
694                                 pipe->curbuf = (pipe->curbuf + 1) & (PIPE_BUFFERS - 1);
695                                 pipe->nrbufs--;
696                                 if (pipe->inode)
697                                         do_wakeup = 1;
698                         }
699
700                         if (!sd->total_len)
701                                 break;
702                 }
703
704                 if (pipe->nrbufs)
705                         continue;
706                 if (!pipe->writers)
707                         break;
708                 if (!pipe->waiting_writers) {
709                         if (ret)
710                                 break;
711                 }
712
713                 if (sd->flags & SPLICE_F_NONBLOCK) {
714                         if (!ret)
715                                 ret = -EAGAIN;
716                         break;
717                 }
718
719                 if (signal_pending(current)) {
720                         if (!ret)
721                                 ret = -ERESTARTSYS;
722                         break;
723                 }
724
725                 if (do_wakeup) {
726                         smp_mb();
727                         if (waitqueue_active(&pipe->wait))
728                                 wake_up_interruptible_sync(&pipe->wait);
729                         kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
730                         do_wakeup = 0;
731                 }
732
733                 pipe_wait(pipe);
734         }
735
736         if (do_wakeup) {
737                 smp_mb();
738                 if (waitqueue_active(&pipe->wait))
739                         wake_up_interruptible(&pipe->wait);
740                 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
741         }
742
743         return ret;
744 }
745 EXPORT_SYMBOL(__splice_from_pipe);
746
747 ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
748                          loff_t *ppos, size_t len, unsigned int flags,
749                          splice_actor *actor)
750 {
751         ssize_t ret;
752         struct inode *inode = out->f_mapping->host;
753         struct splice_desc sd = {
754                 .total_len = len,
755                 .flags = flags,
756                 .pos = *ppos,
757                 .u.file = out,
758         };
759
760         /*
761          * The actor worker might be calling ->prepare_write and
762          * ->commit_write. Most of the time, these expect i_mutex to
763          * be held. Since this may result in an ABBA deadlock with
764          * pipe->inode, we have to order lock acquiry here.
765          */
766         inode_double_lock(inode, pipe->inode);
767         ret = __splice_from_pipe(pipe, &sd, actor);
768         inode_double_unlock(inode, pipe->inode);
769
770         return ret;
771 }
772
773 /**
774  * generic_file_splice_write_nolock - generic_file_splice_write without mutexes
775  * @pipe:       pipe info
776  * @out:        file to write to
777  * @len:        number of bytes to splice
778  * @flags:      splice modifier flags
779  *
780  * Will either move or copy pages (determined by @flags options) from
781  * the given pipe inode to the given file. The caller is responsible
782  * for acquiring i_mutex on both inodes.
783  *
784  */
785 ssize_t
786 generic_file_splice_write_nolock(struct pipe_inode_info *pipe, struct file *out,
787                                  loff_t *ppos, size_t len, unsigned int flags)
788 {
789         struct address_space *mapping = out->f_mapping;
790         struct inode *inode = mapping->host;
791         struct splice_desc sd = {
792                 .total_len = len,
793                 .flags = flags,
794                 .pos = *ppos,
795                 .u.file = out,
796         };
797         ssize_t ret;
798         int err;
799
800         err = remove_suid(out->f_path.dentry);
801         if (unlikely(err))
802                 return err;
803
804         ret = __splice_from_pipe(pipe, &sd, pipe_to_file);
805         if (ret > 0) {
806                 unsigned long nr_pages;
807
808                 *ppos += ret;
809                 nr_pages = (ret + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
810
811                 /*
812                  * If file or inode is SYNC and we actually wrote some data,
813                  * sync it.
814                  */
815                 if (unlikely((out->f_flags & O_SYNC) || IS_SYNC(inode))) {
816                         err = generic_osync_inode(inode, mapping,
817                                                   OSYNC_METADATA|OSYNC_DATA);
818
819                         if (err)
820                                 ret = err;
821                 }
822                 balance_dirty_pages_ratelimited_nr(mapping, nr_pages);
823         }
824
825         return ret;
826 }
827
828 EXPORT_SYMBOL(generic_file_splice_write_nolock);
829
830 /**
831  * generic_file_splice_write - splice data from a pipe to a file
832  * @pipe:       pipe info
833  * @out:        file to write to
834  * @len:        number of bytes to splice
835  * @flags:      splice modifier flags
836  *
837  * Will either move or copy pages (determined by @flags options) from
838  * the given pipe inode to the given file.
839  *
840  */
841 ssize_t
842 generic_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
843                           loff_t *ppos, size_t len, unsigned int flags)
844 {
845         struct address_space *mapping = out->f_mapping;
846         struct inode *inode = mapping->host;
847         ssize_t ret;
848         int err;
849
850         err = should_remove_suid(out->f_path.dentry);
851         if (unlikely(err)) {
852                 mutex_lock(&inode->i_mutex);
853                 err = __remove_suid(out->f_path.dentry, err);
854                 mutex_unlock(&inode->i_mutex);
855                 if (err)
856                         return err;
857         }
858
859         ret = splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_file);
860         if (ret > 0) {
861                 unsigned long nr_pages;
862
863                 *ppos += ret;
864                 nr_pages = (ret + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
865
866                 /*
867                  * If file or inode is SYNC and we actually wrote some data,
868                  * sync it.
869                  */
870                 if (unlikely((out->f_flags & O_SYNC) || IS_SYNC(inode))) {
871                         mutex_lock(&inode->i_mutex);
872                         err = generic_osync_inode(inode, mapping,
873                                                   OSYNC_METADATA|OSYNC_DATA);
874                         mutex_unlock(&inode->i_mutex);
875
876                         if (err)
877                                 ret = err;
878                 }
879                 balance_dirty_pages_ratelimited_nr(mapping, nr_pages);
880         }
881
882         return ret;
883 }
884
885 EXPORT_SYMBOL(generic_file_splice_write);
886
887 /**
888  * generic_splice_sendpage - splice data from a pipe to a socket
889  * @inode:      pipe inode
890  * @out:        socket to write to
891  * @len:        number of bytes to splice
892  * @flags:      splice modifier flags
893  *
894  * Will send @len bytes from the pipe to a network socket. No data copying
895  * is involved.
896  *
897  */
898 ssize_t generic_splice_sendpage(struct pipe_inode_info *pipe, struct file *out,
899                                 loff_t *ppos, size_t len, unsigned int flags)
900 {
901         return splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_sendpage);
902 }
903
904 EXPORT_SYMBOL(generic_splice_sendpage);
905
906 /*
907  * Attempt to initiate a splice from pipe to file.
908  */
909 static long do_splice_from(struct pipe_inode_info *pipe, struct file *out,
910                            loff_t *ppos, size_t len, unsigned int flags)
911 {
912         int ret;
913
914         if (unlikely(!out->f_op || !out->f_op->splice_write))
915                 return -EINVAL;
916
917         if (unlikely(!(out->f_mode & FMODE_WRITE)))
918                 return -EBADF;
919
920         ret = rw_verify_area(WRITE, out, ppos, len);
921         if (unlikely(ret < 0))
922                 return ret;
923
924         return out->f_op->splice_write(pipe, out, ppos, len, flags);
925 }
926
927 /*
928  * Attempt to initiate a splice from a file to a pipe.
929  */
930 static long do_splice_to(struct file *in, loff_t *ppos,
931                          struct pipe_inode_info *pipe, size_t len,
932                          unsigned int flags)
933 {
934         int ret;
935
936         if (unlikely(!in->f_op || !in->f_op->splice_read))
937                 return -EINVAL;
938
939         if (unlikely(!(in->f_mode & FMODE_READ)))
940                 return -EBADF;
941
942         ret = rw_verify_area(READ, in, ppos, len);
943         if (unlikely(ret < 0))
944                 return ret;
945
946         return in->f_op->splice_read(in, ppos, pipe, len, flags);
947 }
948
949 /*
950  * Splices from an input file to an actor, using a 'direct' pipe.
951  */
952 ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,
953                                splice_direct_actor *actor)
954 {
955         struct pipe_inode_info *pipe;
956         long ret, bytes;
957         umode_t i_mode;
958         size_t len;
959         int i, flags;
960
961         /*
962          * We require the input being a regular file, as we don't want to
963          * randomly drop data for eg socket -> socket splicing. Use the
964          * piped splicing for that!
965          */
966         i_mode = in->f_path.dentry->d_inode->i_mode;
967         if (unlikely(!S_ISREG(i_mode) && !S_ISBLK(i_mode)))
968                 return -EINVAL;
969
970         /*
971          * neither in nor out is a pipe, setup an internal pipe attached to
972          * 'out' and transfer the wanted data from 'in' to 'out' through that
973          */
974         pipe = current->splice_pipe;
975         if (unlikely(!pipe)) {
976                 pipe = alloc_pipe_info(NULL);
977                 if (!pipe)
978                         return -ENOMEM;
979
980                 /*
981                  * We don't have an immediate reader, but we'll read the stuff
982                  * out of the pipe right after the splice_to_pipe(). So set
983                  * PIPE_READERS appropriately.
984                  */
985                 pipe->readers = 1;
986
987                 current->splice_pipe = pipe;
988         }
989
990         /*
991          * Do the splice.
992          */
993         ret = 0;
994         bytes = 0;
995         len = sd->total_len;
996         flags = sd->flags;
997
998         /*
999          * Don't block on output, we have to drain the direct pipe.
1000          */
1001         sd->flags &= ~SPLICE_F_NONBLOCK;
1002
1003         while (len) {
1004                 size_t read_len, max_read_len;
1005
1006                 /*
1007                  * Do at most PIPE_BUFFERS pages worth of transfer:
1008                  */
1009                 max_read_len = min(len, (size_t)(PIPE_BUFFERS*PAGE_SIZE));
1010
1011                 ret = do_splice_to(in, &sd->pos, pipe, max_read_len, flags);
1012                 if (unlikely(ret < 0))
1013                         goto out_release;
1014
1015                 read_len = ret;
1016                 sd->total_len = read_len;
1017
1018                 /*
1019                  * NOTE: nonblocking mode only applies to the input. We
1020                  * must not do the output in nonblocking mode as then we
1021                  * could get stuck data in the internal pipe:
1022                  */
1023                 ret = actor(pipe, sd);
1024                 if (unlikely(ret < 0))
1025                         goto out_release;
1026
1027                 bytes += ret;
1028                 len -= ret;
1029
1030                 /*
1031                  * In nonblocking mode, if we got back a short read then
1032                  * that was due to either an IO error or due to the
1033                  * pagecache entry not being there. In the IO error case
1034                  * the _next_ splice attempt will produce a clean IO error
1035                  * return value (not a short read), so in both cases it's
1036                  * correct to break out of the loop here:
1037                  */
1038                 if ((flags & SPLICE_F_NONBLOCK) && (read_len < max_read_len))
1039                         break;
1040         }
1041
1042         pipe->nrbufs = pipe->curbuf = 0;
1043
1044         return bytes;
1045
1046 out_release:
1047         /*
1048          * If we did an incomplete transfer we must release
1049          * the pipe buffers in question:
1050          */
1051         for (i = 0; i < PIPE_BUFFERS; i++) {
1052                 struct pipe_buffer *buf = pipe->bufs + i;
1053
1054                 if (buf->ops) {
1055                         buf->ops->release(pipe, buf);
1056                         buf->ops = NULL;
1057                 }
1058         }
1059         pipe->nrbufs = pipe->curbuf = 0;
1060
1061         /*
1062          * If we transferred some data, return the number of bytes:
1063          */
1064         if (bytes > 0)
1065                 return bytes;
1066
1067         return ret;
1068
1069 }
1070 EXPORT_SYMBOL(splice_direct_to_actor);
1071
1072 static int direct_splice_actor(struct pipe_inode_info *pipe,
1073                                struct splice_desc *sd)
1074 {
1075         struct file *file = sd->u.file;
1076
1077         return do_splice_from(pipe, file, &sd->pos, sd->total_len, sd->flags);
1078 }
1079
1080 long do_splice_direct(struct file *in, loff_t *ppos, struct file *out,
1081                       size_t len, unsigned int flags)
1082 {
1083         struct splice_desc sd = {
1084                 .len            = len,
1085                 .total_len      = len,
1086                 .flags          = flags,
1087                 .pos            = *ppos,
1088                 .u.file         = out,
1089         };
1090         size_t ret;
1091
1092         ret = splice_direct_to_actor(in, &sd, direct_splice_actor);
1093         *ppos = sd.pos;
1094         return ret;
1095 }
1096
1097 /*
1098  * After the inode slimming patch, i_pipe/i_bdev/i_cdev share the same
1099  * location, so checking ->i_pipe is not enough to verify that this is a
1100  * pipe.
1101  */
1102 static inline struct pipe_inode_info *pipe_info(struct inode *inode)
1103 {
1104         if (S_ISFIFO(inode->i_mode))
1105                 return inode->i_pipe;
1106
1107         return NULL;
1108 }
1109
1110 /*
1111  * Determine where to splice to/from.
1112  */
1113 static long do_splice(struct file *in, loff_t __user *off_in,
1114                       struct file *out, loff_t __user *off_out,
1115                       size_t len, unsigned int flags)
1116 {
1117         struct pipe_inode_info *pipe;
1118         loff_t offset, *off;
1119         long ret;
1120
1121         pipe = pipe_info(in->f_path.dentry->d_inode);
1122         if (pipe) {
1123                 if (off_in)
1124                         return -ESPIPE;
1125                 if (off_out) {
1126                         if (out->f_op->llseek == no_llseek)
1127                                 return -EINVAL;
1128                         if (copy_from_user(&offset, off_out, sizeof(loff_t)))
1129                                 return -EFAULT;
1130                         off = &offset;
1131                 } else
1132                         off = &out->f_pos;
1133
1134                 ret = do_splice_from(pipe, out, off, len, flags);
1135
1136                 if (off_out && copy_to_user(off_out, off, sizeof(loff_t)))
1137                         ret = -EFAULT;
1138
1139                 return ret;
1140         }
1141
1142         pipe = pipe_info(out->f_path.dentry->d_inode);
1143         if (pipe) {
1144                 if (off_out)
1145                         return -ESPIPE;
1146                 if (off_in) {
1147                         if (in->f_op->llseek == no_llseek)
1148                                 return -EINVAL;
1149                         if (copy_from_user(&offset, off_in, sizeof(loff_t)))
1150                                 return -EFAULT;
1151                         off = &offset;
1152                 } else
1153                         off = &in->f_pos;
1154
1155                 ret = do_splice_to(in, off, pipe, len, flags);
1156
1157                 if (off_in && copy_to_user(off_in, off, sizeof(loff_t)))
1158                         ret = -EFAULT;
1159
1160                 return ret;
1161         }
1162
1163         return -EINVAL;
1164 }
1165
1166 /*
1167  * Map an iov into an array of pages and offset/length tupples. With the
1168  * partial_page structure, we can map several non-contiguous ranges into
1169  * our ones pages[] map instead of splitting that operation into pieces.
1170  * Could easily be exported as a generic helper for other users, in which
1171  * case one would probably want to add a 'max_nr_pages' parameter as well.
1172  */
1173 static int get_iovec_page_array(const struct iovec __user *iov,
1174                                 unsigned int nr_vecs, struct page **pages,
1175                                 struct partial_page *partial, int aligned)
1176 {
1177         int buffers = 0, error = 0;
1178
1179         /*
1180          * It's ok to take the mmap_sem for reading, even
1181          * across a "get_user()".
1182          */
1183         down_read(&current->mm->mmap_sem);
1184
1185         while (nr_vecs) {
1186                 unsigned long off, npages;
1187                 void __user *base;
1188                 size_t len;
1189                 int i;
1190
1191                 /*
1192                  * Get user address base and length for this iovec.
1193                  */
1194                 error = get_user(base, &iov->iov_base);
1195                 if (unlikely(error))
1196                         break;
1197                 error = get_user(len, &iov->iov_len);
1198                 if (unlikely(error))
1199                         break;
1200
1201                 /*
1202                  * Sanity check this iovec. 0 read succeeds.
1203                  */
1204                 if (unlikely(!len))
1205                         break;
1206                 error = -EFAULT;
1207                 if (unlikely(!base))
1208                         break;
1209
1210                 /*
1211                  * Get this base offset and number of pages, then map
1212                  * in the user pages.
1213                  */
1214                 off = (unsigned long) base & ~PAGE_MASK;
1215
1216                 /*
1217                  * If asked for alignment, the offset must be zero and the
1218                  * length a multiple of the PAGE_SIZE.
1219                  */
1220                 error = -EINVAL;
1221                 if (aligned && (off || len & ~PAGE_MASK))
1222                         break;
1223
1224                 npages = (off + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
1225                 if (npages > PIPE_BUFFERS - buffers)
1226                         npages = PIPE_BUFFERS - buffers;
1227
1228                 error = get_user_pages(current, current->mm,
1229                                        (unsigned long) base, npages, 0, 0,
1230                                        &pages[buffers], NULL);
1231
1232                 if (unlikely(error <= 0))
1233                         break;
1234
1235                 /*
1236                  * Fill this contiguous range into the partial page map.
1237                  */
1238                 for (i = 0; i < error; i++) {
1239                         const int plen = min_t(size_t, len, PAGE_SIZE - off);
1240
1241                         partial[buffers].offset = off;
1242                         partial[buffers].len = plen;
1243
1244                         off = 0;
1245                         len -= plen;
1246                         buffers++;
1247                 }
1248
1249                 /*
1250                  * We didn't complete this iov, stop here since it probably
1251                  * means we have to move some of this into a pipe to
1252                  * be able to continue.
1253                  */
1254                 if (len)
1255                         break;
1256
1257                 /*
1258                  * Don't continue if we mapped fewer pages than we asked for,
1259                  * or if we mapped the max number of pages that we have
1260                  * room for.
1261                  */
1262                 if (error < npages || buffers == PIPE_BUFFERS)
1263                         break;
1264
1265                 nr_vecs--;
1266                 iov++;
1267         }
1268
1269         up_read(&current->mm->mmap_sem);
1270
1271         if (buffers)
1272                 return buffers;
1273
1274         return error;
1275 }
1276
1277 static int pipe_to_user(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1278                         struct splice_desc *sd)
1279 {
1280         char *src;
1281         int ret;
1282
1283         ret = buf->ops->pin(pipe, buf);
1284         if (unlikely(ret))
1285                 return ret;
1286
1287         /*
1288          * See if we can use the atomic maps, by prefaulting in the
1289          * pages and doing an atomic copy
1290          */
1291         if (!fault_in_pages_writeable(sd->u.userptr, sd->len)) {
1292                 src = buf->ops->map(pipe, buf, 1);
1293                 ret = __copy_to_user_inatomic(sd->u.userptr, src + buf->offset,
1294                                                         sd->len);
1295                 buf->ops->unmap(pipe, buf, src);
1296                 if (!ret) {
1297                         ret = sd->len;
1298                         goto out;
1299                 }
1300         }
1301
1302         /*
1303          * No dice, use slow non-atomic map and copy
1304          */
1305         src = buf->ops->map(pipe, buf, 0);
1306
1307         ret = sd->len;
1308         if (copy_to_user(sd->u.userptr, src + buf->offset, sd->len))
1309                 ret = -EFAULT;
1310
1311 out:
1312         if (ret > 0)
1313                 sd->u.userptr += ret;
1314         buf->ops->unmap(pipe, buf, src);
1315         return ret;
1316 }
1317
1318 /*
1319  * For lack of a better implementation, implement vmsplice() to userspace
1320  * as a simple copy of the pipes pages to the user iov.
1321  */
1322 static long vmsplice_to_user(struct file *file, const struct iovec __user *iov,
1323                              unsigned long nr_segs, unsigned int flags)
1324 {
1325         struct pipe_inode_info *pipe;
1326         struct splice_desc sd;
1327         ssize_t size;
1328         int error;
1329         long ret;
1330
1331         pipe = pipe_info(file->f_path.dentry->d_inode);
1332         if (!pipe)
1333                 return -EBADF;
1334
1335         if (pipe->inode)
1336                 mutex_lock(&pipe->inode->i_mutex);
1337
1338         error = ret = 0;
1339         while (nr_segs) {
1340                 void __user *base;
1341                 size_t len;
1342
1343                 /*
1344                  * Get user address base and length for this iovec.
1345                  */
1346                 error = get_user(base, &iov->iov_base);
1347                 if (unlikely(error))
1348                         break;
1349                 error = get_user(len, &iov->iov_len);
1350                 if (unlikely(error))
1351                         break;
1352
1353                 /*
1354                  * Sanity check this iovec. 0 read succeeds.
1355                  */
1356                 if (unlikely(!len))
1357                         break;
1358                 if (unlikely(!base)) {
1359                         error = -EFAULT;
1360                         break;
1361                 }
1362
1363                 sd.len = 0;
1364                 sd.total_len = len;
1365                 sd.flags = flags;
1366                 sd.u.userptr = base;
1367                 sd.pos = 0;
1368
1369                 size = __splice_from_pipe(pipe, &sd, pipe_to_user);
1370                 if (size < 0) {
1371                         if (!ret)
1372                                 ret = size;
1373
1374                         break;
1375                 }
1376
1377                 ret += size;
1378
1379                 if (size < len)
1380                         break;
1381
1382                 nr_segs--;
1383                 iov++;
1384         }
1385
1386         if (pipe->inode)
1387                 mutex_unlock(&pipe->inode->i_mutex);
1388
1389         if (!ret)
1390                 ret = error;
1391
1392         return ret;
1393 }
1394
1395 /*
1396  * vmsplice splices a user address range into a pipe. It can be thought of
1397  * as splice-from-memory, where the regular splice is splice-from-file (or
1398  * to file). In both cases the output is a pipe, naturally.
1399  */
1400 static long vmsplice_to_pipe(struct file *file, const struct iovec __user *iov,
1401                              unsigned long nr_segs, unsigned int flags)
1402 {
1403         struct pipe_inode_info *pipe;
1404         struct page *pages[PIPE_BUFFERS];
1405         struct partial_page partial[PIPE_BUFFERS];
1406         struct splice_pipe_desc spd = {
1407                 .pages = pages,
1408                 .partial = partial,
1409                 .flags = flags,
1410                 .ops = &user_page_pipe_buf_ops,
1411         };
1412
1413         pipe = pipe_info(file->f_path.dentry->d_inode);
1414         if (!pipe)
1415                 return -EBADF;
1416
1417         spd.nr_pages = get_iovec_page_array(iov, nr_segs, pages, partial,
1418                                             flags & SPLICE_F_GIFT);
1419         if (spd.nr_pages <= 0)
1420                 return spd.nr_pages;
1421
1422         return splice_to_pipe(pipe, &spd);
1423 }
1424
1425 /*
1426  * Note that vmsplice only really supports true splicing _from_ user memory
1427  * to a pipe, not the other way around. Splicing from user memory is a simple
1428  * operation that can be supported without any funky alignment restrictions
1429  * or nasty vm tricks. We simply map in the user memory and fill them into
1430  * a pipe. The reverse isn't quite as easy, though. There are two possible
1431  * solutions for that:
1432  *
1433  *      - memcpy() the data internally, at which point we might as well just
1434  *        do a regular read() on the buffer anyway.
1435  *      - Lots of nasty vm tricks, that are neither fast nor flexible (it
1436  *        has restriction limitations on both ends of the pipe).
1437  *
1438  * Currently we punt and implement it as a normal copy, see pipe_to_user().
1439  *
1440  */
1441 asmlinkage long sys_vmsplice(int fd, const struct iovec __user *iov,
1442                              unsigned long nr_segs, unsigned int flags)
1443 {
1444         struct file *file;
1445         long error;
1446         int fput;
1447
1448         if (unlikely(nr_segs > UIO_MAXIOV))
1449                 return -EINVAL;
1450         else if (unlikely(!nr_segs))
1451                 return 0;
1452
1453         error = -EBADF;
1454         file = fget_light(fd, &fput);
1455         if (file) {
1456                 if (file->f_mode & FMODE_WRITE)
1457                         error = vmsplice_to_pipe(file, iov, nr_segs, flags);
1458                 else if (file->f_mode & FMODE_READ)
1459                         error = vmsplice_to_user(file, iov, nr_segs, flags);
1460
1461                 fput_light(file, fput);
1462         }
1463
1464         return error;
1465 }
1466
1467 asmlinkage long sys_splice(int fd_in, loff_t __user *off_in,
1468                            int fd_out, loff_t __user *off_out,
1469                            size_t len, unsigned int flags)
1470 {
1471         long error;
1472         struct file *in, *out;
1473         int fput_in, fput_out;
1474
1475         if (unlikely(!len))
1476                 return 0;
1477
1478         error = -EBADF;
1479         in = fget_light(fd_in, &fput_in);
1480         if (in) {
1481                 if (in->f_mode & FMODE_READ) {
1482                         out = fget_light(fd_out, &fput_out);
1483                         if (out) {
1484                                 if (out->f_mode & FMODE_WRITE)
1485                                         error = do_splice(in, off_in,
1486                                                           out, off_out,
1487                                                           len, flags);
1488                                 fput_light(out, fput_out);
1489                         }
1490                 }
1491
1492                 fput_light(in, fput_in);
1493         }
1494
1495         return error;
1496 }
1497
1498 /*
1499  * Make sure there's data to read. Wait for input if we can, otherwise
1500  * return an appropriate error.
1501  */
1502 static int link_ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1503 {
1504         int ret;
1505
1506         /*
1507          * Check ->nrbufs without the inode lock first. This function
1508          * is speculative anyways, so missing one is ok.
1509          */
1510         if (pipe->nrbufs)
1511                 return 0;
1512
1513         ret = 0;
1514         mutex_lock(&pipe->inode->i_mutex);
1515
1516         while (!pipe->nrbufs) {
1517                 if (signal_pending(current)) {
1518                         ret = -ERESTARTSYS;
1519                         break;
1520                 }
1521                 if (!pipe->writers)
1522                         break;
1523                 if (!pipe->waiting_writers) {
1524                         if (flags & SPLICE_F_NONBLOCK) {
1525                                 ret = -EAGAIN;
1526                                 break;
1527                         }
1528                 }
1529                 pipe_wait(pipe);
1530         }
1531
1532         mutex_unlock(&pipe->inode->i_mutex);
1533         return ret;
1534 }
1535
1536 /*
1537  * Make sure there's writeable room. Wait for room if we can, otherwise
1538  * return an appropriate error.
1539  */
1540 static int link_opipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1541 {
1542         int ret;
1543
1544         /*
1545          * Check ->nrbufs without the inode lock first. This function
1546          * is speculative anyways, so missing one is ok.
1547          */
1548         if (pipe->nrbufs < PIPE_BUFFERS)
1549                 return 0;
1550
1551         ret = 0;
1552         mutex_lock(&pipe->inode->i_mutex);
1553
1554         while (pipe->nrbufs >= PIPE_BUFFERS) {
1555                 if (!pipe->readers) {
1556                         send_sig(SIGPIPE, current, 0);
1557                         ret = -EPIPE;
1558                         break;
1559                 }
1560                 if (flags & SPLICE_F_NONBLOCK) {
1561                         ret = -EAGAIN;
1562                         break;
1563                 }
1564                 if (signal_pending(current)) {
1565                         ret = -ERESTARTSYS;
1566                         break;
1567                 }
1568                 pipe->waiting_writers++;
1569                 pipe_wait(pipe);
1570                 pipe->waiting_writers--;
1571         }
1572
1573         mutex_unlock(&pipe->inode->i_mutex);
1574         return ret;
1575 }
1576
1577 /*
1578  * Link contents of ipipe to opipe.
1579  */
1580 static int link_pipe(struct pipe_inode_info *ipipe,
1581                      struct pipe_inode_info *opipe,
1582                      size_t len, unsigned int flags)
1583 {
1584         struct pipe_buffer *ibuf, *obuf;
1585         int ret = 0, i = 0, nbuf;
1586
1587         /*
1588          * Potential ABBA deadlock, work around it by ordering lock
1589          * grabbing by inode address. Otherwise two different processes
1590          * could deadlock (one doing tee from A -> B, the other from B -> A).
1591          */
1592         inode_double_lock(ipipe->inode, opipe->inode);
1593
1594         do {
1595                 if (!opipe->readers) {
1596                         send_sig(SIGPIPE, current, 0);
1597                         if (!ret)
1598                                 ret = -EPIPE;
1599                         break;
1600                 }
1601
1602                 /*
1603                  * If we have iterated all input buffers or ran out of
1604                  * output room, break.
1605                  */
1606                 if (i >= ipipe->nrbufs || opipe->nrbufs >= PIPE_BUFFERS)
1607                         break;
1608
1609                 ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (PIPE_BUFFERS - 1));
1610                 nbuf = (opipe->curbuf + opipe->nrbufs) & (PIPE_BUFFERS - 1);
1611
1612                 /*
1613                  * Get a reference to this pipe buffer,
1614                  * so we can copy the contents over.
1615                  */
1616                 ibuf->ops->get(ipipe, ibuf);
1617
1618                 obuf = opipe->bufs + nbuf;
1619                 *obuf = *ibuf;
1620
1621                 /*
1622                  * Don't inherit the gift flag, we need to
1623                  * prevent multiple steals of this page.
1624                  */
1625                 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1626
1627                 if (obuf->len > len)
1628                         obuf->len = len;
1629
1630                 opipe->nrbufs++;
1631                 ret += obuf->len;
1632                 len -= obuf->len;
1633                 i++;
1634         } while (len);
1635
1636         inode_double_unlock(ipipe->inode, opipe->inode);
1637
1638         /*
1639          * If we put data in the output pipe, wakeup any potential readers.
1640          */
1641         if (ret > 0) {
1642                 smp_mb();
1643                 if (waitqueue_active(&opipe->wait))
1644                         wake_up_interruptible(&opipe->wait);
1645                 kill_fasync(&opipe->fasync_readers, SIGIO, POLL_IN);
1646         }
1647
1648         return ret;
1649 }
1650
1651 /*
1652  * This is a tee(1) implementation that works on pipes. It doesn't copy
1653  * any data, it simply references the 'in' pages on the 'out' pipe.
1654  * The 'flags' used are the SPLICE_F_* variants, currently the only
1655  * applicable one is SPLICE_F_NONBLOCK.
1656  */
1657 static long do_tee(struct file *in, struct file *out, size_t len,
1658                    unsigned int flags)
1659 {
1660         struct pipe_inode_info *ipipe = pipe_info(in->f_path.dentry->d_inode);
1661         struct pipe_inode_info *opipe = pipe_info(out->f_path.dentry->d_inode);
1662         int ret = -EINVAL;
1663
1664         /*
1665          * Duplicate the contents of ipipe to opipe without actually
1666          * copying the data.
1667          */
1668         if (ipipe && opipe && ipipe != opipe) {
1669                 /*
1670                  * Keep going, unless we encounter an error. The ipipe/opipe
1671                  * ordering doesn't really matter.
1672                  */
1673                 ret = link_ipipe_prep(ipipe, flags);
1674                 if (!ret) {
1675                         ret = link_opipe_prep(opipe, flags);
1676                         if (!ret) {
1677                                 ret = link_pipe(ipipe, opipe, len, flags);
1678                                 if (!ret && (flags & SPLICE_F_NONBLOCK))
1679                                         ret = -EAGAIN;
1680                         }
1681                 }
1682         }
1683
1684         return ret;
1685 }
1686
1687 asmlinkage long sys_tee(int fdin, int fdout, size_t len, unsigned int flags)
1688 {
1689         struct file *in;
1690         int error, fput_in;
1691
1692         if (unlikely(!len))
1693                 return 0;
1694
1695         error = -EBADF;
1696         in = fget_light(fdin, &fput_in);
1697         if (in) {
1698                 if (in->f_mode & FMODE_READ) {
1699                         int fput_out;
1700                         struct file *out = fget_light(fdout, &fput_out);
1701
1702                         if (out) {
1703                                 if (out->f_mode & FMODE_WRITE)
1704                                         error = do_tee(in, out, len, flags);
1705                                 fput_light(out, fput_out);
1706                         }
1707                 }
1708                 fput_light(in, fput_in);
1709         }
1710
1711         return error;
1712 }