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