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/net.h>
37 #include <linux/socket.h>
38 #include <linux/sched/signal.h>
43 * Splice doesn't support FMODE_NOWAIT. Since pipes may set this flag to
44 * indicate they support non-blocking reads or writes, we must clear it
45 * here if set to avoid blocking other users of this pipe if splice is
48 static noinline void pipe_clear_nowait(struct file *file)
50 fmode_t fmode = READ_ONCE(file->f_mode);
53 if (!(fmode & FMODE_NOWAIT))
55 } while (!try_cmpxchg(&file->f_mode, &fmode, fmode & ~FMODE_NOWAIT));
59 * Attempt to steal a page from a pipe buffer. This should perhaps go into
60 * a vm helper function, it's already simplified quite a bit by the
61 * addition of remove_mapping(). If success is returned, the caller may
62 * attempt to reuse this page for another destination.
64 static bool page_cache_pipe_buf_try_steal(struct pipe_inode_info *pipe,
65 struct pipe_buffer *buf)
67 struct folio *folio = page_folio(buf->page);
68 struct address_space *mapping;
72 mapping = folio_mapping(folio);
74 WARN_ON(!folio_test_uptodate(folio));
77 * At least for ext2 with nobh option, we need to wait on
78 * writeback completing on this folio, since we'll remove it
79 * from the pagecache. Otherwise truncate wont wait on the
80 * folio, allowing the disk blocks to be reused by someone else
81 * before we actually wrote our data to them. fs corruption
84 folio_wait_writeback(folio);
86 if (!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 folio *folio = page_folio(buf->page);
125 if (!folio_test_uptodate(folio)) {
129 * Folio got truncated/unhashed. This will cause a 0-byte
130 * splice, if this is the first page.
132 if (!folio->mapping) {
138 * Uh oh, read-error from disk.
140 if (!folio_test_uptodate(folio)) {
145 /* Folio is ok after all, we are done */
155 const struct pipe_buf_operations page_cache_pipe_buf_ops = {
156 .confirm = page_cache_pipe_buf_confirm,
157 .release = page_cache_pipe_buf_release,
158 .try_steal = page_cache_pipe_buf_try_steal,
159 .get = generic_pipe_buf_get,
162 static bool user_page_pipe_buf_try_steal(struct pipe_inode_info *pipe,
163 struct pipe_buffer *buf)
165 if (!(buf->flags & PIPE_BUF_FLAG_GIFT))
168 buf->flags |= PIPE_BUF_FLAG_LRU;
169 return generic_pipe_buf_try_steal(pipe, buf);
172 static const struct pipe_buf_operations user_page_pipe_buf_ops = {
173 .release = page_cache_pipe_buf_release,
174 .try_steal = user_page_pipe_buf_try_steal,
175 .get = generic_pipe_buf_get,
178 static void wakeup_pipe_readers(struct pipe_inode_info *pipe)
181 if (waitqueue_active(&pipe->rd_wait))
182 wake_up_interruptible(&pipe->rd_wait);
183 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
187 * splice_to_pipe - fill passed data into a pipe
188 * @pipe: pipe to fill
192 * @spd contains a map of pages and len/offset tuples, along with
193 * the struct pipe_buf_operations associated with these pages. This
194 * function will link that data to the pipe.
197 ssize_t splice_to_pipe(struct pipe_inode_info *pipe,
198 struct splice_pipe_desc *spd)
200 unsigned int spd_pages = spd->nr_pages;
201 unsigned int tail = pipe->tail;
202 unsigned int head = pipe->head;
209 if (unlikely(!pipe->readers)) {
210 send_sig(SIGPIPE, current, 0);
215 while (!pipe_full(head, tail, pipe->max_usage)) {
216 struct pipe_buffer *buf = pipe_buf(pipe, head);
218 buf->page = spd->pages[page_nr];
219 buf->offset = spd->partial[page_nr].offset;
220 buf->len = spd->partial[page_nr].len;
221 buf->private = spd->partial[page_nr].private;
230 if (!--spd->nr_pages)
238 while (page_nr < spd_pages)
239 spd->spd_release(spd, page_nr++);
243 EXPORT_SYMBOL_GPL(splice_to_pipe);
245 ssize_t add_to_pipe(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
247 unsigned int head = pipe->head;
248 unsigned int tail = pipe->tail;
251 if (unlikely(!pipe->readers)) {
252 send_sig(SIGPIPE, current, 0);
254 } else if (pipe_full(head, tail, pipe->max_usage)) {
257 *pipe_buf(pipe, head) = *buf;
258 pipe->head = head + 1;
261 pipe_buf_release(pipe, buf);
264 EXPORT_SYMBOL(add_to_pipe);
267 * Check if we need to grow the arrays holding pages and partial page
270 int splice_grow_spd(const struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
272 unsigned int max_usage = READ_ONCE(pipe->max_usage);
274 spd->nr_pages_max = max_usage;
275 if (max_usage <= PIPE_DEF_BUFFERS)
278 spd->pages = kmalloc_array(max_usage, sizeof(struct page *), GFP_KERNEL);
279 spd->partial = kmalloc_array(max_usage, sizeof(struct partial_page),
282 if (spd->pages && spd->partial)
290 void splice_shrink_spd(struct splice_pipe_desc *spd)
292 if (spd->nr_pages_max <= PIPE_DEF_BUFFERS)
300 * copy_splice_read - Copy data from a file and splice the copy into a pipe
301 * @in: The file to read from
302 * @ppos: Pointer to the file position to read from
303 * @pipe: The pipe to splice into
304 * @len: The amount to splice
305 * @flags: The SPLICE_F_* flags
307 * This function allocates a bunch of pages sufficient to hold the requested
308 * amount of data (but limited by the remaining pipe capacity), passes it to
309 * the file's ->read_iter() to read into and then splices the used pages into
312 * Return: On success, the number of bytes read will be returned and *@ppos
313 * will be updated if appropriate; 0 will be returned if there is no more data
314 * to be read; -EAGAIN will be returned if the pipe had no space, and some
315 * other negative error code will be returned on error. A short read may occur
316 * if the pipe has insufficient space, we reach the end of the data or we hit a
319 ssize_t copy_splice_read(struct file *in, loff_t *ppos,
320 struct pipe_inode_info *pipe,
321 size_t len, unsigned int flags)
328 size_t used, npages, chunk, remain, keep = 0;
331 /* Work out how much data we can actually add into the pipe */
332 used = pipe_buf_usage(pipe);
333 npages = max_t(ssize_t, pipe->max_usage - used, 0);
334 len = min_t(size_t, len, npages * PAGE_SIZE);
335 npages = DIV_ROUND_UP(len, PAGE_SIZE);
337 bv = kzalloc(array_size(npages, sizeof(bv[0])) +
338 array_size(npages, sizeof(struct page *)), GFP_KERNEL);
342 pages = (struct page **)(bv + npages);
343 npages = alloc_pages_bulk(GFP_USER, npages, pages);
349 remain = len = min_t(size_t, len, npages * PAGE_SIZE);
351 for (i = 0; i < npages; i++) {
352 chunk = min_t(size_t, PAGE_SIZE, remain);
353 bv[i].bv_page = pages[i];
355 bv[i].bv_len = chunk;
360 iov_iter_bvec(&to, ITER_DEST, bv, npages, len);
361 init_sync_kiocb(&kiocb, in);
362 kiocb.ki_pos = *ppos;
363 ret = in->f_op->read_iter(&kiocb, &to);
366 keep = DIV_ROUND_UP(ret, PAGE_SIZE);
367 *ppos = kiocb.ki_pos;
371 * Callers of ->splice_read() expect -EAGAIN on "can't put anything in
372 * there", rather than -EFAULT.
377 /* Free any pages that didn't get touched at all. */
379 release_pages(pages + keep, npages - keep);
381 /* Push the remaining pages into the pipe. */
383 for (i = 0; i < keep; i++) {
384 struct pipe_buffer *buf = pipe_head_buf(pipe);
386 chunk = min_t(size_t, remain, PAGE_SIZE);
387 *buf = (struct pipe_buffer) {
388 .ops = &default_pipe_buf_ops,
389 .page = bv[i].bv_page,
400 EXPORT_SYMBOL(copy_splice_read);
402 const struct pipe_buf_operations default_pipe_buf_ops = {
403 .release = generic_pipe_buf_release,
404 .try_steal = generic_pipe_buf_try_steal,
405 .get = generic_pipe_buf_get,
408 /* Pipe buffer operations for a socket and similar. */
409 const struct pipe_buf_operations nosteal_pipe_buf_ops = {
410 .release = generic_pipe_buf_release,
411 .get = generic_pipe_buf_get,
413 EXPORT_SYMBOL(nosteal_pipe_buf_ops);
415 static void wakeup_pipe_writers(struct pipe_inode_info *pipe)
418 if (waitqueue_active(&pipe->wr_wait))
419 wake_up_interruptible(&pipe->wr_wait);
420 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
424 * splice_from_pipe_feed - feed available data from a pipe to a file
425 * @pipe: pipe to splice from
426 * @sd: information to @actor
427 * @actor: handler that splices the data
430 * This function loops over the pipe and calls @actor to do the
431 * actual moving of a single struct pipe_buffer to the desired
432 * destination. It returns when there's no more buffers left in
433 * the pipe or if the requested number of bytes (@sd->total_len)
434 * have been copied. It returns a positive number (one) if the
435 * pipe needs to be filled with more data, zero if the required
436 * number of bytes have been copied and -errno on error.
438 * This, together with splice_from_pipe_{begin,end,next}, may be
439 * used to implement the functionality of __splice_from_pipe() when
440 * locking is required around copying the pipe buffers to the
443 static int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
446 unsigned int head = pipe->head;
447 unsigned int tail = pipe->tail;
450 while (!pipe_empty(head, tail)) {
451 struct pipe_buffer *buf = pipe_buf(pipe, tail);
454 if (sd->len > sd->total_len)
455 sd->len = sd->total_len;
457 ret = pipe_buf_confirm(pipe, buf);
464 ret = actor(pipe, buf, sd);
471 sd->num_spliced += ret;
474 sd->total_len -= ret;
477 pipe_buf_release(pipe, buf);
481 sd->need_wakeup = true;
491 /* We know we have a pipe buffer, but maybe it's empty? */
492 static inline bool eat_empty_buffer(struct pipe_inode_info *pipe)
494 unsigned int tail = pipe->tail;
495 struct pipe_buffer *buf = pipe_buf(pipe, tail);
497 if (unlikely(!buf->len)) {
498 pipe_buf_release(pipe, buf);
507 * splice_from_pipe_next - wait for some data to splice from
508 * @pipe: pipe to splice from
509 * @sd: information about the splice operation
512 * This function will wait for some data and return a positive
513 * value (one) if pipe buffers are available. It will return zero
514 * or -errno if no more data needs to be spliced.
516 static int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
519 * Check for signal early to make process killable when there are
520 * always buffers available
522 if (signal_pending(current))
526 while (pipe_is_empty(pipe)) {
533 if (sd->flags & SPLICE_F_NONBLOCK)
536 if (signal_pending(current))
539 if (sd->need_wakeup) {
540 wakeup_pipe_writers(pipe);
541 sd->need_wakeup = false;
544 pipe_wait_readable(pipe);
547 if (eat_empty_buffer(pipe))
554 * splice_from_pipe_begin - start splicing from pipe
555 * @sd: information about the splice operation
558 * This function should be called before a loop containing
559 * splice_from_pipe_next() and splice_from_pipe_feed() to
560 * initialize the necessary fields of @sd.
562 static void splice_from_pipe_begin(struct splice_desc *sd)
565 sd->need_wakeup = false;
569 * splice_from_pipe_end - finish splicing from pipe
570 * @pipe: pipe to splice from
571 * @sd: information about the splice operation
574 * This function will wake up pipe writers if necessary. It should
575 * be called after a loop containing splice_from_pipe_next() and
576 * splice_from_pipe_feed().
578 static void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
581 wakeup_pipe_writers(pipe);
585 * __splice_from_pipe - splice data from a pipe to given actor
586 * @pipe: pipe to splice from
587 * @sd: information to @actor
588 * @actor: handler that splices the data
591 * This function does little more than loop over the pipe and call
592 * @actor to do the actual moving of a single struct pipe_buffer to
593 * the desired destination. See pipe_to_file, pipe_to_sendmsg, or
597 ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
602 splice_from_pipe_begin(sd);
605 ret = splice_from_pipe_next(pipe, sd);
607 ret = splice_from_pipe_feed(pipe, sd, actor);
609 splice_from_pipe_end(pipe, sd);
611 return sd->num_spliced ? sd->num_spliced : ret;
613 EXPORT_SYMBOL(__splice_from_pipe);
616 * splice_from_pipe - splice data from a pipe to a file
617 * @pipe: pipe to splice from
618 * @out: file to splice to
619 * @ppos: position in @out
620 * @len: how many bytes to splice
621 * @flags: splice modifier flags
622 * @actor: handler that splices the data
625 * See __splice_from_pipe. This function locks the pipe inode,
626 * otherwise it's identical to __splice_from_pipe().
629 ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
630 loff_t *ppos, size_t len, unsigned int flags,
634 struct splice_desc sd = {
642 ret = __splice_from_pipe(pipe, &sd, actor);
649 * iter_file_splice_write - splice data from a pipe to a file
651 * @out: file to write to
652 * @ppos: position in @out
653 * @len: number of bytes to splice
654 * @flags: splice modifier flags
657 * Will either move or copy pages (determined by @flags options) from
658 * the given pipe inode to the given file.
659 * This one is ->write_iter-based.
663 iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
664 loff_t *ppos, size_t len, unsigned int flags)
666 struct splice_desc sd = {
672 int nbufs = pipe->max_usage;
673 struct bio_vec *array;
676 if (!out->f_op->write_iter)
679 array = kcalloc(nbufs, sizeof(struct bio_vec), GFP_KERNEL);
680 if (unlikely(!array))
685 splice_from_pipe_begin(&sd);
686 while (sd.total_len) {
688 struct iov_iter from;
689 unsigned int head, tail;
693 ret = splice_from_pipe_next(pipe, &sd);
697 if (unlikely(nbufs < pipe->max_usage)) {
699 nbufs = pipe->max_usage;
700 array = kcalloc(nbufs, sizeof(struct bio_vec),
711 /* build the vector */
713 for (n = 0; !pipe_empty(head, tail) && left && n < nbufs; tail++) {
714 struct pipe_buffer *buf = pipe_buf(pipe, tail);
715 size_t this_len = buf->len;
717 /* zero-length bvecs are not supported, skip them */
720 this_len = min(this_len, left);
722 ret = pipe_buf_confirm(pipe, buf);
729 bvec_set_page(&array[n], buf->page, this_len,
735 iov_iter_bvec(&from, ITER_SOURCE, array, n, sd.total_len - left);
736 init_sync_kiocb(&kiocb, out);
737 kiocb.ki_pos = sd.pos;
738 ret = out->f_op->write_iter(&kiocb, &from);
739 sd.pos = kiocb.ki_pos;
743 sd.num_spliced += ret;
747 /* dismiss the fully eaten buffers, adjust the partial one */
750 struct pipe_buffer *buf = pipe_buf(pipe, tail);
751 if (ret >= buf->len) {
754 pipe_buf_release(pipe, buf);
758 sd.need_wakeup = true;
768 splice_from_pipe_end(pipe, &sd);
773 ret = sd.num_spliced;
778 EXPORT_SYMBOL(iter_file_splice_write);
782 * splice_to_socket - splice data from a pipe to a socket
783 * @pipe: pipe to splice from
784 * @out: socket to write to
785 * @ppos: position in @out
786 * @len: number of bytes to splice
787 * @flags: splice modifier flags
790 * Will send @len bytes from the pipe to a network socket. No data copying
794 ssize_t splice_to_socket(struct pipe_inode_info *pipe, struct file *out,
795 loff_t *ppos, size_t len, unsigned int flags)
797 struct socket *sock = sock_from_file(out);
798 struct bio_vec bvec[16];
799 struct msghdr msg = {};
802 bool need_wakeup = false;
807 unsigned int head, tail, bc = 0;
811 * Check for signal early to make process killable when there
812 * are always buffers available
815 if (signal_pending(current))
818 while (pipe_is_empty(pipe)) {
827 if (flags & SPLICE_F_NONBLOCK)
831 if (signal_pending(current))
835 wakeup_pipe_writers(pipe);
839 pipe_wait_readable(pipe);
845 while (!pipe_empty(head, tail)) {
846 struct pipe_buffer *buf = pipe_buf(pipe, tail);
854 seg = min_t(size_t, remain, buf->len);
856 ret = pipe_buf_confirm(pipe, buf);
863 bvec_set_page(&bvec[bc++], buf->page, seg, buf->offset);
865 if (remain == 0 || bc >= ARRAY_SIZE(bvec))
873 msg.msg_flags = MSG_SPLICE_PAGES;
874 if (flags & SPLICE_F_MORE)
875 msg.msg_flags |= MSG_MORE;
876 if (remain && pipe_occupancy(pipe->head, tail) > 0)
877 msg.msg_flags |= MSG_MORE;
878 if (out->f_flags & O_NONBLOCK)
879 msg.msg_flags |= MSG_DONTWAIT;
881 iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, bvec, bc,
883 ret = sock_sendmsg(sock, &msg);
891 struct pipe_buffer *buf = pipe_buf(pipe, tail);
892 size_t seg = min_t(size_t, ret, buf->len);
899 pipe_buf_release(pipe, buf);
904 if (tail != pipe->tail) {
914 wakeup_pipe_writers(pipe);
915 return spliced ?: ret;
919 static int warn_unsupported(struct file *file, const char *op)
921 pr_debug_ratelimited(
922 "splice %s not supported for file %pD4 (pid: %d comm: %.20s)\n",
923 op, file, current->pid, current->comm);
928 * Attempt to initiate a splice from pipe to file.
930 static ssize_t do_splice_from(struct pipe_inode_info *pipe, struct file *out,
931 loff_t *ppos, size_t len, unsigned int flags)
933 if (unlikely(!out->f_op->splice_write))
934 return warn_unsupported(out, "write");
935 return out->f_op->splice_write(pipe, out, ppos, len, flags);
939 * Indicate to the caller that there was a premature EOF when reading from the
940 * source and the caller didn't indicate they would be sending more data after
943 static void do_splice_eof(struct splice_desc *sd)
950 * Callers already called rw_verify_area() on the entire range.
951 * No need to call it for sub ranges.
953 static ssize_t do_splice_read(struct file *in, loff_t *ppos,
954 struct pipe_inode_info *pipe, size_t len,
957 unsigned int p_space;
959 if (unlikely(!(in->f_mode & FMODE_READ)))
964 /* Don't try to read more the pipe has space for. */
965 p_space = pipe->max_usage - pipe_buf_usage(pipe);
966 len = min_t(size_t, len, p_space << PAGE_SHIFT);
968 if (unlikely(len > MAX_RW_COUNT))
971 if (unlikely(!in->f_op->splice_read))
972 return warn_unsupported(in, "read");
974 * O_DIRECT and DAX don't deal with the pagecache, so we allocate a
975 * buffer, copy into it and splice that into the pipe.
977 if ((in->f_flags & O_DIRECT) || IS_DAX(in->f_mapping->host))
978 return copy_splice_read(in, ppos, pipe, len, flags);
979 return in->f_op->splice_read(in, ppos, pipe, len, flags);
983 * vfs_splice_read - Read data from a file and splice it into a pipe
984 * @in: File to splice from
985 * @ppos: Input file offset
986 * @pipe: Pipe to splice to
987 * @len: Number of bytes to splice
988 * @flags: Splice modifier flags (SPLICE_F_*)
990 * Splice the requested amount of data from the input file to the pipe. This
991 * is synchronous as the caller must hold the pipe lock across the entire
994 * If successful, it returns the amount of data spliced, 0 if it hit the EOF or
995 * a hole and a negative error code otherwise.
997 ssize_t vfs_splice_read(struct file *in, loff_t *ppos,
998 struct pipe_inode_info *pipe, size_t len,
1003 ret = rw_verify_area(READ, in, ppos, len);
1004 if (unlikely(ret < 0))
1007 return do_splice_read(in, ppos, pipe, len, flags);
1009 EXPORT_SYMBOL_GPL(vfs_splice_read);
1012 * splice_direct_to_actor - splices data directly between two non-pipes
1013 * @in: file to splice from
1014 * @sd: actor information on where to splice to
1015 * @actor: handles the data splicing
1018 * This is a special case helper to splice directly between two
1019 * points, without requiring an explicit pipe. Internally an allocated
1020 * pipe is cached in the process, and reused during the lifetime of
1024 ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,
1025 splice_direct_actor *actor)
1027 struct pipe_inode_info *pipe;
1033 * We require the input to be seekable, as we don't want to randomly
1034 * drop data for eg socket -> socket splicing. Use the piped splicing
1037 if (unlikely(!(in->f_mode & FMODE_LSEEK)))
1041 * neither in nor out is a pipe, setup an internal pipe attached to
1042 * 'out' and transfer the wanted data from 'in' to 'out' through that
1044 pipe = current->splice_pipe;
1045 if (unlikely(!pipe)) {
1046 pipe = alloc_pipe_info();
1051 * We don't have an immediate reader, but we'll read the stuff
1052 * out of the pipe right after the splice_to_pipe(). So set
1053 * PIPE_READERS appropriately.
1057 current->splice_pipe = pipe;
1064 len = sd->total_len;
1066 /* Don't block on output, we have to drain the direct pipe. */
1068 sd->flags &= ~SPLICE_F_NONBLOCK;
1071 * We signal MORE until we've read sufficient data to fulfill the
1072 * request and we keep signalling it if the caller set it.
1074 more = sd->flags & SPLICE_F_MORE;
1075 sd->flags |= SPLICE_F_MORE;
1077 WARN_ON_ONCE(!pipe_is_empty(pipe));
1081 loff_t pos = sd->pos, prev_pos = pos;
1083 ret = do_splice_read(in, &pos, pipe, len, flags);
1084 if (unlikely(ret <= 0))
1088 sd->total_len = read_len;
1091 * If we now have sufficient data to fulfill the request then
1092 * we clear SPLICE_F_MORE if it was not set initially.
1094 if (read_len >= len && !more)
1095 sd->flags &= ~SPLICE_F_MORE;
1098 * NOTE: nonblocking mode only applies to the input. We
1099 * must not do the output in nonblocking mode as then we
1100 * could get stuck data in the internal pipe:
1102 ret = actor(pipe, sd);
1103 if (unlikely(ret <= 0)) {
1112 if (ret < read_len) {
1113 sd->pos = prev_pos + ret;
1119 pipe->tail = pipe->head = 0;
1125 * If the user did *not* set SPLICE_F_MORE *and* we didn't hit that
1126 * "use all of len" case that cleared SPLICE_F_MORE, *and* we did a
1127 * "->splice_in()" that returned EOF (ie zero) *and* we have sent at
1128 * least 1 byte *then* we will also do the ->splice_eof() call.
1130 if (ret == 0 && !more && len > 0 && bytes)
1134 * If we did an incomplete transfer we must release
1135 * the pipe buffers in question:
1137 for (i = 0; i < pipe->ring_size; i++) {
1138 struct pipe_buffer *buf = &pipe->bufs[i];
1141 pipe_buf_release(pipe, buf);
1149 EXPORT_SYMBOL(splice_direct_to_actor);
1151 static int direct_splice_actor(struct pipe_inode_info *pipe,
1152 struct splice_desc *sd)
1154 struct file *file = sd->u.file;
1157 file_start_write(file);
1158 ret = do_splice_from(pipe, file, sd->opos, sd->total_len, sd->flags);
1159 file_end_write(file);
1163 static int splice_file_range_actor(struct pipe_inode_info *pipe,
1164 struct splice_desc *sd)
1166 struct file *file = sd->u.file;
1168 return do_splice_from(pipe, file, sd->opos, sd->total_len, sd->flags);
1171 static void direct_file_splice_eof(struct splice_desc *sd)
1173 struct file *file = sd->u.file;
1175 if (file->f_op->splice_eof)
1176 file->f_op->splice_eof(file);
1179 static ssize_t do_splice_direct_actor(struct file *in, loff_t *ppos,
1180 struct file *out, loff_t *opos,
1181 size_t len, unsigned int flags,
1182 splice_direct_actor *actor)
1184 struct splice_desc sd = {
1190 .splice_eof = direct_file_splice_eof,
1195 if (unlikely(!(out->f_mode & FMODE_WRITE)))
1198 if (unlikely(out->f_flags & O_APPEND))
1201 ret = splice_direct_to_actor(in, &sd, actor);
1208 * do_splice_direct - splices data directly between two files
1209 * @in: file to splice from
1210 * @ppos: input file offset
1211 * @out: file to splice to
1212 * @opos: output file offset
1213 * @len: number of bytes to splice
1214 * @flags: splice modifier flags
1217 * For use by do_sendfile(). splice can easily emulate sendfile, but
1218 * doing it in the application would incur an extra system call
1219 * (splice in + splice out, as compared to just sendfile()). So this helper
1220 * can splice directly through a process-private pipe.
1222 * Callers already called rw_verify_area() on the entire range.
1224 ssize_t do_splice_direct(struct file *in, loff_t *ppos, struct file *out,
1225 loff_t *opos, size_t len, unsigned int flags)
1227 return do_splice_direct_actor(in, ppos, out, opos, len, flags,
1228 direct_splice_actor);
1230 EXPORT_SYMBOL(do_splice_direct);
1233 * splice_file_range - splices data between two files for copy_file_range()
1234 * @in: file to splice from
1235 * @ppos: input file offset
1236 * @out: file to splice to
1237 * @opos: output file offset
1238 * @len: number of bytes to splice
1241 * For use by ->copy_file_range() methods.
1242 * Like do_splice_direct(), but vfs_copy_file_range() already holds
1243 * start_file_write() on @out file.
1245 * Callers already called rw_verify_area() on the entire range.
1247 ssize_t splice_file_range(struct file *in, loff_t *ppos, struct file *out,
1248 loff_t *opos, size_t len)
1250 lockdep_assert(file_write_started(out));
1252 return do_splice_direct_actor(in, ppos, out, opos,
1253 min_t(size_t, len, MAX_RW_COUNT),
1254 0, splice_file_range_actor);
1256 EXPORT_SYMBOL(splice_file_range);
1258 static int wait_for_space(struct pipe_inode_info *pipe, unsigned flags)
1261 if (unlikely(!pipe->readers)) {
1262 send_sig(SIGPIPE, current, 0);
1265 if (!pipe_is_full(pipe))
1267 if (flags & SPLICE_F_NONBLOCK)
1269 if (signal_pending(current))
1270 return -ERESTARTSYS;
1271 pipe_wait_writable(pipe);
1275 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1276 struct pipe_inode_info *opipe,
1277 size_t len, unsigned int flags);
1279 ssize_t splice_file_to_pipe(struct file *in,
1280 struct pipe_inode_info *opipe,
1282 size_t len, unsigned int flags)
1287 ret = wait_for_space(opipe, flags);
1289 ret = do_splice_read(in, offset, opipe, len, flags);
1292 wakeup_pipe_readers(opipe);
1297 * Determine where to splice to/from.
1299 ssize_t do_splice(struct file *in, loff_t *off_in, struct file *out,
1300 loff_t *off_out, size_t len, unsigned int flags)
1302 struct pipe_inode_info *ipipe;
1303 struct pipe_inode_info *opipe;
1307 if (unlikely(!(in->f_mode & FMODE_READ) ||
1308 !(out->f_mode & FMODE_WRITE)))
1311 ipipe = get_pipe_info(in, true);
1312 opipe = get_pipe_info(out, true);
1314 if (ipipe && opipe) {
1315 if (off_in || off_out)
1318 /* Splicing to self would be fun, but... */
1322 if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1323 flags |= SPLICE_F_NONBLOCK;
1325 ret = splice_pipe_to_pipe(ipipe, opipe, len, flags);
1330 if (!(out->f_mode & FMODE_PWRITE))
1334 offset = out->f_pos;
1337 if (unlikely(out->f_flags & O_APPEND))
1340 ret = rw_verify_area(WRITE, out, &offset, len);
1341 if (unlikely(ret < 0))
1344 if (in->f_flags & O_NONBLOCK)
1345 flags |= SPLICE_F_NONBLOCK;
1347 file_start_write(out);
1348 ret = do_splice_from(ipipe, out, &offset, len, flags);
1349 file_end_write(out);
1352 out->f_pos = offset;
1359 if (!(in->f_mode & FMODE_PREAD))
1366 ret = rw_verify_area(READ, in, &offset, len);
1367 if (unlikely(ret < 0))
1370 if (out->f_flags & O_NONBLOCK)
1371 flags |= SPLICE_F_NONBLOCK;
1373 ret = splice_file_to_pipe(in, opipe, &offset, len, flags);
1385 * Generate modify out before access in:
1386 * do_splice_from() may've already sent modify out,
1387 * and this ensures the events get merged.
1389 fsnotify_modify(out);
1390 fsnotify_access(in);
1396 static ssize_t __do_splice(struct file *in, loff_t __user *off_in,
1397 struct file *out, loff_t __user *off_out,
1398 size_t len, unsigned int flags)
1400 struct pipe_inode_info *ipipe;
1401 struct pipe_inode_info *opipe;
1402 loff_t offset, *__off_in = NULL, *__off_out = NULL;
1405 ipipe = get_pipe_info(in, true);
1406 opipe = get_pipe_info(out, true);
1411 pipe_clear_nowait(in);
1416 pipe_clear_nowait(out);
1420 if (copy_from_user(&offset, off_out, sizeof(loff_t)))
1422 __off_out = &offset;
1425 if (copy_from_user(&offset, off_in, sizeof(loff_t)))
1430 ret = do_splice(in, __off_in, out, __off_out, len, flags);
1434 if (__off_out && copy_to_user(off_out, __off_out, sizeof(loff_t)))
1436 if (__off_in && copy_to_user(off_in, __off_in, sizeof(loff_t)))
1442 static ssize_t iter_to_pipe(struct iov_iter *from,
1443 struct pipe_inode_info *pipe,
1446 struct pipe_buffer buf = {
1447 .ops = &user_page_pipe_buf_ops,
1453 while (iov_iter_count(from)) {
1454 struct page *pages[16];
1459 left = iov_iter_get_pages2(from, pages, ~0UL, 16, &start);
1465 n = DIV_ROUND_UP(left + start, PAGE_SIZE);
1466 for (i = 0; i < n; i++) {
1467 int size = min_t(int, left, PAGE_SIZE - start);
1469 buf.page = pages[i];
1472 ret = add_to_pipe(pipe, &buf);
1473 if (unlikely(ret < 0)) {
1474 iov_iter_revert(from, left);
1475 // this one got dropped by add_to_pipe()
1486 return total ? total : ret;
1489 static int pipe_to_user(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1490 struct splice_desc *sd)
1492 int n = copy_page_to_iter(buf->page, buf->offset, sd->len, sd->u.data);
1493 return n == sd->len ? n : -EFAULT;
1497 * For lack of a better implementation, implement vmsplice() to userspace
1498 * as a simple copy of the pipes pages to the user iov.
1500 static ssize_t vmsplice_to_user(struct file *file, struct iov_iter *iter,
1503 struct pipe_inode_info *pipe = get_pipe_info(file, true);
1504 struct splice_desc sd = {
1505 .total_len = iov_iter_count(iter),
1514 pipe_clear_nowait(file);
1518 ret = __splice_from_pipe(pipe, &sd, pipe_to_user);
1523 fsnotify_access(file);
1529 * vmsplice splices a user address range into a pipe. It can be thought of
1530 * as splice-from-memory, where the regular splice is splice-from-file (or
1531 * to file). In both cases the output is a pipe, naturally.
1533 static ssize_t vmsplice_to_pipe(struct file *file, struct iov_iter *iter,
1536 struct pipe_inode_info *pipe;
1538 unsigned buf_flag = 0;
1540 if (flags & SPLICE_F_GIFT)
1541 buf_flag = PIPE_BUF_FLAG_GIFT;
1543 pipe = get_pipe_info(file, true);
1547 pipe_clear_nowait(file);
1550 ret = wait_for_space(pipe, flags);
1552 ret = iter_to_pipe(iter, pipe, buf_flag);
1555 wakeup_pipe_readers(pipe);
1556 fsnotify_modify(file);
1562 * Note that vmsplice only really supports true splicing _from_ user memory
1563 * to a pipe, not the other way around. Splicing from user memory is a simple
1564 * operation that can be supported without any funky alignment restrictions
1565 * or nasty vm tricks. We simply map in the user memory and fill them into
1566 * a pipe. The reverse isn't quite as easy, though. There are two possible
1567 * solutions for that:
1569 * - memcpy() the data internally, at which point we might as well just
1570 * do a regular read() on the buffer anyway.
1571 * - Lots of nasty vm tricks, that are neither fast nor flexible (it
1572 * has restriction limitations on both ends of the pipe).
1574 * Currently we punt and implement it as a normal copy, see pipe_to_user().
1577 SYSCALL_DEFINE4(vmsplice, int, fd, const struct iovec __user *, uiov,
1578 unsigned long, nr_segs, unsigned int, flags)
1580 struct iovec iovstack[UIO_FASTIOV];
1581 struct iovec *iov = iovstack;
1582 struct iov_iter iter;
1586 if (unlikely(flags & ~SPLICE_F_ALL))
1592 if (fd_file(f)->f_mode & FMODE_WRITE)
1594 else if (fd_file(f)->f_mode & FMODE_READ)
1599 error = import_iovec(type, uiov, nr_segs,
1600 ARRAY_SIZE(iovstack), &iov, &iter);
1604 if (!iov_iter_count(&iter))
1606 else if (type == ITER_SOURCE)
1607 error = vmsplice_to_pipe(fd_file(f), &iter, flags);
1609 error = vmsplice_to_user(fd_file(f), &iter, flags);
1615 SYSCALL_DEFINE6(splice, int, fd_in, loff_t __user *, off_in,
1616 int, fd_out, loff_t __user *, off_out,
1617 size_t, len, unsigned int, flags)
1622 if (unlikely(flags & ~SPLICE_F_ALL))
1625 CLASS(fd, in)(fd_in);
1629 CLASS(fd, out)(fd_out);
1633 return __do_splice(fd_file(in), off_in, fd_file(out), off_out,
1638 * Make sure there's data to read. Wait for input if we can, otherwise
1639 * return an appropriate error.
1641 static int ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1646 * Check the pipe occupancy without the inode lock first. This function
1647 * is speculative anyways, so missing one is ok.
1649 if (!pipe_is_empty(pipe))
1655 while (pipe_is_empty(pipe)) {
1656 if (signal_pending(current)) {
1662 if (flags & SPLICE_F_NONBLOCK) {
1666 pipe_wait_readable(pipe);
1674 * Make sure there's writeable room. Wait for room if we can, otherwise
1675 * return an appropriate error.
1677 static int opipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1682 * Check pipe occupancy without the inode lock first. This function
1683 * is speculative anyways, so missing one is ok.
1685 if (!pipe_is_full(pipe))
1691 while (pipe_is_full(pipe)) {
1692 if (!pipe->readers) {
1693 send_sig(SIGPIPE, current, 0);
1697 if (flags & SPLICE_F_NONBLOCK) {
1701 if (signal_pending(current)) {
1705 pipe_wait_writable(pipe);
1713 * Splice contents of ipipe to opipe.
1715 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1716 struct pipe_inode_info *opipe,
1717 size_t len, unsigned int flags)
1719 struct pipe_buffer *ibuf, *obuf;
1720 unsigned int i_head, o_head;
1721 unsigned int i_tail, o_tail;
1723 bool input_wakeup = false;
1727 ret = ipipe_prep(ipipe, flags);
1731 ret = opipe_prep(opipe, flags);
1736 * Potential ABBA deadlock, work around it by ordering lock
1737 * grabbing by pipe info address. Otherwise two different processes
1738 * could deadlock (one doing tee from A -> B, the other from B -> A).
1740 pipe_double_lock(ipipe, opipe);
1742 i_tail = ipipe->tail;
1743 o_head = opipe->head;
1748 if (!opipe->readers) {
1749 send_sig(SIGPIPE, current, 0);
1755 i_head = ipipe->head;
1756 o_tail = opipe->tail;
1758 if (pipe_empty(i_head, i_tail) && !ipipe->writers)
1762 * Cannot make any progress, because either the input
1763 * pipe is empty or the output pipe is full.
1765 if (pipe_empty(i_head, i_tail) ||
1766 pipe_full(o_head, o_tail, opipe->max_usage)) {
1767 /* Already processed some buffers, break */
1771 if (flags & SPLICE_F_NONBLOCK) {
1777 * We raced with another reader/writer and haven't
1778 * managed to process any buffers. A zero return
1779 * value means EOF, so retry instead.
1786 ibuf = pipe_buf(ipipe, i_tail);
1787 obuf = pipe_buf(opipe, o_head);
1789 if (len >= ibuf->len) {
1791 * Simply move the whole buffer from ipipe to opipe
1796 ipipe->tail = i_tail;
1797 input_wakeup = true;
1800 opipe->head = o_head;
1803 * Get a reference to this pipe buffer,
1804 * so we can copy the contents over.
1806 if (!pipe_buf_get(ipipe, ibuf)) {
1814 * Don't inherit the gift and merge flags, we need to
1815 * prevent multiple steals of this page.
1817 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1818 obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1821 ibuf->offset += len;
1825 opipe->head = o_head;
1835 * If we put data in the output pipe, wakeup any potential readers.
1838 wakeup_pipe_readers(opipe);
1841 wakeup_pipe_writers(ipipe);
1847 * Link contents of ipipe to opipe.
1849 static ssize_t link_pipe(struct pipe_inode_info *ipipe,
1850 struct pipe_inode_info *opipe,
1851 size_t len, unsigned int flags)
1853 struct pipe_buffer *ibuf, *obuf;
1854 unsigned int i_head, o_head;
1855 unsigned int i_tail, o_tail;
1859 * Potential ABBA deadlock, work around it by ordering lock
1860 * grabbing by pipe info address. Otherwise two different processes
1861 * could deadlock (one doing tee from A -> B, the other from B -> A).
1863 pipe_double_lock(ipipe, opipe);
1865 i_tail = ipipe->tail;
1866 o_head = opipe->head;
1869 if (!opipe->readers) {
1870 send_sig(SIGPIPE, current, 0);
1876 i_head = ipipe->head;
1877 o_tail = opipe->tail;
1880 * If we have iterated all input buffers or run out of
1881 * output room, break.
1883 if (pipe_empty(i_head, i_tail) ||
1884 pipe_full(o_head, o_tail, opipe->max_usage))
1887 ibuf = pipe_buf(ipipe, i_tail);
1888 obuf = pipe_buf(opipe, o_head);
1891 * Get a reference to this pipe buffer,
1892 * so we can copy the contents over.
1894 if (!pipe_buf_get(ipipe, ibuf)) {
1903 * Don't inherit the gift and merge flag, we need to prevent
1904 * multiple steals of this page.
1906 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1907 obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1909 if (obuf->len > len)
1915 opipe->head = o_head;
1923 * If we put data in the output pipe, wakeup any potential readers.
1926 wakeup_pipe_readers(opipe);
1932 * This is a tee(1) implementation that works on pipes. It doesn't copy
1933 * any data, it simply references the 'in' pages on the 'out' pipe.
1934 * The 'flags' used are the SPLICE_F_* variants, currently the only
1935 * applicable one is SPLICE_F_NONBLOCK.
1937 ssize_t do_tee(struct file *in, struct file *out, size_t len,
1940 struct pipe_inode_info *ipipe = get_pipe_info(in, true);
1941 struct pipe_inode_info *opipe = get_pipe_info(out, true);
1942 ssize_t ret = -EINVAL;
1944 if (unlikely(!(in->f_mode & FMODE_READ) ||
1945 !(out->f_mode & FMODE_WRITE)))
1949 * Duplicate the contents of ipipe to opipe without actually
1952 if (ipipe && opipe && ipipe != opipe) {
1953 if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1954 flags |= SPLICE_F_NONBLOCK;
1957 * Keep going, unless we encounter an error. The ipipe/opipe
1958 * ordering doesn't really matter.
1960 ret = ipipe_prep(ipipe, flags);
1962 ret = opipe_prep(opipe, flags);
1964 ret = link_pipe(ipipe, opipe, len, flags);
1969 fsnotify_access(in);
1970 fsnotify_modify(out);
1976 SYSCALL_DEFINE4(tee, int, fdin, int, fdout, size_t, len, unsigned int, flags)
1978 if (unlikely(flags & ~SPLICE_F_ALL))
1984 CLASS(fd, in)(fdin);
1988 CLASS(fd, out)(fdout);
1992 return do_tee(fd_file(in), fd_file(out), len, flags);