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