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/security.h>
34 #include <linux/gfp.h>
35 #include <linux/socket.h>
36 #include <linux/sched/signal.h>
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.
46 static bool page_cache_pipe_buf_try_steal(struct pipe_inode_info *pipe,
47 struct pipe_buffer *buf)
49 struct folio *folio = page_folio(buf->page);
50 struct address_space *mapping;
54 mapping = folio_mapping(folio);
56 WARN_ON(!folio_test_uptodate(folio));
59 * At least for ext2 with nobh option, we need to wait on
60 * writeback completing on this folio, since we'll remove it
61 * from the pagecache. Otherwise truncate wont wait on the
62 * folio, allowing the disk blocks to be reused by someone else
63 * before we actually wrote our data to them. fs corruption
66 folio_wait_writeback(folio);
68 if (folio_has_private(folio) &&
69 !filemap_release_folio(folio, GFP_KERNEL))
73 * If we succeeded in removing the mapping, set LRU flag
76 if (remove_mapping(mapping, folio)) {
77 buf->flags |= PIPE_BUF_FLAG_LRU;
83 * Raced with truncate or failed to remove folio from current
84 * address space, unlock and return failure.
91 static void page_cache_pipe_buf_release(struct pipe_inode_info *pipe,
92 struct pipe_buffer *buf)
95 buf->flags &= ~PIPE_BUF_FLAG_LRU;
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.
102 static int page_cache_pipe_buf_confirm(struct pipe_inode_info *pipe,
103 struct pipe_buffer *buf)
105 struct page *page = buf->page;
108 if (!PageUptodate(page)) {
112 * Page got truncated/unhashed. This will cause a 0-byte
113 * splice, if this is the first page.
115 if (!page->mapping) {
121 * Uh oh, read-error from disk.
123 if (!PageUptodate(page)) {
129 * Page is ok afterall, we are done.
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,
147 static bool user_page_pipe_buf_try_steal(struct pipe_inode_info *pipe,
148 struct pipe_buffer *buf)
150 if (!(buf->flags & PIPE_BUF_FLAG_GIFT))
153 buf->flags |= PIPE_BUF_FLAG_LRU;
154 return generic_pipe_buf_try_steal(pipe, buf);
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,
163 static void wakeup_pipe_readers(struct pipe_inode_info *pipe)
166 if (waitqueue_active(&pipe->rd_wait))
167 wake_up_interruptible(&pipe->rd_wait);
168 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
172 * splice_to_pipe - fill passed data into a pipe
173 * @pipe: pipe to fill
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.
182 ssize_t splice_to_pipe(struct pipe_inode_info *pipe,
183 struct splice_pipe_desc *spd)
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;
194 if (unlikely(!pipe->readers)) {
195 send_sig(SIGPIPE, current, 0);
200 while (!pipe_full(head, tail, pipe->max_usage)) {
201 struct pipe_buffer *buf = &pipe->bufs[head & mask];
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;
215 if (!--spd->nr_pages)
223 while (page_nr < spd_pages)
224 spd->spd_release(spd, page_nr++);
228 EXPORT_SYMBOL_GPL(splice_to_pipe);
230 ssize_t add_to_pipe(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
232 unsigned int head = pipe->head;
233 unsigned int tail = pipe->tail;
234 unsigned int mask = pipe->ring_size - 1;
237 if (unlikely(!pipe->readers)) {
238 send_sig(SIGPIPE, current, 0);
240 } else if (pipe_full(head, tail, pipe->max_usage)) {
243 pipe->bufs[head & mask] = *buf;
244 pipe->head = head + 1;
247 pipe_buf_release(pipe, buf);
250 EXPORT_SYMBOL(add_to_pipe);
253 * Check if we need to grow the arrays holding pages and partial page
256 int splice_grow_spd(const struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
258 unsigned int max_usage = READ_ONCE(pipe->max_usage);
260 spd->nr_pages_max = max_usage;
261 if (max_usage <= PIPE_DEF_BUFFERS)
264 spd->pages = kmalloc_array(max_usage, sizeof(struct page *), GFP_KERNEL);
265 spd->partial = kmalloc_array(max_usage, sizeof(struct partial_page),
268 if (spd->pages && spd->partial)
276 void splice_shrink_spd(struct splice_pipe_desc *spd)
278 if (spd->nr_pages_max <= PIPE_DEF_BUFFERS)
286 * Splice data from an O_DIRECT file into pages and then add them to the output
289 ssize_t direct_splice_read(struct file *in, loff_t *ppos,
290 struct pipe_inode_info *pipe,
291 size_t len, unsigned int flags)
298 size_t used, npages, chunk, remain, reclaim;
301 /* Work out how much data we can actually add into the pipe */
302 used = pipe_occupancy(pipe->head, pipe->tail);
303 npages = max_t(ssize_t, pipe->max_usage - used, 0);
304 len = min_t(size_t, len, npages * PAGE_SIZE);
305 npages = DIV_ROUND_UP(len, PAGE_SIZE);
307 bv = kzalloc(array_size(npages, sizeof(bv[0])) +
308 array_size(npages, sizeof(struct page *)), GFP_KERNEL);
312 pages = (void *)(bv + npages);
313 npages = alloc_pages_bulk_array(GFP_USER, npages, pages);
319 remain = len = min_t(size_t, len, npages * PAGE_SIZE);
321 for (i = 0; i < npages; i++) {
322 chunk = min_t(size_t, PAGE_SIZE, remain);
323 bv[i].bv_page = pages[i];
325 bv[i].bv_len = chunk;
330 iov_iter_bvec(&to, ITER_DEST, bv, npages, len);
331 init_sync_kiocb(&kiocb, in);
332 kiocb.ki_pos = *ppos;
333 ret = call_read_iter(in, &kiocb, &to);
335 reclaim = npages * PAGE_SIZE;
340 *ppos = kiocb.ki_pos;
342 } else if (ret < 0) {
344 * callers of ->splice_read() expect -EAGAIN on
345 * "can't put anything in there", rather than -EFAULT.
351 /* Free any pages that didn't get touched at all. */
352 reclaim /= PAGE_SIZE;
355 release_pages(pages + npages, reclaim);
358 /* Push the remaining pages into the pipe. */
359 for (i = 0; i < npages; i++) {
360 struct pipe_buffer *buf = pipe_head_buf(pipe);
362 chunk = min_t(size_t, remain, PAGE_SIZE);
363 *buf = (struct pipe_buffer) {
364 .ops = &default_pipe_buf_ops,
365 .page = bv[i].bv_page,
376 EXPORT_SYMBOL(direct_splice_read);
379 * generic_file_splice_read - splice data from file to a pipe
380 * @in: file to splice from
381 * @ppos: position in @in
382 * @pipe: pipe to splice to
383 * @len: number of bytes to splice
384 * @flags: splice modifier flags
387 * Will read pages from given file and fill them into a pipe. Can be
388 * used as long as it has more or less sane ->read_iter().
391 ssize_t generic_file_splice_read(struct file *in, loff_t *ppos,
392 struct pipe_inode_info *pipe, size_t len,
399 iov_iter_pipe(&to, ITER_DEST, pipe, len);
400 init_sync_kiocb(&kiocb, in);
401 kiocb.ki_pos = *ppos;
402 ret = call_read_iter(in, &kiocb, &to);
404 *ppos = kiocb.ki_pos;
406 } else if (ret < 0) {
407 /* free what was emitted */
408 pipe_discard_from(pipe, to.start_head);
410 * callers of ->splice_read() expect -EAGAIN on
411 * "can't put anything in there", rather than -EFAULT.
419 EXPORT_SYMBOL(generic_file_splice_read);
421 const struct pipe_buf_operations default_pipe_buf_ops = {
422 .release = generic_pipe_buf_release,
423 .try_steal = generic_pipe_buf_try_steal,
424 .get = generic_pipe_buf_get,
427 /* Pipe buffer operations for a socket and similar. */
428 const struct pipe_buf_operations nosteal_pipe_buf_ops = {
429 .release = generic_pipe_buf_release,
430 .get = generic_pipe_buf_get,
432 EXPORT_SYMBOL(nosteal_pipe_buf_ops);
435 * Send 'sd->len' bytes to socket from 'sd->file' at position 'sd->pos'
436 * using sendpage(). Return the number of bytes sent.
438 static int pipe_to_sendpage(struct pipe_inode_info *pipe,
439 struct pipe_buffer *buf, struct splice_desc *sd)
441 struct file *file = sd->u.file;
442 loff_t pos = sd->pos;
445 if (!likely(file->f_op->sendpage))
448 more = (sd->flags & SPLICE_F_MORE) ? MSG_MORE : 0;
450 if (sd->len < sd->total_len &&
451 pipe_occupancy(pipe->head, pipe->tail) > 1)
452 more |= MSG_SENDPAGE_NOTLAST;
454 return file->f_op->sendpage(file, buf->page, buf->offset,
455 sd->len, &pos, more);
458 static void wakeup_pipe_writers(struct pipe_inode_info *pipe)
461 if (waitqueue_active(&pipe->wr_wait))
462 wake_up_interruptible(&pipe->wr_wait);
463 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
467 * splice_from_pipe_feed - feed available data from a pipe to a file
468 * @pipe: pipe to splice from
469 * @sd: information to @actor
470 * @actor: handler that splices the data
473 * This function loops over the pipe and calls @actor to do the
474 * actual moving of a single struct pipe_buffer to the desired
475 * destination. It returns when there's no more buffers left in
476 * the pipe or if the requested number of bytes (@sd->total_len)
477 * have been copied. It returns a positive number (one) if the
478 * pipe needs to be filled with more data, zero if the required
479 * number of bytes have been copied and -errno on error.
481 * This, together with splice_from_pipe_{begin,end,next}, may be
482 * used to implement the functionality of __splice_from_pipe() when
483 * locking is required around copying the pipe buffers to the
486 static int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
489 unsigned int head = pipe->head;
490 unsigned int tail = pipe->tail;
491 unsigned int mask = pipe->ring_size - 1;
494 while (!pipe_empty(head, tail)) {
495 struct pipe_buffer *buf = &pipe->bufs[tail & mask];
498 if (sd->len > sd->total_len)
499 sd->len = sd->total_len;
501 ret = pipe_buf_confirm(pipe, buf);
508 ret = actor(pipe, buf, sd);
515 sd->num_spliced += ret;
518 sd->total_len -= ret;
521 pipe_buf_release(pipe, buf);
525 sd->need_wakeup = true;
535 /* We know we have a pipe buffer, but maybe it's empty? */
536 static inline bool eat_empty_buffer(struct pipe_inode_info *pipe)
538 unsigned int tail = pipe->tail;
539 unsigned int mask = pipe->ring_size - 1;
540 struct pipe_buffer *buf = &pipe->bufs[tail & mask];
542 if (unlikely(!buf->len)) {
543 pipe_buf_release(pipe, buf);
552 * splice_from_pipe_next - wait for some data to splice from
553 * @pipe: pipe to splice from
554 * @sd: information about the splice operation
557 * This function will wait for some data and return a positive
558 * value (one) if pipe buffers are available. It will return zero
559 * or -errno if no more data needs to be spliced.
561 static int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
564 * Check for signal early to make process killable when there are
565 * always buffers available
567 if (signal_pending(current))
571 while (pipe_empty(pipe->head, pipe->tail)) {
578 if (sd->flags & SPLICE_F_NONBLOCK)
581 if (signal_pending(current))
584 if (sd->need_wakeup) {
585 wakeup_pipe_writers(pipe);
586 sd->need_wakeup = false;
589 pipe_wait_readable(pipe);
592 if (eat_empty_buffer(pipe))
599 * splice_from_pipe_begin - start splicing from pipe
600 * @sd: information about the splice operation
603 * This function should be called before a loop containing
604 * splice_from_pipe_next() and splice_from_pipe_feed() to
605 * initialize the necessary fields of @sd.
607 static void splice_from_pipe_begin(struct splice_desc *sd)
610 sd->need_wakeup = false;
614 * splice_from_pipe_end - finish splicing from pipe
615 * @pipe: pipe to splice from
616 * @sd: information about the splice operation
619 * This function will wake up pipe writers if necessary. It should
620 * be called after a loop containing splice_from_pipe_next() and
621 * splice_from_pipe_feed().
623 static void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
626 wakeup_pipe_writers(pipe);
630 * __splice_from_pipe - splice data from a pipe to given actor
631 * @pipe: pipe to splice from
632 * @sd: information to @actor
633 * @actor: handler that splices the data
636 * This function does little more than loop over the pipe and call
637 * @actor to do the actual moving of a single struct pipe_buffer to
638 * the desired destination. See pipe_to_file, pipe_to_sendpage, or
642 ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
647 splice_from_pipe_begin(sd);
650 ret = splice_from_pipe_next(pipe, sd);
652 ret = splice_from_pipe_feed(pipe, sd, actor);
654 splice_from_pipe_end(pipe, sd);
656 return sd->num_spliced ? sd->num_spliced : ret;
658 EXPORT_SYMBOL(__splice_from_pipe);
661 * splice_from_pipe - splice data from a pipe to a file
662 * @pipe: pipe to splice from
663 * @out: file to splice to
664 * @ppos: position in @out
665 * @len: how many bytes to splice
666 * @flags: splice modifier flags
667 * @actor: handler that splices the data
670 * See __splice_from_pipe. This function locks the pipe inode,
671 * otherwise it's identical to __splice_from_pipe().
674 ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
675 loff_t *ppos, size_t len, unsigned int flags,
679 struct splice_desc sd = {
687 ret = __splice_from_pipe(pipe, &sd, actor);
694 * iter_file_splice_write - splice data from a pipe to a file
696 * @out: file to write to
697 * @ppos: position in @out
698 * @len: number of bytes to splice
699 * @flags: splice modifier flags
702 * Will either move or copy pages (determined by @flags options) from
703 * the given pipe inode to the given file.
704 * This one is ->write_iter-based.
708 iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
709 loff_t *ppos, size_t len, unsigned int flags)
711 struct splice_desc sd = {
717 int nbufs = pipe->max_usage;
718 struct bio_vec *array = kcalloc(nbufs, sizeof(struct bio_vec),
722 if (unlikely(!array))
727 splice_from_pipe_begin(&sd);
728 while (sd.total_len) {
729 struct iov_iter from;
730 unsigned int head, tail, mask;
734 ret = splice_from_pipe_next(pipe, &sd);
738 if (unlikely(nbufs < pipe->max_usage)) {
740 nbufs = pipe->max_usage;
741 array = kcalloc(nbufs, sizeof(struct bio_vec),
751 mask = pipe->ring_size - 1;
753 /* build the vector */
755 for (n = 0; !pipe_empty(head, tail) && left && n < nbufs; tail++) {
756 struct pipe_buffer *buf = &pipe->bufs[tail & mask];
757 size_t this_len = buf->len;
759 /* zero-length bvecs are not supported, skip them */
762 this_len = min(this_len, left);
764 ret = pipe_buf_confirm(pipe, buf);
771 bvec_set_page(&array[n], buf->page, this_len,
777 iov_iter_bvec(&from, ITER_SOURCE, array, n, sd.total_len - left);
778 ret = vfs_iter_write(out, &from, &sd.pos, 0);
782 sd.num_spliced += ret;
786 /* dismiss the fully eaten buffers, adjust the partial one */
789 struct pipe_buffer *buf = &pipe->bufs[tail & mask];
790 if (ret >= buf->len) {
793 pipe_buf_release(pipe, buf);
797 sd.need_wakeup = true;
807 splice_from_pipe_end(pipe, &sd);
812 ret = sd.num_spliced;
817 EXPORT_SYMBOL(iter_file_splice_write);
820 * generic_splice_sendpage - splice data from a pipe to a socket
821 * @pipe: pipe to splice from
822 * @out: socket to write to
823 * @ppos: position in @out
824 * @len: number of bytes to splice
825 * @flags: splice modifier flags
828 * Will send @len bytes from the pipe to a network socket. No data copying
832 ssize_t generic_splice_sendpage(struct pipe_inode_info *pipe, struct file *out,
833 loff_t *ppos, size_t len, unsigned int flags)
835 return splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_sendpage);
838 EXPORT_SYMBOL(generic_splice_sendpage);
840 static int warn_unsupported(struct file *file, const char *op)
842 pr_debug_ratelimited(
843 "splice %s not supported for file %pD4 (pid: %d comm: %.20s)\n",
844 op, file, current->pid, current->comm);
849 * Attempt to initiate a splice from pipe to file.
851 static long do_splice_from(struct pipe_inode_info *pipe, struct file *out,
852 loff_t *ppos, size_t len, unsigned int flags)
854 if (unlikely(!out->f_op->splice_write))
855 return warn_unsupported(out, "write");
856 return out->f_op->splice_write(pipe, out, ppos, len, flags);
860 * Attempt to initiate a splice from a file to a pipe.
862 static long do_splice_to(struct file *in, loff_t *ppos,
863 struct pipe_inode_info *pipe, size_t len,
866 unsigned int p_space;
869 if (unlikely(!(in->f_mode & FMODE_READ)))
872 /* Don't try to read more the pipe has space for. */
873 p_space = pipe->max_usage - pipe_occupancy(pipe->head, pipe->tail);
874 len = min_t(size_t, len, p_space << PAGE_SHIFT);
876 ret = rw_verify_area(READ, in, ppos, len);
877 if (unlikely(ret < 0))
880 if (unlikely(len > MAX_RW_COUNT))
883 if (unlikely(!in->f_op->splice_read))
884 return warn_unsupported(in, "read");
885 return in->f_op->splice_read(in, ppos, pipe, len, flags);
889 * splice_direct_to_actor - splices data directly between two non-pipes
890 * @in: file to splice from
891 * @sd: actor information on where to splice to
892 * @actor: handles the data splicing
895 * This is a special case helper to splice directly between two
896 * points, without requiring an explicit pipe. Internally an allocated
897 * pipe is cached in the process, and reused during the lifetime of
901 ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,
902 splice_direct_actor *actor)
904 struct pipe_inode_info *pipe;
910 * We require the input to be seekable, as we don't want to randomly
911 * drop data for eg socket -> socket splicing. Use the piped splicing
914 if (unlikely(!(in->f_mode & FMODE_LSEEK)))
918 * neither in nor out is a pipe, setup an internal pipe attached to
919 * 'out' and transfer the wanted data from 'in' to 'out' through that
921 pipe = current->splice_pipe;
922 if (unlikely(!pipe)) {
923 pipe = alloc_pipe_info();
928 * We don't have an immediate reader, but we'll read the stuff
929 * out of the pipe right after the splice_to_pipe(). So set
930 * PIPE_READERS appropriately.
934 current->splice_pipe = pipe;
946 * Don't block on output, we have to drain the direct pipe.
948 sd->flags &= ~SPLICE_F_NONBLOCK;
949 more = sd->flags & SPLICE_F_MORE;
951 WARN_ON_ONCE(!pipe_empty(pipe->head, pipe->tail));
955 loff_t pos = sd->pos, prev_pos = pos;
957 ret = do_splice_to(in, &pos, pipe, len, flags);
958 if (unlikely(ret <= 0))
962 sd->total_len = read_len;
965 * If more data is pending, set SPLICE_F_MORE
966 * If this is the last data and SPLICE_F_MORE was not set
967 * initially, clears it.
970 sd->flags |= SPLICE_F_MORE;
972 sd->flags &= ~SPLICE_F_MORE;
974 * NOTE: nonblocking mode only applies to the input. We
975 * must not do the output in nonblocking mode as then we
976 * could get stuck data in the internal pipe:
978 ret = actor(pipe, sd);
979 if (unlikely(ret <= 0)) {
988 if (ret < read_len) {
989 sd->pos = prev_pos + ret;
995 pipe->tail = pipe->head = 0;
1001 * If we did an incomplete transfer we must release
1002 * the pipe buffers in question:
1004 for (i = 0; i < pipe->ring_size; i++) {
1005 struct pipe_buffer *buf = &pipe->bufs[i];
1008 pipe_buf_release(pipe, buf);
1016 EXPORT_SYMBOL(splice_direct_to_actor);
1018 static int direct_splice_actor(struct pipe_inode_info *pipe,
1019 struct splice_desc *sd)
1021 struct file *file = sd->u.file;
1023 return do_splice_from(pipe, file, sd->opos, sd->total_len,
1028 * do_splice_direct - splices data directly between two files
1029 * @in: file to splice from
1030 * @ppos: input file offset
1031 * @out: file to splice to
1032 * @opos: output file offset
1033 * @len: number of bytes to splice
1034 * @flags: splice modifier flags
1037 * For use by do_sendfile(). splice can easily emulate sendfile, but
1038 * doing it in the application would incur an extra system call
1039 * (splice in + splice out, as compared to just sendfile()). So this helper
1040 * can splice directly through a process-private pipe.
1043 long do_splice_direct(struct file *in, loff_t *ppos, struct file *out,
1044 loff_t *opos, size_t len, unsigned int flags)
1046 struct splice_desc sd = {
1056 if (unlikely(!(out->f_mode & FMODE_WRITE)))
1059 if (unlikely(out->f_flags & O_APPEND))
1062 ret = rw_verify_area(WRITE, out, opos, len);
1063 if (unlikely(ret < 0))
1066 ret = splice_direct_to_actor(in, &sd, direct_splice_actor);
1072 EXPORT_SYMBOL(do_splice_direct);
1074 static int wait_for_space(struct pipe_inode_info *pipe, unsigned flags)
1077 if (unlikely(!pipe->readers)) {
1078 send_sig(SIGPIPE, current, 0);
1081 if (!pipe_full(pipe->head, pipe->tail, pipe->max_usage))
1083 if (flags & SPLICE_F_NONBLOCK)
1085 if (signal_pending(current))
1086 return -ERESTARTSYS;
1087 pipe_wait_writable(pipe);
1091 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1092 struct pipe_inode_info *opipe,
1093 size_t len, unsigned int flags);
1095 long splice_file_to_pipe(struct file *in,
1096 struct pipe_inode_info *opipe,
1098 size_t len, unsigned int flags)
1103 ret = wait_for_space(opipe, flags);
1105 ret = do_splice_to(in, offset, opipe, len, flags);
1108 wakeup_pipe_readers(opipe);
1113 * Determine where to splice to/from.
1115 long do_splice(struct file *in, loff_t *off_in, struct file *out,
1116 loff_t *off_out, size_t len, unsigned int flags)
1118 struct pipe_inode_info *ipipe;
1119 struct pipe_inode_info *opipe;
1123 if (unlikely(!(in->f_mode & FMODE_READ) ||
1124 !(out->f_mode & FMODE_WRITE)))
1127 ipipe = get_pipe_info(in, true);
1128 opipe = get_pipe_info(out, true);
1130 if (ipipe && opipe) {
1131 if (off_in || off_out)
1134 /* Splicing to self would be fun, but... */
1138 if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1139 flags |= SPLICE_F_NONBLOCK;
1141 return splice_pipe_to_pipe(ipipe, opipe, len, flags);
1148 if (!(out->f_mode & FMODE_PWRITE))
1152 offset = out->f_pos;
1155 if (unlikely(out->f_flags & O_APPEND))
1158 ret = rw_verify_area(WRITE, out, &offset, len);
1159 if (unlikely(ret < 0))
1162 if (in->f_flags & O_NONBLOCK)
1163 flags |= SPLICE_F_NONBLOCK;
1165 file_start_write(out);
1166 ret = do_splice_from(ipipe, out, &offset, len, flags);
1167 file_end_write(out);
1170 out->f_pos = offset;
1181 if (!(in->f_mode & FMODE_PREAD))
1188 if (out->f_flags & O_NONBLOCK)
1189 flags |= SPLICE_F_NONBLOCK;
1191 ret = splice_file_to_pipe(in, opipe, &offset, len, flags);
1203 static long __do_splice(struct file *in, loff_t __user *off_in,
1204 struct file *out, loff_t __user *off_out,
1205 size_t len, unsigned int flags)
1207 struct pipe_inode_info *ipipe;
1208 struct pipe_inode_info *opipe;
1209 loff_t offset, *__off_in = NULL, *__off_out = NULL;
1212 ipipe = get_pipe_info(in, true);
1213 opipe = get_pipe_info(out, true);
1215 if (ipipe && off_in)
1217 if (opipe && off_out)
1221 if (copy_from_user(&offset, off_out, sizeof(loff_t)))
1223 __off_out = &offset;
1226 if (copy_from_user(&offset, off_in, sizeof(loff_t)))
1231 ret = do_splice(in, __off_in, out, __off_out, len, flags);
1235 if (__off_out && copy_to_user(off_out, __off_out, sizeof(loff_t)))
1237 if (__off_in && copy_to_user(off_in, __off_in, sizeof(loff_t)))
1243 static int iter_to_pipe(struct iov_iter *from,
1244 struct pipe_inode_info *pipe,
1247 struct pipe_buffer buf = {
1248 .ops = &user_page_pipe_buf_ops,
1254 while (iov_iter_count(from)) {
1255 struct page *pages[16];
1260 left = iov_iter_get_pages2(from, pages, ~0UL, 16, &start);
1266 n = DIV_ROUND_UP(left + start, PAGE_SIZE);
1267 for (i = 0; i < n; i++) {
1268 int size = min_t(int, left, PAGE_SIZE - start);
1270 buf.page = pages[i];
1273 ret = add_to_pipe(pipe, &buf);
1274 if (unlikely(ret < 0)) {
1275 iov_iter_revert(from, left);
1276 // this one got dropped by add_to_pipe()
1287 return total ? total : ret;
1290 static int pipe_to_user(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1291 struct splice_desc *sd)
1293 int n = copy_page_to_iter(buf->page, buf->offset, sd->len, sd->u.data);
1294 return n == sd->len ? n : -EFAULT;
1298 * For lack of a better implementation, implement vmsplice() to userspace
1299 * as a simple copy of the pipes pages to the user iov.
1301 static long vmsplice_to_user(struct file *file, struct iov_iter *iter,
1304 struct pipe_inode_info *pipe = get_pipe_info(file, true);
1305 struct splice_desc sd = {
1306 .total_len = iov_iter_count(iter),
1317 ret = __splice_from_pipe(pipe, &sd, pipe_to_user);
1325 * vmsplice splices a user address range into a pipe. It can be thought of
1326 * as splice-from-memory, where the regular splice is splice-from-file (or
1327 * to file). In both cases the output is a pipe, naturally.
1329 static long vmsplice_to_pipe(struct file *file, struct iov_iter *iter,
1332 struct pipe_inode_info *pipe;
1334 unsigned buf_flag = 0;
1336 if (flags & SPLICE_F_GIFT)
1337 buf_flag = PIPE_BUF_FLAG_GIFT;
1339 pipe = get_pipe_info(file, true);
1344 ret = wait_for_space(pipe, flags);
1346 ret = iter_to_pipe(iter, pipe, buf_flag);
1349 wakeup_pipe_readers(pipe);
1353 static int vmsplice_type(struct fd f, int *type)
1357 if (f.file->f_mode & FMODE_WRITE) {
1358 *type = ITER_SOURCE;
1359 } else if (f.file->f_mode & FMODE_READ) {
1369 * Note that vmsplice only really supports true splicing _from_ user memory
1370 * to a pipe, not the other way around. Splicing from user memory is a simple
1371 * operation that can be supported without any funky alignment restrictions
1372 * or nasty vm tricks. We simply map in the user memory and fill them into
1373 * a pipe. The reverse isn't quite as easy, though. There are two possible
1374 * solutions for that:
1376 * - memcpy() the data internally, at which point we might as well just
1377 * do a regular read() on the buffer anyway.
1378 * - Lots of nasty vm tricks, that are neither fast nor flexible (it
1379 * has restriction limitations on both ends of the pipe).
1381 * Currently we punt and implement it as a normal copy, see pipe_to_user().
1384 SYSCALL_DEFINE4(vmsplice, int, fd, const struct iovec __user *, uiov,
1385 unsigned long, nr_segs, unsigned int, flags)
1387 struct iovec iovstack[UIO_FASTIOV];
1388 struct iovec *iov = iovstack;
1389 struct iov_iter iter;
1394 if (unlikely(flags & ~SPLICE_F_ALL))
1398 error = vmsplice_type(f, &type);
1402 error = import_iovec(type, uiov, nr_segs,
1403 ARRAY_SIZE(iovstack), &iov, &iter);
1407 if (!iov_iter_count(&iter))
1409 else if (type == ITER_SOURCE)
1410 error = vmsplice_to_pipe(f.file, &iter, flags);
1412 error = vmsplice_to_user(f.file, &iter, flags);
1420 SYSCALL_DEFINE6(splice, int, fd_in, loff_t __user *, off_in,
1421 int, fd_out, loff_t __user *, off_out,
1422 size_t, len, unsigned int, flags)
1430 if (unlikely(flags & ~SPLICE_F_ALL))
1436 out = fdget(fd_out);
1438 error = __do_splice(in.file, off_in, out.file, off_out,
1448 * Make sure there's data to read. Wait for input if we can, otherwise
1449 * return an appropriate error.
1451 static int ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1456 * Check the pipe occupancy without the inode lock first. This function
1457 * is speculative anyways, so missing one is ok.
1459 if (!pipe_empty(pipe->head, pipe->tail))
1465 while (pipe_empty(pipe->head, pipe->tail)) {
1466 if (signal_pending(current)) {
1472 if (flags & SPLICE_F_NONBLOCK) {
1476 pipe_wait_readable(pipe);
1484 * Make sure there's writeable room. Wait for room if we can, otherwise
1485 * return an appropriate error.
1487 static int opipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1492 * Check pipe occupancy without the inode lock first. This function
1493 * is speculative anyways, so missing one is ok.
1495 if (!pipe_full(pipe->head, pipe->tail, pipe->max_usage))
1501 while (pipe_full(pipe->head, pipe->tail, pipe->max_usage)) {
1502 if (!pipe->readers) {
1503 send_sig(SIGPIPE, current, 0);
1507 if (flags & SPLICE_F_NONBLOCK) {
1511 if (signal_pending(current)) {
1515 pipe_wait_writable(pipe);
1523 * Splice contents of ipipe to opipe.
1525 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1526 struct pipe_inode_info *opipe,
1527 size_t len, unsigned int flags)
1529 struct pipe_buffer *ibuf, *obuf;
1530 unsigned int i_head, o_head;
1531 unsigned int i_tail, o_tail;
1532 unsigned int i_mask, o_mask;
1534 bool input_wakeup = false;
1538 ret = ipipe_prep(ipipe, flags);
1542 ret = opipe_prep(opipe, flags);
1547 * Potential ABBA deadlock, work around it by ordering lock
1548 * grabbing by pipe info address. Otherwise two different processes
1549 * could deadlock (one doing tee from A -> B, the other from B -> A).
1551 pipe_double_lock(ipipe, opipe);
1553 i_tail = ipipe->tail;
1554 i_mask = ipipe->ring_size - 1;
1555 o_head = opipe->head;
1556 o_mask = opipe->ring_size - 1;
1561 if (!opipe->readers) {
1562 send_sig(SIGPIPE, current, 0);
1568 i_head = ipipe->head;
1569 o_tail = opipe->tail;
1571 if (pipe_empty(i_head, i_tail) && !ipipe->writers)
1575 * Cannot make any progress, because either the input
1576 * pipe is empty or the output pipe is full.
1578 if (pipe_empty(i_head, i_tail) ||
1579 pipe_full(o_head, o_tail, opipe->max_usage)) {
1580 /* Already processed some buffers, break */
1584 if (flags & SPLICE_F_NONBLOCK) {
1590 * We raced with another reader/writer and haven't
1591 * managed to process any buffers. A zero return
1592 * value means EOF, so retry instead.
1599 ibuf = &ipipe->bufs[i_tail & i_mask];
1600 obuf = &opipe->bufs[o_head & o_mask];
1602 if (len >= ibuf->len) {
1604 * Simply move the whole buffer from ipipe to opipe
1609 ipipe->tail = i_tail;
1610 input_wakeup = true;
1613 opipe->head = o_head;
1616 * Get a reference to this pipe buffer,
1617 * so we can copy the contents over.
1619 if (!pipe_buf_get(ipipe, ibuf)) {
1627 * Don't inherit the gift and merge flags, we need to
1628 * prevent multiple steals of this page.
1630 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1631 obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1634 ibuf->offset += len;
1638 opipe->head = o_head;
1648 * If we put data in the output pipe, wakeup any potential readers.
1651 wakeup_pipe_readers(opipe);
1654 wakeup_pipe_writers(ipipe);
1660 * Link contents of ipipe to opipe.
1662 static int link_pipe(struct pipe_inode_info *ipipe,
1663 struct pipe_inode_info *opipe,
1664 size_t len, unsigned int flags)
1666 struct pipe_buffer *ibuf, *obuf;
1667 unsigned int i_head, o_head;
1668 unsigned int i_tail, o_tail;
1669 unsigned int i_mask, o_mask;
1673 * Potential ABBA deadlock, work around it by ordering lock
1674 * grabbing by pipe info address. Otherwise two different processes
1675 * could deadlock (one doing tee from A -> B, the other from B -> A).
1677 pipe_double_lock(ipipe, opipe);
1679 i_tail = ipipe->tail;
1680 i_mask = ipipe->ring_size - 1;
1681 o_head = opipe->head;
1682 o_mask = opipe->ring_size - 1;
1685 if (!opipe->readers) {
1686 send_sig(SIGPIPE, current, 0);
1692 i_head = ipipe->head;
1693 o_tail = opipe->tail;
1696 * If we have iterated all input buffers or run out of
1697 * output room, break.
1699 if (pipe_empty(i_head, i_tail) ||
1700 pipe_full(o_head, o_tail, opipe->max_usage))
1703 ibuf = &ipipe->bufs[i_tail & i_mask];
1704 obuf = &opipe->bufs[o_head & o_mask];
1707 * Get a reference to this pipe buffer,
1708 * so we can copy the contents over.
1710 if (!pipe_buf_get(ipipe, ibuf)) {
1719 * Don't inherit the gift and merge flag, we need to prevent
1720 * multiple steals of this page.
1722 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1723 obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1725 if (obuf->len > len)
1731 opipe->head = o_head;
1739 * If we put data in the output pipe, wakeup any potential readers.
1742 wakeup_pipe_readers(opipe);
1748 * This is a tee(1) implementation that works on pipes. It doesn't copy
1749 * any data, it simply references the 'in' pages on the 'out' pipe.
1750 * The 'flags' used are the SPLICE_F_* variants, currently the only
1751 * applicable one is SPLICE_F_NONBLOCK.
1753 long do_tee(struct file *in, struct file *out, size_t len, unsigned int flags)
1755 struct pipe_inode_info *ipipe = get_pipe_info(in, true);
1756 struct pipe_inode_info *opipe = get_pipe_info(out, true);
1759 if (unlikely(!(in->f_mode & FMODE_READ) ||
1760 !(out->f_mode & FMODE_WRITE)))
1764 * Duplicate the contents of ipipe to opipe without actually
1767 if (ipipe && opipe && ipipe != opipe) {
1768 if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1769 flags |= SPLICE_F_NONBLOCK;
1772 * Keep going, unless we encounter an error. The ipipe/opipe
1773 * ordering doesn't really matter.
1775 ret = ipipe_prep(ipipe, flags);
1777 ret = opipe_prep(opipe, flags);
1779 ret = link_pipe(ipipe, opipe, len, flags);
1786 SYSCALL_DEFINE4(tee, int, fdin, int, fdout, size_t, len, unsigned int, flags)
1791 if (unlikely(flags & ~SPLICE_F_ALL))
1802 error = do_tee(in.file, out.file, len, flags);