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