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