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