new iov_iter flavour: pipe-backed
[cascardo/linux.git] / 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/memcontrol.h>
25 #include <linux/mm_inline.h>
26 #include <linux/swap.h>
27 #include <linux/writeback.h>
28 #include <linux/export.h>
29 #include <linux/syscalls.h>
30 #include <linux/uio.h>
31 #include <linux/security.h>
32 #include <linux/gfp.h>
33 #include <linux/socket.h>
34 #include <linux/compat.h>
35 #include "internal.h"
36
37 /*
38  * Attempt to steal a page from a pipe buffer. This should perhaps go into
39  * a vm helper function, it's already simplified quite a bit by the
40  * addition of remove_mapping(). If success is returned, the caller may
41  * attempt to reuse this page for another destination.
42  */
43 static int page_cache_pipe_buf_steal(struct pipe_inode_info *pipe,
44                                      struct pipe_buffer *buf)
45 {
46         struct page *page = buf->page;
47         struct address_space *mapping;
48
49         lock_page(page);
50
51         mapping = page_mapping(page);
52         if (mapping) {
53                 WARN_ON(!PageUptodate(page));
54
55                 /*
56                  * At least for ext2 with nobh option, we need to wait on
57                  * writeback completing on this page, since we'll remove it
58                  * from the pagecache.  Otherwise truncate wont wait on the
59                  * page, allowing the disk blocks to be reused by someone else
60                  * before we actually wrote our data to them. fs corruption
61                  * ensues.
62                  */
63                 wait_on_page_writeback(page);
64
65                 if (page_has_private(page) &&
66                     !try_to_release_page(page, GFP_KERNEL))
67                         goto out_unlock;
68
69                 /*
70                  * If we succeeded in removing the mapping, set LRU flag
71                  * and return good.
72                  */
73                 if (remove_mapping(mapping, page)) {
74                         buf->flags |= PIPE_BUF_FLAG_LRU;
75                         return 0;
76                 }
77         }
78
79         /*
80          * Raced with truncate or failed to remove page from current
81          * address space, unlock and return failure.
82          */
83 out_unlock:
84         unlock_page(page);
85         return 1;
86 }
87
88 static void page_cache_pipe_buf_release(struct pipe_inode_info *pipe,
89                                         struct pipe_buffer *buf)
90 {
91         put_page(buf->page);
92         buf->flags &= ~PIPE_BUF_FLAG_LRU;
93 }
94
95 /*
96  * Check whether the contents of buf is OK to access. Since the content
97  * is a page cache page, IO may be in flight.
98  */
99 static int page_cache_pipe_buf_confirm(struct pipe_inode_info *pipe,
100                                        struct pipe_buffer *buf)
101 {
102         struct page *page = buf->page;
103         int err;
104
105         if (!PageUptodate(page)) {
106                 lock_page(page);
107
108                 /*
109                  * Page got truncated/unhashed. This will cause a 0-byte
110                  * splice, if this is the first page.
111                  */
112                 if (!page->mapping) {
113                         err = -ENODATA;
114                         goto error;
115                 }
116
117                 /*
118                  * Uh oh, read-error from disk.
119                  */
120                 if (!PageUptodate(page)) {
121                         err = -EIO;
122                         goto error;
123                 }
124
125                 /*
126                  * Page is ok afterall, we are done.
127                  */
128                 unlock_page(page);
129         }
130
131         return 0;
132 error:
133         unlock_page(page);
134         return err;
135 }
136
137 const struct pipe_buf_operations page_cache_pipe_buf_ops = {
138         .can_merge = 0,
139         .confirm = page_cache_pipe_buf_confirm,
140         .release = page_cache_pipe_buf_release,
141         .steal = page_cache_pipe_buf_steal,
142         .get = generic_pipe_buf_get,
143 };
144
145 static int user_page_pipe_buf_steal(struct pipe_inode_info *pipe,
146                                     struct pipe_buffer *buf)
147 {
148         if (!(buf->flags & PIPE_BUF_FLAG_GIFT))
149                 return 1;
150
151         buf->flags |= PIPE_BUF_FLAG_LRU;
152         return generic_pipe_buf_steal(pipe, buf);
153 }
154
155 static const struct pipe_buf_operations user_page_pipe_buf_ops = {
156         .can_merge = 0,
157         .confirm = generic_pipe_buf_confirm,
158         .release = page_cache_pipe_buf_release,
159         .steal = user_page_pipe_buf_steal,
160         .get = generic_pipe_buf_get,
161 };
162
163 static void wakeup_pipe_readers(struct pipe_inode_info *pipe)
164 {
165         smp_mb();
166         if (waitqueue_active(&pipe->wait))
167                 wake_up_interruptible(&pipe->wait);
168         kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
169 }
170
171 /**
172  * splice_to_pipe - fill passed data into a pipe
173  * @pipe:       pipe to fill
174  * @spd:        data to fill
175  *
176  * Description:
177  *    @spd contains a map of pages and len/offset tuples, along with
178  *    the struct pipe_buf_operations associated with these pages. This
179  *    function will link that data to the pipe.
180  *
181  */
182 ssize_t splice_to_pipe(struct pipe_inode_info *pipe,
183                        struct splice_pipe_desc *spd)
184 {
185         unsigned int spd_pages = spd->nr_pages;
186         int ret = 0, page_nr = 0;
187
188         if (!spd_pages)
189                 return 0;
190
191         if (unlikely(!pipe->readers)) {
192                 send_sig(SIGPIPE, current, 0);
193                 ret = -EPIPE;
194                 goto out;
195         }
196
197         while (pipe->nrbufs < pipe->buffers) {
198                 int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
199                 struct pipe_buffer *buf = pipe->bufs + newbuf;
200
201                 buf->page = spd->pages[page_nr];
202                 buf->offset = spd->partial[page_nr].offset;
203                 buf->len = spd->partial[page_nr].len;
204                 buf->private = spd->partial[page_nr].private;
205                 buf->ops = spd->ops;
206
207                 pipe->nrbufs++;
208                 page_nr++;
209                 ret += buf->len;
210
211                 if (!--spd->nr_pages)
212                         break;
213         }
214
215         if (!ret)
216                 ret = -EAGAIN;
217
218 out:
219         while (page_nr < spd_pages)
220                 spd->spd_release(spd, page_nr++);
221
222         return ret;
223 }
224 EXPORT_SYMBOL_GPL(splice_to_pipe);
225
226 ssize_t add_to_pipe(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
227 {
228         int ret;
229
230         if (unlikely(!pipe->readers)) {
231                 send_sig(SIGPIPE, current, 0);
232                 ret = -EPIPE;
233         } else if (pipe->nrbufs == pipe->buffers) {
234                 ret = -EAGAIN;
235         } else {
236                 int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
237                 pipe->bufs[newbuf] = *buf;
238                 pipe->nrbufs++;
239                 return buf->len;
240         }
241         buf->ops->release(pipe, buf);
242         buf->ops = NULL;
243         return ret;
244 }
245 EXPORT_SYMBOL(add_to_pipe);
246
247 void spd_release_page(struct splice_pipe_desc *spd, unsigned int i)
248 {
249         put_page(spd->pages[i]);
250 }
251
252 /*
253  * Check if we need to grow the arrays holding pages and partial page
254  * descriptions.
255  */
256 int splice_grow_spd(const struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
257 {
258         unsigned int buffers = ACCESS_ONCE(pipe->buffers);
259
260         spd->nr_pages_max = buffers;
261         if (buffers <= PIPE_DEF_BUFFERS)
262                 return 0;
263
264         spd->pages = kmalloc(buffers * sizeof(struct page *), GFP_KERNEL);
265         spd->partial = kmalloc(buffers * sizeof(struct partial_page), GFP_KERNEL);
266
267         if (spd->pages && spd->partial)
268                 return 0;
269
270         kfree(spd->pages);
271         kfree(spd->partial);
272         return -ENOMEM;
273 }
274
275 void splice_shrink_spd(struct splice_pipe_desc *spd)
276 {
277         if (spd->nr_pages_max <= PIPE_DEF_BUFFERS)
278                 return;
279
280         kfree(spd->pages);
281         kfree(spd->partial);
282 }
283
284 static int
285 __generic_file_splice_read(struct file *in, loff_t *ppos,
286                            struct pipe_inode_info *pipe, size_t len,
287                            unsigned int flags)
288 {
289         struct address_space *mapping = in->f_mapping;
290         unsigned int loff, nr_pages, req_pages;
291         struct page *pages[PIPE_DEF_BUFFERS];
292         struct partial_page partial[PIPE_DEF_BUFFERS];
293         struct page *page;
294         pgoff_t index, end_index;
295         loff_t isize;
296         int error, page_nr;
297         struct splice_pipe_desc spd = {
298                 .pages = pages,
299                 .partial = partial,
300                 .nr_pages_max = PIPE_DEF_BUFFERS,
301                 .flags = flags,
302                 .ops = &page_cache_pipe_buf_ops,
303                 .spd_release = spd_release_page,
304         };
305
306         if (splice_grow_spd(pipe, &spd))
307                 return -ENOMEM;
308
309         index = *ppos >> PAGE_SHIFT;
310         loff = *ppos & ~PAGE_MASK;
311         req_pages = (len + loff + PAGE_SIZE - 1) >> PAGE_SHIFT;
312         nr_pages = min(req_pages, spd.nr_pages_max);
313
314         /*
315          * Lookup the (hopefully) full range of pages we need.
316          */
317         spd.nr_pages = find_get_pages_contig(mapping, index, nr_pages, spd.pages);
318         index += spd.nr_pages;
319
320         /*
321          * If find_get_pages_contig() returned fewer pages than we needed,
322          * readahead/allocate the rest and fill in the holes.
323          */
324         if (spd.nr_pages < nr_pages)
325                 page_cache_sync_readahead(mapping, &in->f_ra, in,
326                                 index, req_pages - spd.nr_pages);
327
328         error = 0;
329         while (spd.nr_pages < nr_pages) {
330                 /*
331                  * Page could be there, find_get_pages_contig() breaks on
332                  * the first hole.
333                  */
334                 page = find_get_page(mapping, index);
335                 if (!page) {
336                         /*
337                          * page didn't exist, allocate one.
338                          */
339                         page = page_cache_alloc_cold(mapping);
340                         if (!page)
341                                 break;
342
343                         error = add_to_page_cache_lru(page, mapping, index,
344                                    mapping_gfp_constraint(mapping, GFP_KERNEL));
345                         if (unlikely(error)) {
346                                 put_page(page);
347                                 if (error == -EEXIST)
348                                         continue;
349                                 break;
350                         }
351                         /*
352                          * add_to_page_cache() locks the page, unlock it
353                          * to avoid convoluting the logic below even more.
354                          */
355                         unlock_page(page);
356                 }
357
358                 spd.pages[spd.nr_pages++] = page;
359                 index++;
360         }
361
362         /*
363          * Now loop over the map and see if we need to start IO on any
364          * pages, fill in the partial map, etc.
365          */
366         index = *ppos >> PAGE_SHIFT;
367         nr_pages = spd.nr_pages;
368         spd.nr_pages = 0;
369         for (page_nr = 0; page_nr < nr_pages; page_nr++) {
370                 unsigned int this_len;
371
372                 if (!len)
373                         break;
374
375                 /*
376                  * this_len is the max we'll use from this page
377                  */
378                 this_len = min_t(unsigned long, len, PAGE_SIZE - loff);
379                 page = spd.pages[page_nr];
380
381                 if (PageReadahead(page))
382                         page_cache_async_readahead(mapping, &in->f_ra, in,
383                                         page, index, req_pages - page_nr);
384
385                 /*
386                  * If the page isn't uptodate, we may need to start io on it
387                  */
388                 if (!PageUptodate(page)) {
389                         lock_page(page);
390
391                         /*
392                          * Page was truncated, or invalidated by the
393                          * filesystem.  Redo the find/create, but this time the
394                          * page is kept locked, so there's no chance of another
395                          * race with truncate/invalidate.
396                          */
397                         if (!page->mapping) {
398                                 unlock_page(page);
399 retry_lookup:
400                                 page = find_or_create_page(mapping, index,
401                                                 mapping_gfp_mask(mapping));
402
403                                 if (!page) {
404                                         error = -ENOMEM;
405                                         break;
406                                 }
407                                 put_page(spd.pages[page_nr]);
408                                 spd.pages[page_nr] = page;
409                         }
410                         /*
411                          * page was already under io and is now done, great
412                          */
413                         if (PageUptodate(page)) {
414                                 unlock_page(page);
415                                 goto fill_it;
416                         }
417
418                         /*
419                          * need to read in the page
420                          */
421                         error = mapping->a_ops->readpage(in, page);
422                         if (unlikely(error)) {
423                                 /*
424                                  * Re-lookup the page
425                                  */
426                                 if (error == AOP_TRUNCATED_PAGE)
427                                         goto retry_lookup;
428
429                                 break;
430                         }
431                 }
432 fill_it:
433                 /*
434                  * i_size must be checked after PageUptodate.
435                  */
436                 isize = i_size_read(mapping->host);
437                 end_index = (isize - 1) >> PAGE_SHIFT;
438                 if (unlikely(!isize || index > end_index))
439                         break;
440
441                 /*
442                  * if this is the last page, see if we need to shrink
443                  * the length and stop
444                  */
445                 if (end_index == index) {
446                         unsigned int plen;
447
448                         /*
449                          * max good bytes in this page
450                          */
451                         plen = ((isize - 1) & ~PAGE_MASK) + 1;
452                         if (plen <= loff)
453                                 break;
454
455                         /*
456                          * force quit after adding this page
457                          */
458                         this_len = min(this_len, plen - loff);
459                         len = this_len;
460                 }
461
462                 spd.partial[page_nr].offset = loff;
463                 spd.partial[page_nr].len = this_len;
464                 len -= this_len;
465                 loff = 0;
466                 spd.nr_pages++;
467                 index++;
468         }
469
470         /*
471          * Release any pages at the end, if we quit early. 'page_nr' is how far
472          * we got, 'nr_pages' is how many pages are in the map.
473          */
474         while (page_nr < nr_pages)
475                 put_page(spd.pages[page_nr++]);
476         in->f_ra.prev_pos = (loff_t)index << PAGE_SHIFT;
477
478         if (spd.nr_pages)
479                 error = splice_to_pipe(pipe, &spd);
480
481         splice_shrink_spd(&spd);
482         return error;
483 }
484
485 /**
486  * generic_file_splice_read - splice data from file to a pipe
487  * @in:         file to splice from
488  * @ppos:       position in @in
489  * @pipe:       pipe to splice to
490  * @len:        number of bytes to splice
491  * @flags:      splice modifier flags
492  *
493  * Description:
494  *    Will read pages from given file and fill them into a pipe. Can be
495  *    used as long as the address_space operations for the source implements
496  *    a readpage() hook.
497  *
498  */
499 ssize_t generic_file_splice_read(struct file *in, loff_t *ppos,
500                                  struct pipe_inode_info *pipe, size_t len,
501                                  unsigned int flags)
502 {
503         loff_t isize, left;
504         int ret;
505
506         if (IS_DAX(in->f_mapping->host))
507                 return default_file_splice_read(in, ppos, pipe, len, flags);
508
509         isize = i_size_read(in->f_mapping->host);
510         if (unlikely(*ppos >= isize))
511                 return 0;
512
513         left = isize - *ppos;
514         if (unlikely(left < len))
515                 len = left;
516
517         ret = __generic_file_splice_read(in, ppos, pipe, len, flags);
518         if (ret > 0) {
519                 *ppos += ret;
520                 file_accessed(in);
521         }
522
523         return ret;
524 }
525 EXPORT_SYMBOL(generic_file_splice_read);
526
527 const struct pipe_buf_operations default_pipe_buf_ops = {
528         .can_merge = 0,
529         .confirm = generic_pipe_buf_confirm,
530         .release = generic_pipe_buf_release,
531         .steal = generic_pipe_buf_steal,
532         .get = generic_pipe_buf_get,
533 };
534
535 static int generic_pipe_buf_nosteal(struct pipe_inode_info *pipe,
536                                     struct pipe_buffer *buf)
537 {
538         return 1;
539 }
540
541 /* Pipe buffer operations for a socket and similar. */
542 const struct pipe_buf_operations nosteal_pipe_buf_ops = {
543         .can_merge = 0,
544         .confirm = generic_pipe_buf_confirm,
545         .release = generic_pipe_buf_release,
546         .steal = generic_pipe_buf_nosteal,
547         .get = generic_pipe_buf_get,
548 };
549 EXPORT_SYMBOL(nosteal_pipe_buf_ops);
550
551 static ssize_t kernel_readv(struct file *file, const struct iovec *vec,
552                             unsigned long vlen, loff_t offset)
553 {
554         mm_segment_t old_fs;
555         loff_t pos = offset;
556         ssize_t res;
557
558         old_fs = get_fs();
559         set_fs(get_ds());
560         /* The cast to a user pointer is valid due to the set_fs() */
561         res = vfs_readv(file, (const struct iovec __user *)vec, vlen, &pos, 0);
562         set_fs(old_fs);
563
564         return res;
565 }
566
567 ssize_t kernel_write(struct file *file, const char *buf, size_t count,
568                             loff_t pos)
569 {
570         mm_segment_t old_fs;
571         ssize_t res;
572
573         old_fs = get_fs();
574         set_fs(get_ds());
575         /* The cast to a user pointer is valid due to the set_fs() */
576         res = vfs_write(file, (__force const char __user *)buf, count, &pos);
577         set_fs(old_fs);
578
579         return res;
580 }
581 EXPORT_SYMBOL(kernel_write);
582
583 ssize_t default_file_splice_read(struct file *in, loff_t *ppos,
584                                  struct pipe_inode_info *pipe, size_t len,
585                                  unsigned int flags)
586 {
587         unsigned int nr_pages;
588         unsigned int nr_freed;
589         size_t offset;
590         struct page *pages[PIPE_DEF_BUFFERS];
591         struct partial_page partial[PIPE_DEF_BUFFERS];
592         struct iovec *vec, __vec[PIPE_DEF_BUFFERS];
593         ssize_t res;
594         size_t this_len;
595         int error;
596         int i;
597         struct splice_pipe_desc spd = {
598                 .pages = pages,
599                 .partial = partial,
600                 .nr_pages_max = PIPE_DEF_BUFFERS,
601                 .flags = flags,
602                 .ops = &default_pipe_buf_ops,
603                 .spd_release = spd_release_page,
604         };
605
606         if (splice_grow_spd(pipe, &spd))
607                 return -ENOMEM;
608
609         res = -ENOMEM;
610         vec = __vec;
611         if (spd.nr_pages_max > PIPE_DEF_BUFFERS) {
612                 vec = kmalloc(spd.nr_pages_max * sizeof(struct iovec), GFP_KERNEL);
613                 if (!vec)
614                         goto shrink_ret;
615         }
616
617         offset = *ppos & ~PAGE_MASK;
618         nr_pages = (len + offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
619
620         for (i = 0; i < nr_pages && i < spd.nr_pages_max && len; i++) {
621                 struct page *page;
622
623                 page = alloc_page(GFP_USER);
624                 error = -ENOMEM;
625                 if (!page)
626                         goto err;
627
628                 this_len = min_t(size_t, len, PAGE_SIZE - offset);
629                 vec[i].iov_base = (void __user *) page_address(page);
630                 vec[i].iov_len = this_len;
631                 spd.pages[i] = page;
632                 spd.nr_pages++;
633                 len -= this_len;
634                 offset = 0;
635         }
636
637         res = kernel_readv(in, vec, spd.nr_pages, *ppos);
638         if (res < 0) {
639                 error = res;
640                 goto err;
641         }
642
643         error = 0;
644         if (!res)
645                 goto err;
646
647         nr_freed = 0;
648         for (i = 0; i < spd.nr_pages; i++) {
649                 this_len = min_t(size_t, vec[i].iov_len, res);
650                 spd.partial[i].offset = 0;
651                 spd.partial[i].len = this_len;
652                 if (!this_len) {
653                         __free_page(spd.pages[i]);
654                         spd.pages[i] = NULL;
655                         nr_freed++;
656                 }
657                 res -= this_len;
658         }
659         spd.nr_pages -= nr_freed;
660
661         res = splice_to_pipe(pipe, &spd);
662         if (res > 0)
663                 *ppos += res;
664
665 shrink_ret:
666         if (vec != __vec)
667                 kfree(vec);
668         splice_shrink_spd(&spd);
669         return res;
670
671 err:
672         for (i = 0; i < spd.nr_pages; i++)
673                 __free_page(spd.pages[i]);
674
675         res = error;
676         goto shrink_ret;
677 }
678 EXPORT_SYMBOL(default_file_splice_read);
679
680 /*
681  * Send 'sd->len' bytes to socket from 'sd->file' at position 'sd->pos'
682  * using sendpage(). Return the number of bytes sent.
683  */
684 static int pipe_to_sendpage(struct pipe_inode_info *pipe,
685                             struct pipe_buffer *buf, struct splice_desc *sd)
686 {
687         struct file *file = sd->u.file;
688         loff_t pos = sd->pos;
689         int more;
690
691         if (!likely(file->f_op->sendpage))
692                 return -EINVAL;
693
694         more = (sd->flags & SPLICE_F_MORE) ? MSG_MORE : 0;
695
696         if (sd->len < sd->total_len && pipe->nrbufs > 1)
697                 more |= MSG_SENDPAGE_NOTLAST;
698
699         return file->f_op->sendpage(file, buf->page, buf->offset,
700                                     sd->len, &pos, more);
701 }
702
703 static void wakeup_pipe_writers(struct pipe_inode_info *pipe)
704 {
705         smp_mb();
706         if (waitqueue_active(&pipe->wait))
707                 wake_up_interruptible(&pipe->wait);
708         kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
709 }
710
711 /**
712  * splice_from_pipe_feed - feed available data from a pipe to a file
713  * @pipe:       pipe to splice from
714  * @sd:         information to @actor
715  * @actor:      handler that splices the data
716  *
717  * Description:
718  *    This function loops over the pipe and calls @actor to do the
719  *    actual moving of a single struct pipe_buffer to the desired
720  *    destination.  It returns when there's no more buffers left in
721  *    the pipe or if the requested number of bytes (@sd->total_len)
722  *    have been copied.  It returns a positive number (one) if the
723  *    pipe needs to be filled with more data, zero if the required
724  *    number of bytes have been copied and -errno on error.
725  *
726  *    This, together with splice_from_pipe_{begin,end,next}, may be
727  *    used to implement the functionality of __splice_from_pipe() when
728  *    locking is required around copying the pipe buffers to the
729  *    destination.
730  */
731 static int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
732                           splice_actor *actor)
733 {
734         int ret;
735
736         while (pipe->nrbufs) {
737                 struct pipe_buffer *buf = pipe->bufs + pipe->curbuf;
738                 const struct pipe_buf_operations *ops = buf->ops;
739
740                 sd->len = buf->len;
741                 if (sd->len > sd->total_len)
742                         sd->len = sd->total_len;
743
744                 ret = buf->ops->confirm(pipe, buf);
745                 if (unlikely(ret)) {
746                         if (ret == -ENODATA)
747                                 ret = 0;
748                         return ret;
749                 }
750
751                 ret = actor(pipe, buf, sd);
752                 if (ret <= 0)
753                         return ret;
754
755                 buf->offset += ret;
756                 buf->len -= ret;
757
758                 sd->num_spliced += ret;
759                 sd->len -= ret;
760                 sd->pos += ret;
761                 sd->total_len -= ret;
762
763                 if (!buf->len) {
764                         buf->ops = NULL;
765                         ops->release(pipe, buf);
766                         pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
767                         pipe->nrbufs--;
768                         if (pipe->files)
769                                 sd->need_wakeup = true;
770                 }
771
772                 if (!sd->total_len)
773                         return 0;
774         }
775
776         return 1;
777 }
778
779 /**
780  * splice_from_pipe_next - wait for some data to splice from
781  * @pipe:       pipe to splice from
782  * @sd:         information about the splice operation
783  *
784  * Description:
785  *    This function will wait for some data and return a positive
786  *    value (one) if pipe buffers are available.  It will return zero
787  *    or -errno if no more data needs to be spliced.
788  */
789 static int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
790 {
791         /*
792          * Check for signal early to make process killable when there are
793          * always buffers available
794          */
795         if (signal_pending(current))
796                 return -ERESTARTSYS;
797
798         while (!pipe->nrbufs) {
799                 if (!pipe->writers)
800                         return 0;
801
802                 if (!pipe->waiting_writers && sd->num_spliced)
803                         return 0;
804
805                 if (sd->flags & SPLICE_F_NONBLOCK)
806                         return -EAGAIN;
807
808                 if (signal_pending(current))
809                         return -ERESTARTSYS;
810
811                 if (sd->need_wakeup) {
812                         wakeup_pipe_writers(pipe);
813                         sd->need_wakeup = false;
814                 }
815
816                 pipe_wait(pipe);
817         }
818
819         return 1;
820 }
821
822 /**
823  * splice_from_pipe_begin - start splicing from pipe
824  * @sd:         information about the splice operation
825  *
826  * Description:
827  *    This function should be called before a loop containing
828  *    splice_from_pipe_next() and splice_from_pipe_feed() to
829  *    initialize the necessary fields of @sd.
830  */
831 static void splice_from_pipe_begin(struct splice_desc *sd)
832 {
833         sd->num_spliced = 0;
834         sd->need_wakeup = false;
835 }
836
837 /**
838  * splice_from_pipe_end - finish splicing from pipe
839  * @pipe:       pipe to splice from
840  * @sd:         information about the splice operation
841  *
842  * Description:
843  *    This function will wake up pipe writers if necessary.  It should
844  *    be called after a loop containing splice_from_pipe_next() and
845  *    splice_from_pipe_feed().
846  */
847 static void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
848 {
849         if (sd->need_wakeup)
850                 wakeup_pipe_writers(pipe);
851 }
852
853 /**
854  * __splice_from_pipe - splice data from a pipe to given actor
855  * @pipe:       pipe to splice from
856  * @sd:         information to @actor
857  * @actor:      handler that splices the data
858  *
859  * Description:
860  *    This function does little more than loop over the pipe and call
861  *    @actor to do the actual moving of a single struct pipe_buffer to
862  *    the desired destination. See pipe_to_file, pipe_to_sendpage, or
863  *    pipe_to_user.
864  *
865  */
866 ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
867                            splice_actor *actor)
868 {
869         int ret;
870
871         splice_from_pipe_begin(sd);
872         do {
873                 cond_resched();
874                 ret = splice_from_pipe_next(pipe, sd);
875                 if (ret > 0)
876                         ret = splice_from_pipe_feed(pipe, sd, actor);
877         } while (ret > 0);
878         splice_from_pipe_end(pipe, sd);
879
880         return sd->num_spliced ? sd->num_spliced : ret;
881 }
882 EXPORT_SYMBOL(__splice_from_pipe);
883
884 /**
885  * splice_from_pipe - splice data from a pipe to a file
886  * @pipe:       pipe to splice from
887  * @out:        file to splice to
888  * @ppos:       position in @out
889  * @len:        how many bytes to splice
890  * @flags:      splice modifier flags
891  * @actor:      handler that splices the data
892  *
893  * Description:
894  *    See __splice_from_pipe. This function locks the pipe inode,
895  *    otherwise it's identical to __splice_from_pipe().
896  *
897  */
898 ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
899                          loff_t *ppos, size_t len, unsigned int flags,
900                          splice_actor *actor)
901 {
902         ssize_t ret;
903         struct splice_desc sd = {
904                 .total_len = len,
905                 .flags = flags,
906                 .pos = *ppos,
907                 .u.file = out,
908         };
909
910         pipe_lock(pipe);
911         ret = __splice_from_pipe(pipe, &sd, actor);
912         pipe_unlock(pipe);
913
914         return ret;
915 }
916
917 /**
918  * iter_file_splice_write - splice data from a pipe to a file
919  * @pipe:       pipe info
920  * @out:        file to write to
921  * @ppos:       position in @out
922  * @len:        number of bytes to splice
923  * @flags:      splice modifier flags
924  *
925  * Description:
926  *    Will either move or copy pages (determined by @flags options) from
927  *    the given pipe inode to the given file.
928  *    This one is ->write_iter-based.
929  *
930  */
931 ssize_t
932 iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
933                           loff_t *ppos, size_t len, unsigned int flags)
934 {
935         struct splice_desc sd = {
936                 .total_len = len,
937                 .flags = flags,
938                 .pos = *ppos,
939                 .u.file = out,
940         };
941         int nbufs = pipe->buffers;
942         struct bio_vec *array = kcalloc(nbufs, sizeof(struct bio_vec),
943                                         GFP_KERNEL);
944         ssize_t ret;
945
946         if (unlikely(!array))
947                 return -ENOMEM;
948
949         pipe_lock(pipe);
950
951         splice_from_pipe_begin(&sd);
952         while (sd.total_len) {
953                 struct iov_iter from;
954                 size_t left;
955                 int n, idx;
956
957                 ret = splice_from_pipe_next(pipe, &sd);
958                 if (ret <= 0)
959                         break;
960
961                 if (unlikely(nbufs < pipe->buffers)) {
962                         kfree(array);
963                         nbufs = pipe->buffers;
964                         array = kcalloc(nbufs, sizeof(struct bio_vec),
965                                         GFP_KERNEL);
966                         if (!array) {
967                                 ret = -ENOMEM;
968                                 break;
969                         }
970                 }
971
972                 /* build the vector */
973                 left = sd.total_len;
974                 for (n = 0, idx = pipe->curbuf; left && n < pipe->nrbufs; n++, idx++) {
975                         struct pipe_buffer *buf = pipe->bufs + idx;
976                         size_t this_len = buf->len;
977
978                         if (this_len > left)
979                                 this_len = left;
980
981                         if (idx == pipe->buffers - 1)
982                                 idx = -1;
983
984                         ret = buf->ops->confirm(pipe, buf);
985                         if (unlikely(ret)) {
986                                 if (ret == -ENODATA)
987                                         ret = 0;
988                                 goto done;
989                         }
990
991                         array[n].bv_page = buf->page;
992                         array[n].bv_len = this_len;
993                         array[n].bv_offset = buf->offset;
994                         left -= this_len;
995                 }
996
997                 iov_iter_bvec(&from, ITER_BVEC | WRITE, array, n,
998                               sd.total_len - left);
999                 ret = vfs_iter_write(out, &from, &sd.pos);
1000                 if (ret <= 0)
1001                         break;
1002
1003                 sd.num_spliced += ret;
1004                 sd.total_len -= ret;
1005                 *ppos = sd.pos;
1006
1007                 /* dismiss the fully eaten buffers, adjust the partial one */
1008                 while (ret) {
1009                         struct pipe_buffer *buf = pipe->bufs + pipe->curbuf;
1010                         if (ret >= buf->len) {
1011                                 const struct pipe_buf_operations *ops = buf->ops;
1012                                 ret -= buf->len;
1013                                 buf->len = 0;
1014                                 buf->ops = NULL;
1015                                 ops->release(pipe, buf);
1016                                 pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
1017                                 pipe->nrbufs--;
1018                                 if (pipe->files)
1019                                         sd.need_wakeup = true;
1020                         } else {
1021                                 buf->offset += ret;
1022                                 buf->len -= ret;
1023                                 ret = 0;
1024                         }
1025                 }
1026         }
1027 done:
1028         kfree(array);
1029         splice_from_pipe_end(pipe, &sd);
1030
1031         pipe_unlock(pipe);
1032
1033         if (sd.num_spliced)
1034                 ret = sd.num_spliced;
1035
1036         return ret;
1037 }
1038
1039 EXPORT_SYMBOL(iter_file_splice_write);
1040
1041 static int write_pipe_buf(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1042                           struct splice_desc *sd)
1043 {
1044         int ret;
1045         void *data;
1046         loff_t tmp = sd->pos;
1047
1048         data = kmap(buf->page);
1049         ret = __kernel_write(sd->u.file, data + buf->offset, sd->len, &tmp);
1050         kunmap(buf->page);
1051
1052         return ret;
1053 }
1054
1055 static ssize_t default_file_splice_write(struct pipe_inode_info *pipe,
1056                                          struct file *out, loff_t *ppos,
1057                                          size_t len, unsigned int flags)
1058 {
1059         ssize_t ret;
1060
1061         ret = splice_from_pipe(pipe, out, ppos, len, flags, write_pipe_buf);
1062         if (ret > 0)
1063                 *ppos += ret;
1064
1065         return ret;
1066 }
1067
1068 /**
1069  * generic_splice_sendpage - splice data from a pipe to a socket
1070  * @pipe:       pipe to splice from
1071  * @out:        socket to write to
1072  * @ppos:       position in @out
1073  * @len:        number of bytes to splice
1074  * @flags:      splice modifier flags
1075  *
1076  * Description:
1077  *    Will send @len bytes from the pipe to a network socket. No data copying
1078  *    is involved.
1079  *
1080  */
1081 ssize_t generic_splice_sendpage(struct pipe_inode_info *pipe, struct file *out,
1082                                 loff_t *ppos, size_t len, unsigned int flags)
1083 {
1084         return splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_sendpage);
1085 }
1086
1087 EXPORT_SYMBOL(generic_splice_sendpage);
1088
1089 /*
1090  * Attempt to initiate a splice from pipe to file.
1091  */
1092 static long do_splice_from(struct pipe_inode_info *pipe, struct file *out,
1093                            loff_t *ppos, size_t len, unsigned int flags)
1094 {
1095         ssize_t (*splice_write)(struct pipe_inode_info *, struct file *,
1096                                 loff_t *, size_t, unsigned int);
1097
1098         if (out->f_op->splice_write)
1099                 splice_write = out->f_op->splice_write;
1100         else
1101                 splice_write = default_file_splice_write;
1102
1103         return splice_write(pipe, out, ppos, len, flags);
1104 }
1105
1106 /*
1107  * Attempt to initiate a splice from a file to a pipe.
1108  */
1109 static long do_splice_to(struct file *in, loff_t *ppos,
1110                          struct pipe_inode_info *pipe, size_t len,
1111                          unsigned int flags)
1112 {
1113         ssize_t (*splice_read)(struct file *, loff_t *,
1114                                struct pipe_inode_info *, size_t, unsigned int);
1115         int ret;
1116
1117         if (unlikely(!(in->f_mode & FMODE_READ)))
1118                 return -EBADF;
1119
1120         ret = rw_verify_area(READ, in, ppos, len);
1121         if (unlikely(ret < 0))
1122                 return ret;
1123
1124         if (unlikely(len > MAX_RW_COUNT))
1125                 len = MAX_RW_COUNT;
1126
1127         if (in->f_op->splice_read)
1128                 splice_read = in->f_op->splice_read;
1129         else
1130                 splice_read = default_file_splice_read;
1131
1132         return splice_read(in, ppos, pipe, len, flags);
1133 }
1134
1135 /**
1136  * splice_direct_to_actor - splices data directly between two non-pipes
1137  * @in:         file to splice from
1138  * @sd:         actor information on where to splice to
1139  * @actor:      handles the data splicing
1140  *
1141  * Description:
1142  *    This is a special case helper to splice directly between two
1143  *    points, without requiring an explicit pipe. Internally an allocated
1144  *    pipe is cached in the process, and reused during the lifetime of
1145  *    that process.
1146  *
1147  */
1148 ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,
1149                                splice_direct_actor *actor)
1150 {
1151         struct pipe_inode_info *pipe;
1152         long ret, bytes;
1153         umode_t i_mode;
1154         size_t len;
1155         int i, flags, more;
1156
1157         /*
1158          * We require the input being a regular file, as we don't want to
1159          * randomly drop data for eg socket -> socket splicing. Use the
1160          * piped splicing for that!
1161          */
1162         i_mode = file_inode(in)->i_mode;
1163         if (unlikely(!S_ISREG(i_mode) && !S_ISBLK(i_mode)))
1164                 return -EINVAL;
1165
1166         /*
1167          * neither in nor out is a pipe, setup an internal pipe attached to
1168          * 'out' and transfer the wanted data from 'in' to 'out' through that
1169          */
1170         pipe = current->splice_pipe;
1171         if (unlikely(!pipe)) {
1172                 pipe = alloc_pipe_info();
1173                 if (!pipe)
1174                         return -ENOMEM;
1175
1176                 /*
1177                  * We don't have an immediate reader, but we'll read the stuff
1178                  * out of the pipe right after the splice_to_pipe(). So set
1179                  * PIPE_READERS appropriately.
1180                  */
1181                 pipe->readers = 1;
1182
1183                 current->splice_pipe = pipe;
1184         }
1185
1186         /*
1187          * Do the splice.
1188          */
1189         ret = 0;
1190         bytes = 0;
1191         len = sd->total_len;
1192         flags = sd->flags;
1193
1194         /*
1195          * Don't block on output, we have to drain the direct pipe.
1196          */
1197         sd->flags &= ~SPLICE_F_NONBLOCK;
1198         more = sd->flags & SPLICE_F_MORE;
1199
1200         while (len) {
1201                 size_t read_len;
1202                 loff_t pos = sd->pos, prev_pos = pos;
1203
1204                 ret = do_splice_to(in, &pos, pipe, len, flags);
1205                 if (unlikely(ret <= 0))
1206                         goto out_release;
1207
1208                 read_len = ret;
1209                 sd->total_len = read_len;
1210
1211                 /*
1212                  * If more data is pending, set SPLICE_F_MORE
1213                  * If this is the last data and SPLICE_F_MORE was not set
1214                  * initially, clears it.
1215                  */
1216                 if (read_len < len)
1217                         sd->flags |= SPLICE_F_MORE;
1218                 else if (!more)
1219                         sd->flags &= ~SPLICE_F_MORE;
1220                 /*
1221                  * NOTE: nonblocking mode only applies to the input. We
1222                  * must not do the output in nonblocking mode as then we
1223                  * could get stuck data in the internal pipe:
1224                  */
1225                 ret = actor(pipe, sd);
1226                 if (unlikely(ret <= 0)) {
1227                         sd->pos = prev_pos;
1228                         goto out_release;
1229                 }
1230
1231                 bytes += ret;
1232                 len -= ret;
1233                 sd->pos = pos;
1234
1235                 if (ret < read_len) {
1236                         sd->pos = prev_pos + ret;
1237                         goto out_release;
1238                 }
1239         }
1240
1241 done:
1242         pipe->nrbufs = pipe->curbuf = 0;
1243         file_accessed(in);
1244         return bytes;
1245
1246 out_release:
1247         /*
1248          * If we did an incomplete transfer we must release
1249          * the pipe buffers in question:
1250          */
1251         for (i = 0; i < pipe->buffers; i++) {
1252                 struct pipe_buffer *buf = pipe->bufs + i;
1253
1254                 if (buf->ops) {
1255                         buf->ops->release(pipe, buf);
1256                         buf->ops = NULL;
1257                 }
1258         }
1259
1260         if (!bytes)
1261                 bytes = ret;
1262
1263         goto done;
1264 }
1265 EXPORT_SYMBOL(splice_direct_to_actor);
1266
1267 static int direct_splice_actor(struct pipe_inode_info *pipe,
1268                                struct splice_desc *sd)
1269 {
1270         struct file *file = sd->u.file;
1271
1272         return do_splice_from(pipe, file, sd->opos, sd->total_len,
1273                               sd->flags);
1274 }
1275
1276 /**
1277  * do_splice_direct - splices data directly between two files
1278  * @in:         file to splice from
1279  * @ppos:       input file offset
1280  * @out:        file to splice to
1281  * @opos:       output file offset
1282  * @len:        number of bytes to splice
1283  * @flags:      splice modifier flags
1284  *
1285  * Description:
1286  *    For use by do_sendfile(). splice can easily emulate sendfile, but
1287  *    doing it in the application would incur an extra system call
1288  *    (splice in + splice out, as compared to just sendfile()). So this helper
1289  *    can splice directly through a process-private pipe.
1290  *
1291  */
1292 long do_splice_direct(struct file *in, loff_t *ppos, struct file *out,
1293                       loff_t *opos, size_t len, unsigned int flags)
1294 {
1295         struct splice_desc sd = {
1296                 .len            = len,
1297                 .total_len      = len,
1298                 .flags          = flags,
1299                 .pos            = *ppos,
1300                 .u.file         = out,
1301                 .opos           = opos,
1302         };
1303         long ret;
1304
1305         if (unlikely(!(out->f_mode & FMODE_WRITE)))
1306                 return -EBADF;
1307
1308         if (unlikely(out->f_flags & O_APPEND))
1309                 return -EINVAL;
1310
1311         ret = rw_verify_area(WRITE, out, opos, len);
1312         if (unlikely(ret < 0))
1313                 return ret;
1314
1315         ret = splice_direct_to_actor(in, &sd, direct_splice_actor);
1316         if (ret > 0)
1317                 *ppos = sd.pos;
1318
1319         return ret;
1320 }
1321 EXPORT_SYMBOL(do_splice_direct);
1322
1323 static int wait_for_space(struct pipe_inode_info *pipe, unsigned flags)
1324 {
1325         while (pipe->nrbufs == pipe->buffers) {
1326                 if (flags & SPLICE_F_NONBLOCK)
1327                         return -EAGAIN;
1328                 if (signal_pending(current))
1329                         return -ERESTARTSYS;
1330                 pipe->waiting_writers++;
1331                 pipe_wait(pipe);
1332                 pipe->waiting_writers--;
1333         }
1334         return 0;
1335 }
1336
1337 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1338                                struct pipe_inode_info *opipe,
1339                                size_t len, unsigned int flags);
1340
1341 /*
1342  * Determine where to splice to/from.
1343  */
1344 static long do_splice(struct file *in, loff_t __user *off_in,
1345                       struct file *out, loff_t __user *off_out,
1346                       size_t len, unsigned int flags)
1347 {
1348         struct pipe_inode_info *ipipe;
1349         struct pipe_inode_info *opipe;
1350         loff_t offset;
1351         long ret;
1352
1353         ipipe = get_pipe_info(in);
1354         opipe = get_pipe_info(out);
1355
1356         if (ipipe && opipe) {
1357                 if (off_in || off_out)
1358                         return -ESPIPE;
1359
1360                 if (!(in->f_mode & FMODE_READ))
1361                         return -EBADF;
1362
1363                 if (!(out->f_mode & FMODE_WRITE))
1364                         return -EBADF;
1365
1366                 /* Splicing to self would be fun, but... */
1367                 if (ipipe == opipe)
1368                         return -EINVAL;
1369
1370                 return splice_pipe_to_pipe(ipipe, opipe, len, flags);
1371         }
1372
1373         if (ipipe) {
1374                 if (off_in)
1375                         return -ESPIPE;
1376                 if (off_out) {
1377                         if (!(out->f_mode & FMODE_PWRITE))
1378                                 return -EINVAL;
1379                         if (copy_from_user(&offset, off_out, sizeof(loff_t)))
1380                                 return -EFAULT;
1381                 } else {
1382                         offset = out->f_pos;
1383                 }
1384
1385                 if (unlikely(!(out->f_mode & FMODE_WRITE)))
1386                         return -EBADF;
1387
1388                 if (unlikely(out->f_flags & O_APPEND))
1389                         return -EINVAL;
1390
1391                 ret = rw_verify_area(WRITE, out, &offset, len);
1392                 if (unlikely(ret < 0))
1393                         return ret;
1394
1395                 file_start_write(out);
1396                 ret = do_splice_from(ipipe, out, &offset, len, flags);
1397                 file_end_write(out);
1398
1399                 if (!off_out)
1400                         out->f_pos = offset;
1401                 else if (copy_to_user(off_out, &offset, sizeof(loff_t)))
1402                         ret = -EFAULT;
1403
1404                 return ret;
1405         }
1406
1407         if (opipe) {
1408                 if (off_out)
1409                         return -ESPIPE;
1410                 if (off_in) {
1411                         if (!(in->f_mode & FMODE_PREAD))
1412                                 return -EINVAL;
1413                         if (copy_from_user(&offset, off_in, sizeof(loff_t)))
1414                                 return -EFAULT;
1415                 } else {
1416                         offset = in->f_pos;
1417                 }
1418
1419                 pipe_lock(opipe);
1420                 ret = wait_for_space(opipe, flags);
1421                 if (!ret)
1422                         ret = do_splice_to(in, &offset, opipe, len, flags);
1423                 pipe_unlock(opipe);
1424                 if (ret > 0)
1425                         wakeup_pipe_readers(opipe);
1426                 if (!off_in)
1427                         in->f_pos = offset;
1428                 else if (copy_to_user(off_in, &offset, sizeof(loff_t)))
1429                         ret = -EFAULT;
1430
1431                 return ret;
1432         }
1433
1434         return -EINVAL;
1435 }
1436
1437 static int iter_to_pipe(struct iov_iter *from,
1438                         struct pipe_inode_info *pipe,
1439                         unsigned flags)
1440 {
1441         struct pipe_buffer buf = {
1442                 .ops = &user_page_pipe_buf_ops,
1443                 .flags = flags
1444         };
1445         size_t total = 0;
1446         int ret = 0;
1447         bool failed = false;
1448
1449         while (iov_iter_count(from) && !failed) {
1450                 struct page *pages[16];
1451                 ssize_t copied;
1452                 size_t start;
1453                 int n;
1454
1455                 copied = iov_iter_get_pages(from, pages, ~0UL, 16, &start);
1456                 if (copied <= 0) {
1457                         ret = copied;
1458                         break;
1459                 }
1460
1461                 for (n = 0; copied; n++, start = 0) {
1462                         int size = min_t(int, copied, PAGE_SIZE - start);
1463                         if (!failed) {
1464                                 buf.page = pages[n];
1465                                 buf.offset = start;
1466                                 buf.len = size;
1467                                 ret = add_to_pipe(pipe, &buf);
1468                                 if (unlikely(ret < 0)) {
1469                                         failed = true;
1470                                 } else {
1471                                         iov_iter_advance(from, ret);
1472                                         total += ret;
1473                                 }
1474                         } else {
1475                                 put_page(pages[n]);
1476                         }
1477                         copied -= size;
1478                 }
1479         }
1480         return total ? total : ret;
1481 }
1482
1483 static int pipe_to_user(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1484                         struct splice_desc *sd)
1485 {
1486         int n = copy_page_to_iter(buf->page, buf->offset, sd->len, sd->u.data);
1487         return n == sd->len ? n : -EFAULT;
1488 }
1489
1490 /*
1491  * For lack of a better implementation, implement vmsplice() to userspace
1492  * as a simple copy of the pipes pages to the user iov.
1493  */
1494 static long vmsplice_to_user(struct file *file, const struct iovec __user *uiov,
1495                              unsigned long nr_segs, unsigned int flags)
1496 {
1497         struct pipe_inode_info *pipe;
1498         struct splice_desc sd;
1499         long ret;
1500         struct iovec iovstack[UIO_FASTIOV];
1501         struct iovec *iov = iovstack;
1502         struct iov_iter iter;
1503
1504         pipe = get_pipe_info(file);
1505         if (!pipe)
1506                 return -EBADF;
1507
1508         ret = import_iovec(READ, uiov, nr_segs,
1509                            ARRAY_SIZE(iovstack), &iov, &iter);
1510         if (ret < 0)
1511                 return ret;
1512
1513         sd.total_len = iov_iter_count(&iter);
1514         sd.len = 0;
1515         sd.flags = flags;
1516         sd.u.data = &iter;
1517         sd.pos = 0;
1518
1519         if (sd.total_len) {
1520                 pipe_lock(pipe);
1521                 ret = __splice_from_pipe(pipe, &sd, pipe_to_user);
1522                 pipe_unlock(pipe);
1523         }
1524
1525         kfree(iov);
1526         return ret;
1527 }
1528
1529 /*
1530  * vmsplice splices a user address range into a pipe. It can be thought of
1531  * as splice-from-memory, where the regular splice is splice-from-file (or
1532  * to file). In both cases the output is a pipe, naturally.
1533  */
1534 static long vmsplice_to_pipe(struct file *file, const struct iovec __user *uiov,
1535                              unsigned long nr_segs, unsigned int flags)
1536 {
1537         struct pipe_inode_info *pipe;
1538         struct iovec iovstack[UIO_FASTIOV];
1539         struct iovec *iov = iovstack;
1540         struct iov_iter from;
1541         long ret;
1542         unsigned buf_flag = 0;
1543
1544         if (flags & SPLICE_F_GIFT)
1545                 buf_flag = PIPE_BUF_FLAG_GIFT;
1546
1547         pipe = get_pipe_info(file);
1548         if (!pipe)
1549                 return -EBADF;
1550
1551         ret = import_iovec(WRITE, uiov, nr_segs,
1552                            ARRAY_SIZE(iovstack), &iov, &from);
1553         if (ret < 0)
1554                 return ret;
1555
1556         pipe_lock(pipe);
1557         ret = wait_for_space(pipe, flags);
1558         if (!ret)
1559                 ret = iter_to_pipe(&from, pipe, buf_flag);
1560         pipe_unlock(pipe);
1561         if (ret > 0)
1562                 wakeup_pipe_readers(pipe);
1563         kfree(iov);
1564         return ret;
1565 }
1566
1567 /*
1568  * Note that vmsplice only really supports true splicing _from_ user memory
1569  * to a pipe, not the other way around. Splicing from user memory is a simple
1570  * operation that can be supported without any funky alignment restrictions
1571  * or nasty vm tricks. We simply map in the user memory and fill them into
1572  * a pipe. The reverse isn't quite as easy, though. There are two possible
1573  * solutions for that:
1574  *
1575  *      - memcpy() the data internally, at which point we might as well just
1576  *        do a regular read() on the buffer anyway.
1577  *      - Lots of nasty vm tricks, that are neither fast nor flexible (it
1578  *        has restriction limitations on both ends of the pipe).
1579  *
1580  * Currently we punt and implement it as a normal copy, see pipe_to_user().
1581  *
1582  */
1583 SYSCALL_DEFINE4(vmsplice, int, fd, const struct iovec __user *, iov,
1584                 unsigned long, nr_segs, unsigned int, flags)
1585 {
1586         struct fd f;
1587         long error;
1588
1589         if (unlikely(nr_segs > UIO_MAXIOV))
1590                 return -EINVAL;
1591         else if (unlikely(!nr_segs))
1592                 return 0;
1593
1594         error = -EBADF;
1595         f = fdget(fd);
1596         if (f.file) {
1597                 if (f.file->f_mode & FMODE_WRITE)
1598                         error = vmsplice_to_pipe(f.file, iov, nr_segs, flags);
1599                 else if (f.file->f_mode & FMODE_READ)
1600                         error = vmsplice_to_user(f.file, iov, nr_segs, flags);
1601
1602                 fdput(f);
1603         }
1604
1605         return error;
1606 }
1607
1608 #ifdef CONFIG_COMPAT
1609 COMPAT_SYSCALL_DEFINE4(vmsplice, int, fd, const struct compat_iovec __user *, iov32,
1610                     unsigned int, nr_segs, unsigned int, flags)
1611 {
1612         unsigned i;
1613         struct iovec __user *iov;
1614         if (nr_segs > UIO_MAXIOV)
1615                 return -EINVAL;
1616         iov = compat_alloc_user_space(nr_segs * sizeof(struct iovec));
1617         for (i = 0; i < nr_segs; i++) {
1618                 struct compat_iovec v;
1619                 if (get_user(v.iov_base, &iov32[i].iov_base) ||
1620                     get_user(v.iov_len, &iov32[i].iov_len) ||
1621                     put_user(compat_ptr(v.iov_base), &iov[i].iov_base) ||
1622                     put_user(v.iov_len, &iov[i].iov_len))
1623                         return -EFAULT;
1624         }
1625         return sys_vmsplice(fd, iov, nr_segs, flags);
1626 }
1627 #endif
1628
1629 SYSCALL_DEFINE6(splice, int, fd_in, loff_t __user *, off_in,
1630                 int, fd_out, loff_t __user *, off_out,
1631                 size_t, len, unsigned int, flags)
1632 {
1633         struct fd in, out;
1634         long error;
1635
1636         if (unlikely(!len))
1637                 return 0;
1638
1639         error = -EBADF;
1640         in = fdget(fd_in);
1641         if (in.file) {
1642                 if (in.file->f_mode & FMODE_READ) {
1643                         out = fdget(fd_out);
1644                         if (out.file) {
1645                                 if (out.file->f_mode & FMODE_WRITE)
1646                                         error = do_splice(in.file, off_in,
1647                                                           out.file, off_out,
1648                                                           len, flags);
1649                                 fdput(out);
1650                         }
1651                 }
1652                 fdput(in);
1653         }
1654         return error;
1655 }
1656
1657 /*
1658  * Make sure there's data to read. Wait for input if we can, otherwise
1659  * return an appropriate error.
1660  */
1661 static int ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1662 {
1663         int ret;
1664
1665         /*
1666          * Check ->nrbufs without the inode lock first. This function
1667          * is speculative anyways, so missing one is ok.
1668          */
1669         if (pipe->nrbufs)
1670                 return 0;
1671
1672         ret = 0;
1673         pipe_lock(pipe);
1674
1675         while (!pipe->nrbufs) {
1676                 if (signal_pending(current)) {
1677                         ret = -ERESTARTSYS;
1678                         break;
1679                 }
1680                 if (!pipe->writers)
1681                         break;
1682                 if (!pipe->waiting_writers) {
1683                         if (flags & SPLICE_F_NONBLOCK) {
1684                                 ret = -EAGAIN;
1685                                 break;
1686                         }
1687                 }
1688                 pipe_wait(pipe);
1689         }
1690
1691         pipe_unlock(pipe);
1692         return ret;
1693 }
1694
1695 /*
1696  * Make sure there's writeable room. Wait for room if we can, otherwise
1697  * return an appropriate error.
1698  */
1699 static int opipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1700 {
1701         int ret;
1702
1703         /*
1704          * Check ->nrbufs without the inode lock first. This function
1705          * is speculative anyways, so missing one is ok.
1706          */
1707         if (pipe->nrbufs < pipe->buffers)
1708                 return 0;
1709
1710         ret = 0;
1711         pipe_lock(pipe);
1712
1713         while (pipe->nrbufs >= pipe->buffers) {
1714                 if (!pipe->readers) {
1715                         send_sig(SIGPIPE, current, 0);
1716                         ret = -EPIPE;
1717                         break;
1718                 }
1719                 if (flags & SPLICE_F_NONBLOCK) {
1720                         ret = -EAGAIN;
1721                         break;
1722                 }
1723                 if (signal_pending(current)) {
1724                         ret = -ERESTARTSYS;
1725                         break;
1726                 }
1727                 pipe->waiting_writers++;
1728                 pipe_wait(pipe);
1729                 pipe->waiting_writers--;
1730         }
1731
1732         pipe_unlock(pipe);
1733         return ret;
1734 }
1735
1736 /*
1737  * Splice contents of ipipe to opipe.
1738  */
1739 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1740                                struct pipe_inode_info *opipe,
1741                                size_t len, unsigned int flags)
1742 {
1743         struct pipe_buffer *ibuf, *obuf;
1744         int ret = 0, nbuf;
1745         bool input_wakeup = false;
1746
1747
1748 retry:
1749         ret = ipipe_prep(ipipe, flags);
1750         if (ret)
1751                 return ret;
1752
1753         ret = opipe_prep(opipe, flags);
1754         if (ret)
1755                 return ret;
1756
1757         /*
1758          * Potential ABBA deadlock, work around it by ordering lock
1759          * grabbing by pipe info address. Otherwise two different processes
1760          * could deadlock (one doing tee from A -> B, the other from B -> A).
1761          */
1762         pipe_double_lock(ipipe, opipe);
1763
1764         do {
1765                 if (!opipe->readers) {
1766                         send_sig(SIGPIPE, current, 0);
1767                         if (!ret)
1768                                 ret = -EPIPE;
1769                         break;
1770                 }
1771
1772                 if (!ipipe->nrbufs && !ipipe->writers)
1773                         break;
1774
1775                 /*
1776                  * Cannot make any progress, because either the input
1777                  * pipe is empty or the output pipe is full.
1778                  */
1779                 if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
1780                         /* Already processed some buffers, break */
1781                         if (ret)
1782                                 break;
1783
1784                         if (flags & SPLICE_F_NONBLOCK) {
1785                                 ret = -EAGAIN;
1786                                 break;
1787                         }
1788
1789                         /*
1790                          * We raced with another reader/writer and haven't
1791                          * managed to process any buffers.  A zero return
1792                          * value means EOF, so retry instead.
1793                          */
1794                         pipe_unlock(ipipe);
1795                         pipe_unlock(opipe);
1796                         goto retry;
1797                 }
1798
1799                 ibuf = ipipe->bufs + ipipe->curbuf;
1800                 nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
1801                 obuf = opipe->bufs + nbuf;
1802
1803                 if (len >= ibuf->len) {
1804                         /*
1805                          * Simply move the whole buffer from ipipe to opipe
1806                          */
1807                         *obuf = *ibuf;
1808                         ibuf->ops = NULL;
1809                         opipe->nrbufs++;
1810                         ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
1811                         ipipe->nrbufs--;
1812                         input_wakeup = true;
1813                 } else {
1814                         /*
1815                          * Get a reference to this pipe buffer,
1816                          * so we can copy the contents over.
1817                          */
1818                         ibuf->ops->get(ipipe, ibuf);
1819                         *obuf = *ibuf;
1820
1821                         /*
1822                          * Don't inherit the gift flag, we need to
1823                          * prevent multiple steals of this page.
1824                          */
1825                         obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1826
1827                         obuf->len = len;
1828                         opipe->nrbufs++;
1829                         ibuf->offset += obuf->len;
1830                         ibuf->len -= obuf->len;
1831                 }
1832                 ret += obuf->len;
1833                 len -= obuf->len;
1834         } while (len);
1835
1836         pipe_unlock(ipipe);
1837         pipe_unlock(opipe);
1838
1839         /*
1840          * If we put data in the output pipe, wakeup any potential readers.
1841          */
1842         if (ret > 0)
1843                 wakeup_pipe_readers(opipe);
1844
1845         if (input_wakeup)
1846                 wakeup_pipe_writers(ipipe);
1847
1848         return ret;
1849 }
1850
1851 /*
1852  * Link contents of ipipe to opipe.
1853  */
1854 static int link_pipe(struct pipe_inode_info *ipipe,
1855                      struct pipe_inode_info *opipe,
1856                      size_t len, unsigned int flags)
1857 {
1858         struct pipe_buffer *ibuf, *obuf;
1859         int ret = 0, i = 0, nbuf;
1860
1861         /*
1862          * Potential ABBA deadlock, work around it by ordering lock
1863          * grabbing by pipe info address. Otherwise two different processes
1864          * could deadlock (one doing tee from A -> B, the other from B -> A).
1865          */
1866         pipe_double_lock(ipipe, opipe);
1867
1868         do {
1869                 if (!opipe->readers) {
1870                         send_sig(SIGPIPE, current, 0);
1871                         if (!ret)
1872                                 ret = -EPIPE;
1873                         break;
1874                 }
1875
1876                 /*
1877                  * If we have iterated all input buffers or ran out of
1878                  * output room, break.
1879                  */
1880                 if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
1881                         break;
1882
1883                 ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
1884                 nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
1885
1886                 /*
1887                  * Get a reference to this pipe buffer,
1888                  * so we can copy the contents over.
1889                  */
1890                 ibuf->ops->get(ipipe, ibuf);
1891
1892                 obuf = opipe->bufs + nbuf;
1893                 *obuf = *ibuf;
1894
1895                 /*
1896                  * Don't inherit the gift flag, we need to
1897                  * prevent multiple steals of this page.
1898                  */
1899                 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1900
1901                 if (obuf->len > len)
1902                         obuf->len = len;
1903
1904                 opipe->nrbufs++;
1905                 ret += obuf->len;
1906                 len -= obuf->len;
1907                 i++;
1908         } while (len);
1909
1910         /*
1911          * return EAGAIN if we have the potential of some data in the
1912          * future, otherwise just return 0
1913          */
1914         if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
1915                 ret = -EAGAIN;
1916
1917         pipe_unlock(ipipe);
1918         pipe_unlock(opipe);
1919
1920         /*
1921          * If we put data in the output pipe, wakeup any potential readers.
1922          */
1923         if (ret > 0)
1924                 wakeup_pipe_readers(opipe);
1925
1926         return ret;
1927 }
1928
1929 /*
1930  * This is a tee(1) implementation that works on pipes. It doesn't copy
1931  * any data, it simply references the 'in' pages on the 'out' pipe.
1932  * The 'flags' used are the SPLICE_F_* variants, currently the only
1933  * applicable one is SPLICE_F_NONBLOCK.
1934  */
1935 static long do_tee(struct file *in, struct file *out, size_t len,
1936                    unsigned int flags)
1937 {
1938         struct pipe_inode_info *ipipe = get_pipe_info(in);
1939         struct pipe_inode_info *opipe = get_pipe_info(out);
1940         int ret = -EINVAL;
1941
1942         /*
1943          * Duplicate the contents of ipipe to opipe without actually
1944          * copying the data.
1945          */
1946         if (ipipe && opipe && ipipe != opipe) {
1947                 /*
1948                  * Keep going, unless we encounter an error. The ipipe/opipe
1949                  * ordering doesn't really matter.
1950                  */
1951                 ret = ipipe_prep(ipipe, flags);
1952                 if (!ret) {
1953                         ret = opipe_prep(opipe, flags);
1954                         if (!ret)
1955                                 ret = link_pipe(ipipe, opipe, len, flags);
1956                 }
1957         }
1958
1959         return ret;
1960 }
1961
1962 SYSCALL_DEFINE4(tee, int, fdin, int, fdout, size_t, len, unsigned int, flags)
1963 {
1964         struct fd in;
1965         int error;
1966
1967         if (unlikely(!len))
1968                 return 0;
1969
1970         error = -EBADF;
1971         in = fdget(fdin);
1972         if (in.file) {
1973                 if (in.file->f_mode & FMODE_READ) {
1974                         struct fd out = fdget(fdout);
1975                         if (out.file) {
1976                                 if (out.file->f_mode & FMODE_WRITE)
1977                                         error = do_tee(in.file, out.file,
1978                                                         len, flags);
1979                                 fdput(out);
1980                         }
1981                 }
1982                 fdput(in);
1983         }
1984
1985         return error;
1986 }