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