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