1 // SPDX-License-Identifier: GPL-2.0-only
3 * "splice": joining two ropes together by interweaving their strands.
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.
9 * The traditional unix read/write is extended with a "splice()" operation
10 * that transfers data buffers to or from a pipe buffer.
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.
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>
21 #include <linux/bvec.h>
23 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/splice.h>
26 #include <linux/memcontrol.h>
27 #include <linux/mm_inline.h>
28 #include <linux/swap.h>
29 #include <linux/writeback.h>
30 #include <linux/export.h>
31 #include <linux/syscalls.h>
32 #include <linux/uio.h>
33 #include <linux/fsnotify.h>
34 #include <linux/security.h>
35 #include <linux/gfp.h>
36 #include <linux/socket.h>
37 #include <linux/sched/signal.h>
42 * Splice doesn't support FMODE_NOWAIT. Since pipes may set this flag to
43 * indicate they support non-blocking reads or writes, we must clear it
44 * here if set to avoid blocking other users of this pipe if splice is
47 static noinline void noinline pipe_clear_nowait(struct file *file)
49 fmode_t fmode = READ_ONCE(file->f_mode);
52 if (!(fmode & FMODE_NOWAIT))
54 } while (!try_cmpxchg(&file->f_mode, &fmode, fmode & ~FMODE_NOWAIT));
58 * Attempt to steal a page from a pipe buffer. This should perhaps go into
59 * a vm helper function, it's already simplified quite a bit by the
60 * addition of remove_mapping(). If success is returned, the caller may
61 * attempt to reuse this page for another destination.
63 static bool page_cache_pipe_buf_try_steal(struct pipe_inode_info *pipe,
64 struct pipe_buffer *buf)
66 struct folio *folio = page_folio(buf->page);
67 struct address_space *mapping;
71 mapping = folio_mapping(folio);
73 WARN_ON(!folio_test_uptodate(folio));
76 * At least for ext2 with nobh option, we need to wait on
77 * writeback completing on this folio, since we'll remove it
78 * from the pagecache. Otherwise truncate wont wait on the
79 * folio, allowing the disk blocks to be reused by someone else
80 * before we actually wrote our data to them. fs corruption
83 folio_wait_writeback(folio);
85 if (folio_has_private(folio) &&
86 !filemap_release_folio(folio, GFP_KERNEL))
90 * If we succeeded in removing the mapping, set LRU flag
93 if (remove_mapping(mapping, folio)) {
94 buf->flags |= PIPE_BUF_FLAG_LRU;
100 * Raced with truncate or failed to remove folio from current
101 * address space, unlock and return failure.
108 static void page_cache_pipe_buf_release(struct pipe_inode_info *pipe,
109 struct pipe_buffer *buf)
112 buf->flags &= ~PIPE_BUF_FLAG_LRU;
116 * Check whether the contents of buf is OK to access. Since the content
117 * is a page cache page, IO may be in flight.
119 static int page_cache_pipe_buf_confirm(struct pipe_inode_info *pipe,
120 struct pipe_buffer *buf)
122 struct page *page = buf->page;
125 if (!PageUptodate(page)) {
129 * Page got truncated/unhashed. This will cause a 0-byte
130 * splice, if this is the first page.
132 if (!page->mapping) {
138 * Uh oh, read-error from disk.
140 if (!PageUptodate(page)) {
146 * Page is ok afterall, we are done.
157 const struct pipe_buf_operations page_cache_pipe_buf_ops = {
158 .confirm = page_cache_pipe_buf_confirm,
159 .release = page_cache_pipe_buf_release,
160 .try_steal = page_cache_pipe_buf_try_steal,
161 .get = generic_pipe_buf_get,
164 static bool user_page_pipe_buf_try_steal(struct pipe_inode_info *pipe,
165 struct pipe_buffer *buf)
167 if (!(buf->flags & PIPE_BUF_FLAG_GIFT))
170 buf->flags |= PIPE_BUF_FLAG_LRU;
171 return generic_pipe_buf_try_steal(pipe, buf);
174 static const struct pipe_buf_operations user_page_pipe_buf_ops = {
175 .release = page_cache_pipe_buf_release,
176 .try_steal = user_page_pipe_buf_try_steal,
177 .get = generic_pipe_buf_get,
180 static void wakeup_pipe_readers(struct pipe_inode_info *pipe)
183 if (waitqueue_active(&pipe->rd_wait))
184 wake_up_interruptible(&pipe->rd_wait);
185 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
189 * splice_to_pipe - fill passed data into a pipe
190 * @pipe: pipe to fill
194 * @spd contains a map of pages and len/offset tuples, along with
195 * the struct pipe_buf_operations associated with these pages. This
196 * function will link that data to the pipe.
199 ssize_t splice_to_pipe(struct pipe_inode_info *pipe,
200 struct splice_pipe_desc *spd)
202 unsigned int spd_pages = spd->nr_pages;
203 unsigned int tail = pipe->tail;
204 unsigned int head = pipe->head;
205 unsigned int mask = pipe->ring_size - 1;
206 int ret = 0, page_nr = 0;
211 if (unlikely(!pipe->readers)) {
212 send_sig(SIGPIPE, current, 0);
217 while (!pipe_full(head, tail, pipe->max_usage)) {
218 struct pipe_buffer *buf = &pipe->bufs[head & mask];
220 buf->page = spd->pages[page_nr];
221 buf->offset = spd->partial[page_nr].offset;
222 buf->len = spd->partial[page_nr].len;
223 buf->private = spd->partial[page_nr].private;
232 if (!--spd->nr_pages)
240 while (page_nr < spd_pages)
241 spd->spd_release(spd, page_nr++);
245 EXPORT_SYMBOL_GPL(splice_to_pipe);
247 ssize_t add_to_pipe(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
249 unsigned int head = pipe->head;
250 unsigned int tail = pipe->tail;
251 unsigned int mask = pipe->ring_size - 1;
254 if (unlikely(!pipe->readers)) {
255 send_sig(SIGPIPE, current, 0);
257 } else if (pipe_full(head, tail, pipe->max_usage)) {
260 pipe->bufs[head & mask] = *buf;
261 pipe->head = head + 1;
264 pipe_buf_release(pipe, buf);
267 EXPORT_SYMBOL(add_to_pipe);
270 * Check if we need to grow the arrays holding pages and partial page
273 int splice_grow_spd(const struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
275 unsigned int max_usage = READ_ONCE(pipe->max_usage);
277 spd->nr_pages_max = max_usage;
278 if (max_usage <= PIPE_DEF_BUFFERS)
281 spd->pages = kmalloc_array(max_usage, sizeof(struct page *), GFP_KERNEL);
282 spd->partial = kmalloc_array(max_usage, sizeof(struct partial_page),
285 if (spd->pages && spd->partial)
293 void splice_shrink_spd(struct splice_pipe_desc *spd)
295 if (spd->nr_pages_max <= PIPE_DEF_BUFFERS)
303 * Splice data from an O_DIRECT file into pages and then add them to the output
306 ssize_t direct_splice_read(struct file *in, loff_t *ppos,
307 struct pipe_inode_info *pipe,
308 size_t len, unsigned int flags)
315 size_t used, npages, chunk, remain, reclaim;
318 /* Work out how much data we can actually add into the pipe */
319 used = pipe_occupancy(pipe->head, pipe->tail);
320 npages = max_t(ssize_t, pipe->max_usage - used, 0);
321 len = min_t(size_t, len, npages * PAGE_SIZE);
322 npages = DIV_ROUND_UP(len, PAGE_SIZE);
324 bv = kzalloc(array_size(npages, sizeof(bv[0])) +
325 array_size(npages, sizeof(struct page *)), GFP_KERNEL);
329 pages = (void *)(bv + npages);
330 npages = alloc_pages_bulk_array(GFP_USER, npages, pages);
336 remain = len = min_t(size_t, len, npages * PAGE_SIZE);
338 for (i = 0; i < npages; i++) {
339 chunk = min_t(size_t, PAGE_SIZE, remain);
340 bv[i].bv_page = pages[i];
342 bv[i].bv_len = chunk;
347 iov_iter_bvec(&to, ITER_DEST, bv, npages, len);
348 init_sync_kiocb(&kiocb, in);
349 kiocb.ki_pos = *ppos;
350 ret = call_read_iter(in, &kiocb, &to);
352 reclaim = npages * PAGE_SIZE;
357 *ppos = kiocb.ki_pos;
359 } else if (ret < 0) {
361 * callers of ->splice_read() expect -EAGAIN on
362 * "can't put anything in there", rather than -EFAULT.
368 /* Free any pages that didn't get touched at all. */
369 reclaim /= PAGE_SIZE;
372 release_pages(pages + npages, reclaim);
375 /* Push the remaining pages into the pipe. */
376 for (i = 0; i < npages; i++) {
377 struct pipe_buffer *buf = pipe_head_buf(pipe);
379 chunk = min_t(size_t, remain, PAGE_SIZE);
380 *buf = (struct pipe_buffer) {
381 .ops = &default_pipe_buf_ops,
382 .page = bv[i].bv_page,
393 EXPORT_SYMBOL(direct_splice_read);
396 * generic_file_splice_read - splice data from file to a pipe
397 * @in: file to splice from
398 * @ppos: position in @in
399 * @pipe: pipe to splice to
400 * @len: number of bytes to splice
401 * @flags: splice modifier flags
404 * Will read pages from given file and fill them into a pipe. Can be
405 * used as long as it has more or less sane ->read_iter().
408 ssize_t generic_file_splice_read(struct file *in, loff_t *ppos,
409 struct pipe_inode_info *pipe, size_t len,
416 iov_iter_pipe(&to, ITER_DEST, pipe, len);
417 init_sync_kiocb(&kiocb, in);
418 kiocb.ki_pos = *ppos;
419 ret = call_read_iter(in, &kiocb, &to);
421 *ppos = kiocb.ki_pos;
423 } else if (ret < 0) {
424 /* free what was emitted */
425 pipe_discard_from(pipe, to.start_head);
427 * callers of ->splice_read() expect -EAGAIN on
428 * "can't put anything in there", rather than -EFAULT.
436 EXPORT_SYMBOL(generic_file_splice_read);
438 const struct pipe_buf_operations default_pipe_buf_ops = {
439 .release = generic_pipe_buf_release,
440 .try_steal = generic_pipe_buf_try_steal,
441 .get = generic_pipe_buf_get,
444 /* Pipe buffer operations for a socket and similar. */
445 const struct pipe_buf_operations nosteal_pipe_buf_ops = {
446 .release = generic_pipe_buf_release,
447 .get = generic_pipe_buf_get,
449 EXPORT_SYMBOL(nosteal_pipe_buf_ops);
452 * Send 'sd->len' bytes to socket from 'sd->file' at position 'sd->pos'
453 * using sendpage(). Return the number of bytes sent.
455 static int pipe_to_sendpage(struct pipe_inode_info *pipe,
456 struct pipe_buffer *buf, struct splice_desc *sd)
458 struct file *file = sd->u.file;
459 loff_t pos = sd->pos;
462 if (!likely(file->f_op->sendpage))
465 more = (sd->flags & SPLICE_F_MORE) ? MSG_MORE : 0;
467 if (sd->len < sd->total_len &&
468 pipe_occupancy(pipe->head, pipe->tail) > 1)
469 more |= MSG_SENDPAGE_NOTLAST;
471 return file->f_op->sendpage(file, buf->page, buf->offset,
472 sd->len, &pos, more);
475 static void wakeup_pipe_writers(struct pipe_inode_info *pipe)
478 if (waitqueue_active(&pipe->wr_wait))
479 wake_up_interruptible(&pipe->wr_wait);
480 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
484 * splice_from_pipe_feed - feed available data from a pipe to a file
485 * @pipe: pipe to splice from
486 * @sd: information to @actor
487 * @actor: handler that splices the data
490 * This function loops over the pipe and calls @actor to do the
491 * actual moving of a single struct pipe_buffer to the desired
492 * destination. It returns when there's no more buffers left in
493 * the pipe or if the requested number of bytes (@sd->total_len)
494 * have been copied. It returns a positive number (one) if the
495 * pipe needs to be filled with more data, zero if the required
496 * number of bytes have been copied and -errno on error.
498 * This, together with splice_from_pipe_{begin,end,next}, may be
499 * used to implement the functionality of __splice_from_pipe() when
500 * locking is required around copying the pipe buffers to the
503 static int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
506 unsigned int head = pipe->head;
507 unsigned int tail = pipe->tail;
508 unsigned int mask = pipe->ring_size - 1;
511 while (!pipe_empty(head, tail)) {
512 struct pipe_buffer *buf = &pipe->bufs[tail & mask];
515 if (sd->len > sd->total_len)
516 sd->len = sd->total_len;
518 ret = pipe_buf_confirm(pipe, buf);
525 ret = actor(pipe, buf, sd);
532 sd->num_spliced += ret;
535 sd->total_len -= ret;
538 pipe_buf_release(pipe, buf);
542 sd->need_wakeup = true;
552 /* We know we have a pipe buffer, but maybe it's empty? */
553 static inline bool eat_empty_buffer(struct pipe_inode_info *pipe)
555 unsigned int tail = pipe->tail;
556 unsigned int mask = pipe->ring_size - 1;
557 struct pipe_buffer *buf = &pipe->bufs[tail & mask];
559 if (unlikely(!buf->len)) {
560 pipe_buf_release(pipe, buf);
569 * splice_from_pipe_next - wait for some data to splice from
570 * @pipe: pipe to splice from
571 * @sd: information about the splice operation
574 * This function will wait for some data and return a positive
575 * value (one) if pipe buffers are available. It will return zero
576 * or -errno if no more data needs to be spliced.
578 static int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
581 * Check for signal early to make process killable when there are
582 * always buffers available
584 if (signal_pending(current))
588 while (pipe_empty(pipe->head, pipe->tail)) {
595 if (sd->flags & SPLICE_F_NONBLOCK)
598 if (signal_pending(current))
601 if (sd->need_wakeup) {
602 wakeup_pipe_writers(pipe);
603 sd->need_wakeup = false;
606 pipe_wait_readable(pipe);
609 if (eat_empty_buffer(pipe))
616 * splice_from_pipe_begin - start splicing from pipe
617 * @sd: information about the splice operation
620 * This function should be called before a loop containing
621 * splice_from_pipe_next() and splice_from_pipe_feed() to
622 * initialize the necessary fields of @sd.
624 static void splice_from_pipe_begin(struct splice_desc *sd)
627 sd->need_wakeup = false;
631 * splice_from_pipe_end - finish splicing from pipe
632 * @pipe: pipe to splice from
633 * @sd: information about the splice operation
636 * This function will wake up pipe writers if necessary. It should
637 * be called after a loop containing splice_from_pipe_next() and
638 * splice_from_pipe_feed().
640 static void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
643 wakeup_pipe_writers(pipe);
647 * __splice_from_pipe - splice data from a pipe to given actor
648 * @pipe: pipe to splice from
649 * @sd: information to @actor
650 * @actor: handler that splices the data
653 * This function does little more than loop over the pipe and call
654 * @actor to do the actual moving of a single struct pipe_buffer to
655 * the desired destination. See pipe_to_file, pipe_to_sendpage, or
659 ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
664 splice_from_pipe_begin(sd);
667 ret = splice_from_pipe_next(pipe, sd);
669 ret = splice_from_pipe_feed(pipe, sd, actor);
671 splice_from_pipe_end(pipe, sd);
673 return sd->num_spliced ? sd->num_spliced : ret;
675 EXPORT_SYMBOL(__splice_from_pipe);
678 * splice_from_pipe - splice data from a pipe to a file
679 * @pipe: pipe to splice from
680 * @out: file to splice to
681 * @ppos: position in @out
682 * @len: how many bytes to splice
683 * @flags: splice modifier flags
684 * @actor: handler that splices the data
687 * See __splice_from_pipe. This function locks the pipe inode,
688 * otherwise it's identical to __splice_from_pipe().
691 ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
692 loff_t *ppos, size_t len, unsigned int flags,
696 struct splice_desc sd = {
704 ret = __splice_from_pipe(pipe, &sd, actor);
711 * iter_file_splice_write - splice data from a pipe to a file
713 * @out: file to write to
714 * @ppos: position in @out
715 * @len: number of bytes to splice
716 * @flags: splice modifier flags
719 * Will either move or copy pages (determined by @flags options) from
720 * the given pipe inode to the given file.
721 * This one is ->write_iter-based.
725 iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
726 loff_t *ppos, size_t len, unsigned int flags)
728 struct splice_desc sd = {
734 int nbufs = pipe->max_usage;
735 struct bio_vec *array = kcalloc(nbufs, sizeof(struct bio_vec),
739 if (unlikely(!array))
744 splice_from_pipe_begin(&sd);
745 while (sd.total_len) {
746 struct iov_iter from;
747 unsigned int head, tail, mask;
751 ret = splice_from_pipe_next(pipe, &sd);
755 if (unlikely(nbufs < pipe->max_usage)) {
757 nbufs = pipe->max_usage;
758 array = kcalloc(nbufs, sizeof(struct bio_vec),
768 mask = pipe->ring_size - 1;
770 /* build the vector */
772 for (n = 0; !pipe_empty(head, tail) && left && n < nbufs; tail++) {
773 struct pipe_buffer *buf = &pipe->bufs[tail & mask];
774 size_t this_len = buf->len;
776 /* zero-length bvecs are not supported, skip them */
779 this_len = min(this_len, left);
781 ret = pipe_buf_confirm(pipe, buf);
788 bvec_set_page(&array[n], buf->page, this_len,
794 iov_iter_bvec(&from, ITER_SOURCE, array, n, sd.total_len - left);
795 ret = vfs_iter_write(out, &from, &sd.pos, 0);
799 sd.num_spliced += ret;
803 /* dismiss the fully eaten buffers, adjust the partial one */
806 struct pipe_buffer *buf = &pipe->bufs[tail & mask];
807 if (ret >= buf->len) {
810 pipe_buf_release(pipe, buf);
814 sd.need_wakeup = true;
824 splice_from_pipe_end(pipe, &sd);
829 ret = sd.num_spliced;
834 EXPORT_SYMBOL(iter_file_splice_write);
837 * generic_splice_sendpage - splice data from a pipe to a socket
838 * @pipe: pipe to splice from
839 * @out: socket to write to
840 * @ppos: position in @out
841 * @len: number of bytes to splice
842 * @flags: splice modifier flags
845 * Will send @len bytes from the pipe to a network socket. No data copying
849 ssize_t generic_splice_sendpage(struct pipe_inode_info *pipe, struct file *out,
850 loff_t *ppos, size_t len, unsigned int flags)
852 return splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_sendpage);
855 EXPORT_SYMBOL(generic_splice_sendpage);
857 static int warn_unsupported(struct file *file, const char *op)
859 pr_debug_ratelimited(
860 "splice %s not supported for file %pD4 (pid: %d comm: %.20s)\n",
861 op, file, current->pid, current->comm);
866 * Attempt to initiate a splice from pipe to file.
868 static long do_splice_from(struct pipe_inode_info *pipe, struct file *out,
869 loff_t *ppos, size_t len, unsigned int flags)
871 if (unlikely(!out->f_op->splice_write))
872 return warn_unsupported(out, "write");
873 return out->f_op->splice_write(pipe, out, ppos, len, flags);
877 * Attempt to initiate a splice from a file to a pipe.
879 static long do_splice_to(struct file *in, loff_t *ppos,
880 struct pipe_inode_info *pipe, size_t len,
883 unsigned int p_space;
886 if (unlikely(!(in->f_mode & FMODE_READ)))
889 /* Don't try to read more the pipe has space for. */
890 p_space = pipe->max_usage - pipe_occupancy(pipe->head, pipe->tail);
891 len = min_t(size_t, len, p_space << PAGE_SHIFT);
893 ret = rw_verify_area(READ, in, ppos, len);
894 if (unlikely(ret < 0))
897 if (unlikely(len > MAX_RW_COUNT))
900 if (unlikely(!in->f_op->splice_read))
901 return warn_unsupported(in, "read");
902 return in->f_op->splice_read(in, ppos, pipe, len, flags);
906 * splice_direct_to_actor - splices data directly between two non-pipes
907 * @in: file to splice from
908 * @sd: actor information on where to splice to
909 * @actor: handles the data splicing
912 * This is a special case helper to splice directly between two
913 * points, without requiring an explicit pipe. Internally an allocated
914 * pipe is cached in the process, and reused during the lifetime of
918 ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,
919 splice_direct_actor *actor)
921 struct pipe_inode_info *pipe;
927 * We require the input to be seekable, as we don't want to randomly
928 * drop data for eg socket -> socket splicing. Use the piped splicing
931 if (unlikely(!(in->f_mode & FMODE_LSEEK)))
935 * neither in nor out is a pipe, setup an internal pipe attached to
936 * 'out' and transfer the wanted data from 'in' to 'out' through that
938 pipe = current->splice_pipe;
939 if (unlikely(!pipe)) {
940 pipe = alloc_pipe_info();
945 * We don't have an immediate reader, but we'll read the stuff
946 * out of the pipe right after the splice_to_pipe(). So set
947 * PIPE_READERS appropriately.
951 current->splice_pipe = pipe;
962 * Don't block on output, we have to drain the direct pipe.
964 sd->flags &= ~SPLICE_F_NONBLOCK;
965 more = sd->flags & SPLICE_F_MORE;
967 WARN_ON_ONCE(!pipe_empty(pipe->head, pipe->tail));
971 loff_t pos = sd->pos, prev_pos = pos;
973 ret = do_splice_to(in, &pos, pipe, len, flags);
974 if (unlikely(ret <= 0))
978 sd->total_len = read_len;
981 * If more data is pending, set SPLICE_F_MORE
982 * If this is the last data and SPLICE_F_MORE was not set
983 * initially, clears it.
986 sd->flags |= SPLICE_F_MORE;
988 sd->flags &= ~SPLICE_F_MORE;
990 * NOTE: nonblocking mode only applies to the input. We
991 * must not do the output in nonblocking mode as then we
992 * could get stuck data in the internal pipe:
994 ret = actor(pipe, sd);
995 if (unlikely(ret <= 0)) {
1004 if (ret < read_len) {
1005 sd->pos = prev_pos + ret;
1011 pipe->tail = pipe->head = 0;
1017 * If we did an incomplete transfer we must release
1018 * the pipe buffers in question:
1020 for (i = 0; i < pipe->ring_size; i++) {
1021 struct pipe_buffer *buf = &pipe->bufs[i];
1024 pipe_buf_release(pipe, buf);
1032 EXPORT_SYMBOL(splice_direct_to_actor);
1034 static int direct_splice_actor(struct pipe_inode_info *pipe,
1035 struct splice_desc *sd)
1037 struct file *file = sd->u.file;
1039 return do_splice_from(pipe, file, sd->opos, sd->total_len,
1044 * do_splice_direct - splices data directly between two files
1045 * @in: file to splice from
1046 * @ppos: input file offset
1047 * @out: file to splice to
1048 * @opos: output file offset
1049 * @len: number of bytes to splice
1050 * @flags: splice modifier flags
1053 * For use by do_sendfile(). splice can easily emulate sendfile, but
1054 * doing it in the application would incur an extra system call
1055 * (splice in + splice out, as compared to just sendfile()). So this helper
1056 * can splice directly through a process-private pipe.
1059 long do_splice_direct(struct file *in, loff_t *ppos, struct file *out,
1060 loff_t *opos, size_t len, unsigned int flags)
1062 struct splice_desc sd = {
1072 if (unlikely(!(out->f_mode & FMODE_WRITE)))
1075 if (unlikely(out->f_flags & O_APPEND))
1078 ret = rw_verify_area(WRITE, out, opos, len);
1079 if (unlikely(ret < 0))
1082 ret = splice_direct_to_actor(in, &sd, direct_splice_actor);
1088 EXPORT_SYMBOL(do_splice_direct);
1090 static int wait_for_space(struct pipe_inode_info *pipe, unsigned flags)
1093 if (unlikely(!pipe->readers)) {
1094 send_sig(SIGPIPE, current, 0);
1097 if (!pipe_full(pipe->head, pipe->tail, pipe->max_usage))
1099 if (flags & SPLICE_F_NONBLOCK)
1101 if (signal_pending(current))
1102 return -ERESTARTSYS;
1103 pipe_wait_writable(pipe);
1107 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1108 struct pipe_inode_info *opipe,
1109 size_t len, unsigned int flags);
1111 long splice_file_to_pipe(struct file *in,
1112 struct pipe_inode_info *opipe,
1114 size_t len, unsigned int flags)
1119 ret = wait_for_space(opipe, flags);
1121 ret = do_splice_to(in, offset, opipe, len, flags);
1124 wakeup_pipe_readers(opipe);
1129 * Determine where to splice to/from.
1131 long do_splice(struct file *in, loff_t *off_in, struct file *out,
1132 loff_t *off_out, size_t len, unsigned int flags)
1134 struct pipe_inode_info *ipipe;
1135 struct pipe_inode_info *opipe;
1139 if (unlikely(!(in->f_mode & FMODE_READ) ||
1140 !(out->f_mode & FMODE_WRITE)))
1143 ipipe = get_pipe_info(in, true);
1144 opipe = get_pipe_info(out, true);
1146 if (ipipe && opipe) {
1147 if (off_in || off_out)
1150 /* Splicing to self would be fun, but... */
1154 if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1155 flags |= SPLICE_F_NONBLOCK;
1157 return splice_pipe_to_pipe(ipipe, opipe, len, flags);
1164 if (!(out->f_mode & FMODE_PWRITE))
1168 offset = out->f_pos;
1171 if (unlikely(out->f_flags & O_APPEND))
1174 ret = rw_verify_area(WRITE, out, &offset, len);
1175 if (unlikely(ret < 0))
1178 if (in->f_flags & O_NONBLOCK)
1179 flags |= SPLICE_F_NONBLOCK;
1181 file_start_write(out);
1182 ret = do_splice_from(ipipe, out, &offset, len, flags);
1183 file_end_write(out);
1186 fsnotify_modify(out);
1189 out->f_pos = offset;
1200 if (!(in->f_mode & FMODE_PREAD))
1207 if (out->f_flags & O_NONBLOCK)
1208 flags |= SPLICE_F_NONBLOCK;
1210 ret = splice_file_to_pipe(in, opipe, &offset, len, flags);
1213 fsnotify_access(in);
1226 static long __do_splice(struct file *in, loff_t __user *off_in,
1227 struct file *out, loff_t __user *off_out,
1228 size_t len, unsigned int flags)
1230 struct pipe_inode_info *ipipe;
1231 struct pipe_inode_info *opipe;
1232 loff_t offset, *__off_in = NULL, *__off_out = NULL;
1235 ipipe = get_pipe_info(in, true);
1236 opipe = get_pipe_info(out, true);
1241 pipe_clear_nowait(in);
1246 pipe_clear_nowait(out);
1250 if (copy_from_user(&offset, off_out, sizeof(loff_t)))
1252 __off_out = &offset;
1255 if (copy_from_user(&offset, off_in, sizeof(loff_t)))
1260 ret = do_splice(in, __off_in, out, __off_out, len, flags);
1264 if (__off_out && copy_to_user(off_out, __off_out, sizeof(loff_t)))
1266 if (__off_in && copy_to_user(off_in, __off_in, sizeof(loff_t)))
1272 static int iter_to_pipe(struct iov_iter *from,
1273 struct pipe_inode_info *pipe,
1276 struct pipe_buffer buf = {
1277 .ops = &user_page_pipe_buf_ops,
1283 while (iov_iter_count(from)) {
1284 struct page *pages[16];
1289 left = iov_iter_get_pages2(from, pages, ~0UL, 16, &start);
1295 n = DIV_ROUND_UP(left + start, PAGE_SIZE);
1296 for (i = 0; i < n; i++) {
1297 int size = min_t(int, left, PAGE_SIZE - start);
1299 buf.page = pages[i];
1302 ret = add_to_pipe(pipe, &buf);
1303 if (unlikely(ret < 0)) {
1304 iov_iter_revert(from, left);
1305 // this one got dropped by add_to_pipe()
1316 return total ? total : ret;
1319 static int pipe_to_user(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1320 struct splice_desc *sd)
1322 int n = copy_page_to_iter(buf->page, buf->offset, sd->len, sd->u.data);
1323 return n == sd->len ? n : -EFAULT;
1327 * For lack of a better implementation, implement vmsplice() to userspace
1328 * as a simple copy of the pipes pages to the user iov.
1330 static long vmsplice_to_user(struct file *file, struct iov_iter *iter,
1333 struct pipe_inode_info *pipe = get_pipe_info(file, true);
1334 struct splice_desc sd = {
1335 .total_len = iov_iter_count(iter),
1344 pipe_clear_nowait(file);
1348 ret = __splice_from_pipe(pipe, &sd, pipe_to_user);
1356 * vmsplice splices a user address range into a pipe. It can be thought of
1357 * as splice-from-memory, where the regular splice is splice-from-file (or
1358 * to file). In both cases the output is a pipe, naturally.
1360 static long vmsplice_to_pipe(struct file *file, struct iov_iter *iter,
1363 struct pipe_inode_info *pipe;
1365 unsigned buf_flag = 0;
1367 if (flags & SPLICE_F_GIFT)
1368 buf_flag = PIPE_BUF_FLAG_GIFT;
1370 pipe = get_pipe_info(file, true);
1374 pipe_clear_nowait(file);
1377 ret = wait_for_space(pipe, flags);
1379 ret = iter_to_pipe(iter, pipe, buf_flag);
1382 wakeup_pipe_readers(pipe);
1386 static int vmsplice_type(struct fd f, int *type)
1390 if (f.file->f_mode & FMODE_WRITE) {
1391 *type = ITER_SOURCE;
1392 } else if (f.file->f_mode & FMODE_READ) {
1402 * Note that vmsplice only really supports true splicing _from_ user memory
1403 * to a pipe, not the other way around. Splicing from user memory is a simple
1404 * operation that can be supported without any funky alignment restrictions
1405 * or nasty vm tricks. We simply map in the user memory and fill them into
1406 * a pipe. The reverse isn't quite as easy, though. There are two possible
1407 * solutions for that:
1409 * - memcpy() the data internally, at which point we might as well just
1410 * do a regular read() on the buffer anyway.
1411 * - Lots of nasty vm tricks, that are neither fast nor flexible (it
1412 * has restriction limitations on both ends of the pipe).
1414 * Currently we punt and implement it as a normal copy, see pipe_to_user().
1417 SYSCALL_DEFINE4(vmsplice, int, fd, const struct iovec __user *, uiov,
1418 unsigned long, nr_segs, unsigned int, flags)
1420 struct iovec iovstack[UIO_FASTIOV];
1421 struct iovec *iov = iovstack;
1422 struct iov_iter iter;
1427 if (unlikely(flags & ~SPLICE_F_ALL))
1431 error = vmsplice_type(f, &type);
1435 error = import_iovec(type, uiov, nr_segs,
1436 ARRAY_SIZE(iovstack), &iov, &iter);
1440 if (!iov_iter_count(&iter))
1442 else if (type == ITER_SOURCE)
1443 error = vmsplice_to_pipe(f.file, &iter, flags);
1445 error = vmsplice_to_user(f.file, &iter, flags);
1453 SYSCALL_DEFINE6(splice, int, fd_in, loff_t __user *, off_in,
1454 int, fd_out, loff_t __user *, off_out,
1455 size_t, len, unsigned int, flags)
1463 if (unlikely(flags & ~SPLICE_F_ALL))
1469 out = fdget(fd_out);
1471 error = __do_splice(in.file, off_in, out.file, off_out,
1481 * Make sure there's data to read. Wait for input if we can, otherwise
1482 * return an appropriate error.
1484 static int ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1489 * Check the pipe occupancy without the inode lock first. This function
1490 * is speculative anyways, so missing one is ok.
1492 if (!pipe_empty(pipe->head, pipe->tail))
1498 while (pipe_empty(pipe->head, pipe->tail)) {
1499 if (signal_pending(current)) {
1505 if (flags & SPLICE_F_NONBLOCK) {
1509 pipe_wait_readable(pipe);
1517 * Make sure there's writeable room. Wait for room if we can, otherwise
1518 * return an appropriate error.
1520 static int opipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1525 * Check pipe occupancy without the inode lock first. This function
1526 * is speculative anyways, so missing one is ok.
1528 if (!pipe_full(pipe->head, pipe->tail, pipe->max_usage))
1534 while (pipe_full(pipe->head, pipe->tail, pipe->max_usage)) {
1535 if (!pipe->readers) {
1536 send_sig(SIGPIPE, current, 0);
1540 if (flags & SPLICE_F_NONBLOCK) {
1544 if (signal_pending(current)) {
1548 pipe_wait_writable(pipe);
1556 * Splice contents of ipipe to opipe.
1558 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1559 struct pipe_inode_info *opipe,
1560 size_t len, unsigned int flags)
1562 struct pipe_buffer *ibuf, *obuf;
1563 unsigned int i_head, o_head;
1564 unsigned int i_tail, o_tail;
1565 unsigned int i_mask, o_mask;
1567 bool input_wakeup = false;
1571 ret = ipipe_prep(ipipe, flags);
1575 ret = opipe_prep(opipe, flags);
1580 * Potential ABBA deadlock, work around it by ordering lock
1581 * grabbing by pipe info address. Otherwise two different processes
1582 * could deadlock (one doing tee from A -> B, the other from B -> A).
1584 pipe_double_lock(ipipe, opipe);
1586 i_tail = ipipe->tail;
1587 i_mask = ipipe->ring_size - 1;
1588 o_head = opipe->head;
1589 o_mask = opipe->ring_size - 1;
1594 if (!opipe->readers) {
1595 send_sig(SIGPIPE, current, 0);
1601 i_head = ipipe->head;
1602 o_tail = opipe->tail;
1604 if (pipe_empty(i_head, i_tail) && !ipipe->writers)
1608 * Cannot make any progress, because either the input
1609 * pipe is empty or the output pipe is full.
1611 if (pipe_empty(i_head, i_tail) ||
1612 pipe_full(o_head, o_tail, opipe->max_usage)) {
1613 /* Already processed some buffers, break */
1617 if (flags & SPLICE_F_NONBLOCK) {
1623 * We raced with another reader/writer and haven't
1624 * managed to process any buffers. A zero return
1625 * value means EOF, so retry instead.
1632 ibuf = &ipipe->bufs[i_tail & i_mask];
1633 obuf = &opipe->bufs[o_head & o_mask];
1635 if (len >= ibuf->len) {
1637 * Simply move the whole buffer from ipipe to opipe
1642 ipipe->tail = i_tail;
1643 input_wakeup = true;
1646 opipe->head = o_head;
1649 * Get a reference to this pipe buffer,
1650 * so we can copy the contents over.
1652 if (!pipe_buf_get(ipipe, ibuf)) {
1660 * Don't inherit the gift and merge flags, we need to
1661 * prevent multiple steals of this page.
1663 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1664 obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1667 ibuf->offset += len;
1671 opipe->head = o_head;
1681 * If we put data in the output pipe, wakeup any potential readers.
1684 wakeup_pipe_readers(opipe);
1687 wakeup_pipe_writers(ipipe);
1693 * Link contents of ipipe to opipe.
1695 static int link_pipe(struct pipe_inode_info *ipipe,
1696 struct pipe_inode_info *opipe,
1697 size_t len, unsigned int flags)
1699 struct pipe_buffer *ibuf, *obuf;
1700 unsigned int i_head, o_head;
1701 unsigned int i_tail, o_tail;
1702 unsigned int i_mask, o_mask;
1706 * Potential ABBA deadlock, work around it by ordering lock
1707 * grabbing by pipe info address. Otherwise two different processes
1708 * could deadlock (one doing tee from A -> B, the other from B -> A).
1710 pipe_double_lock(ipipe, opipe);
1712 i_tail = ipipe->tail;
1713 i_mask = ipipe->ring_size - 1;
1714 o_head = opipe->head;
1715 o_mask = opipe->ring_size - 1;
1718 if (!opipe->readers) {
1719 send_sig(SIGPIPE, current, 0);
1725 i_head = ipipe->head;
1726 o_tail = opipe->tail;
1729 * If we have iterated all input buffers or run out of
1730 * output room, break.
1732 if (pipe_empty(i_head, i_tail) ||
1733 pipe_full(o_head, o_tail, opipe->max_usage))
1736 ibuf = &ipipe->bufs[i_tail & i_mask];
1737 obuf = &opipe->bufs[o_head & o_mask];
1740 * Get a reference to this pipe buffer,
1741 * so we can copy the contents over.
1743 if (!pipe_buf_get(ipipe, ibuf)) {
1752 * Don't inherit the gift and merge flag, we need to prevent
1753 * multiple steals of this page.
1755 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1756 obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1758 if (obuf->len > len)
1764 opipe->head = o_head;
1772 * If we put data in the output pipe, wakeup any potential readers.
1775 wakeup_pipe_readers(opipe);
1781 * This is a tee(1) implementation that works on pipes. It doesn't copy
1782 * any data, it simply references the 'in' pages on the 'out' pipe.
1783 * The 'flags' used are the SPLICE_F_* variants, currently the only
1784 * applicable one is SPLICE_F_NONBLOCK.
1786 long do_tee(struct file *in, struct file *out, size_t len, unsigned int flags)
1788 struct pipe_inode_info *ipipe = get_pipe_info(in, true);
1789 struct pipe_inode_info *opipe = get_pipe_info(out, true);
1792 if (unlikely(!(in->f_mode & FMODE_READ) ||
1793 !(out->f_mode & FMODE_WRITE)))
1797 * Duplicate the contents of ipipe to opipe without actually
1800 if (ipipe && opipe && ipipe != opipe) {
1801 if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1802 flags |= SPLICE_F_NONBLOCK;
1805 * Keep going, unless we encounter an error. The ipipe/opipe
1806 * ordering doesn't really matter.
1808 ret = ipipe_prep(ipipe, flags);
1810 ret = opipe_prep(opipe, flags);
1812 ret = link_pipe(ipipe, opipe, len, flags);
1819 SYSCALL_DEFINE4(tee, int, fdin, int, fdout, size_t, len, unsigned int, flags)
1824 if (unlikely(flags & ~SPLICE_F_ALL))
1835 error = do_tee(in.file, out.file, len, flags);