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