xref: /linux/fs/splice.c (revision c924c5e9b8c65b3a479a90e5e37d74cc8cd9fe0a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * "splice": joining two ropes together by interweaving their strands.
4  *
5  * This is the "extended pipe" functionality, where a pipe is used as
6  * an arbitrary in-memory buffer. Think of a pipe as a small kernel
7  * buffer that you can use to transfer data from one end to the other.
8  *
9  * The traditional unix read/write is extended with a "splice()" operation
10  * that transfers data buffers to or from a pipe buffer.
11  *
12  * Named by Larry McVoy, original implementation from Linus, extended by
13  * Jens to support splicing to files, network, direct splicing, etc and
14  * fixing lots of bugs.
15  *
16  * Copyright (C) 2005-2006 Jens Axboe <axboe@kernel.dk>
17  * Copyright (C) 2005-2006 Linus Torvalds <torvalds@osdl.org>
18  * Copyright (C) 2006 Ingo Molnar <mingo@elte.hu>
19  *
20  */
21 #include <linux/bvec.h>
22 #include <linux/fs.h>
23 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/splice.h>
26 #include <linux/memcontrol.h>
27 #include <linux/mm_inline.h>
28 #include <linux/swap.h>
29 #include <linux/writeback.h>
30 #include <linux/export.h>
31 #include <linux/syscalls.h>
32 #include <linux/uio.h>
33 #include <linux/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>
39 
40 #include "internal.h"
41 
42 /*
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
46  * being done on it.
47  */
pipe_clear_nowait(struct file * file)48 static noinline void noinline pipe_clear_nowait(struct file *file)
49 {
50 	fmode_t fmode = READ_ONCE(file->f_mode);
51 
52 	do {
53 		if (!(fmode & FMODE_NOWAIT))
54 			break;
55 	} while (!try_cmpxchg(&file->f_mode, &fmode, fmode & ~FMODE_NOWAIT));
56 }
57 
58 /*
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.
63  */
page_cache_pipe_buf_try_steal(struct pipe_inode_info * pipe,struct pipe_buffer * buf)64 static bool page_cache_pipe_buf_try_steal(struct pipe_inode_info *pipe,
65 		struct pipe_buffer *buf)
66 {
67 	struct folio *folio = page_folio(buf->page);
68 	struct address_space *mapping;
69 
70 	folio_lock(folio);
71 
72 	mapping = folio_mapping(folio);
73 	if (mapping) {
74 		WARN_ON(!folio_test_uptodate(folio));
75 
76 		/*
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
82 		 * ensues.
83 		 */
84 		folio_wait_writeback(folio);
85 
86 		if (!filemap_release_folio(folio, GFP_KERNEL))
87 			goto out_unlock;
88 
89 		/*
90 		 * If we succeeded in removing the mapping, set LRU flag
91 		 * and return good.
92 		 */
93 		if (remove_mapping(mapping, folio)) {
94 			buf->flags |= PIPE_BUF_FLAG_LRU;
95 			return true;
96 		}
97 	}
98 
99 	/*
100 	 * Raced with truncate or failed to remove folio from current
101 	 * address space, unlock and return failure.
102 	 */
103 out_unlock:
104 	folio_unlock(folio);
105 	return false;
106 }
107 
page_cache_pipe_buf_release(struct pipe_inode_info * pipe,struct pipe_buffer * buf)108 static void page_cache_pipe_buf_release(struct pipe_inode_info *pipe,
109 					struct pipe_buffer *buf)
110 {
111 	put_page(buf->page);
112 	buf->flags &= ~PIPE_BUF_FLAG_LRU;
113 }
114 
115 /*
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.
118  */
page_cache_pipe_buf_confirm(struct pipe_inode_info * pipe,struct pipe_buffer * buf)119 static int page_cache_pipe_buf_confirm(struct pipe_inode_info *pipe,
120 				       struct pipe_buffer *buf)
121 {
122 	struct folio *folio = page_folio(buf->page);
123 	int err;
124 
125 	if (!folio_test_uptodate(folio)) {
126 		folio_lock(folio);
127 
128 		/*
129 		 * Folio got truncated/unhashed. This will cause a 0-byte
130 		 * splice, if this is the first page.
131 		 */
132 		if (!folio->mapping) {
133 			err = -ENODATA;
134 			goto error;
135 		}
136 
137 		/*
138 		 * Uh oh, read-error from disk.
139 		 */
140 		if (!folio_test_uptodate(folio)) {
141 			err = -EIO;
142 			goto error;
143 		}
144 
145 		/* Folio is ok after all, we are done */
146 		folio_unlock(folio);
147 	}
148 
149 	return 0;
150 error:
151 	folio_unlock(folio);
152 	return err;
153 }
154 
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,
160 };
161 
user_page_pipe_buf_try_steal(struct pipe_inode_info * pipe,struct pipe_buffer * buf)162 static bool user_page_pipe_buf_try_steal(struct pipe_inode_info *pipe,
163 		struct pipe_buffer *buf)
164 {
165 	if (!(buf->flags & PIPE_BUF_FLAG_GIFT))
166 		return false;
167 
168 	buf->flags |= PIPE_BUF_FLAG_LRU;
169 	return generic_pipe_buf_try_steal(pipe, buf);
170 }
171 
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,
176 };
177 
wakeup_pipe_readers(struct pipe_inode_info * pipe)178 static void wakeup_pipe_readers(struct pipe_inode_info *pipe)
179 {
180 	smp_mb();
181 	if (waitqueue_active(&pipe->rd_wait))
182 		wake_up_interruptible(&pipe->rd_wait);
183 	kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
184 }
185 
186 /**
187  * splice_to_pipe - fill passed data into a pipe
188  * @pipe:	pipe to fill
189  * @spd:	data to fill
190  *
191  * Description:
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.
195  *
196  */
splice_to_pipe(struct pipe_inode_info * pipe,struct splice_pipe_desc * spd)197 ssize_t splice_to_pipe(struct pipe_inode_info *pipe,
198 		       struct splice_pipe_desc *spd)
199 {
200 	unsigned int spd_pages = spd->nr_pages;
201 	unsigned int tail = pipe->tail;
202 	unsigned int head = pipe->head;
203 	ssize_t ret = 0;
204 	int page_nr = 0;
205 
206 	if (!spd_pages)
207 		return 0;
208 
209 	if (unlikely(!pipe->readers)) {
210 		send_sig(SIGPIPE, current, 0);
211 		ret = -EPIPE;
212 		goto out;
213 	}
214 
215 	while (!pipe_full(head, tail, pipe->max_usage)) {
216 		struct pipe_buffer *buf = pipe_buf(pipe, head);
217 
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;
222 		buf->ops = spd->ops;
223 		buf->flags = 0;
224 
225 		head++;
226 		pipe->head = head;
227 		page_nr++;
228 		ret += buf->len;
229 
230 		if (!--spd->nr_pages)
231 			break;
232 	}
233 
234 	if (!ret)
235 		ret = -EAGAIN;
236 
237 out:
238 	while (page_nr < spd_pages)
239 		spd->spd_release(spd, page_nr++);
240 
241 	return ret;
242 }
243 EXPORT_SYMBOL_GPL(splice_to_pipe);
244 
add_to_pipe(struct pipe_inode_info * pipe,struct pipe_buffer * buf)245 ssize_t add_to_pipe(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
246 {
247 	unsigned int head = pipe->head;
248 	unsigned int tail = pipe->tail;
249 	int ret;
250 
251 	if (unlikely(!pipe->readers)) {
252 		send_sig(SIGPIPE, current, 0);
253 		ret = -EPIPE;
254 	} else if (pipe_full(head, tail, pipe->max_usage)) {
255 		ret = -EAGAIN;
256 	} else {
257 		*pipe_buf(pipe, head) = *buf;
258 		pipe->head = head + 1;
259 		return buf->len;
260 	}
261 	pipe_buf_release(pipe, buf);
262 	return ret;
263 }
264 EXPORT_SYMBOL(add_to_pipe);
265 
266 /*
267  * Check if we need to grow the arrays holding pages and partial page
268  * descriptions.
269  */
splice_grow_spd(const struct pipe_inode_info * pipe,struct splice_pipe_desc * spd)270 int splice_grow_spd(const struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
271 {
272 	unsigned int max_usage = READ_ONCE(pipe->max_usage);
273 
274 	spd->nr_pages_max = max_usage;
275 	if (max_usage <= PIPE_DEF_BUFFERS)
276 		return 0;
277 
278 	spd->pages = kmalloc_array(max_usage, sizeof(struct page *), GFP_KERNEL);
279 	spd->partial = kmalloc_array(max_usage, sizeof(struct partial_page),
280 				     GFP_KERNEL);
281 
282 	if (spd->pages && spd->partial)
283 		return 0;
284 
285 	kfree(spd->pages);
286 	kfree(spd->partial);
287 	return -ENOMEM;
288 }
289 
splice_shrink_spd(struct splice_pipe_desc * spd)290 void splice_shrink_spd(struct splice_pipe_desc *spd)
291 {
292 	if (spd->nr_pages_max <= PIPE_DEF_BUFFERS)
293 		return;
294 
295 	kfree(spd->pages);
296 	kfree(spd->partial);
297 }
298 
299 /**
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
306  *
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
310  * the pipe.
311  *
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
317  * hole.
318  */
copy_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)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)
322 {
323 	struct iov_iter to;
324 	struct bio_vec *bv;
325 	struct kiocb kiocb;
326 	struct page **pages;
327 	ssize_t ret;
328 	size_t used, npages, chunk, remain, keep = 0;
329 	int i;
330 
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);
336 
337 	bv = kzalloc(array_size(npages, sizeof(bv[0])) +
338 		     array_size(npages, sizeof(struct page *)), GFP_KERNEL);
339 	if (!bv)
340 		return -ENOMEM;
341 
342 	pages = (struct page **)(bv + npages);
343 	npages = alloc_pages_bulk(GFP_USER, npages, pages);
344 	if (!npages) {
345 		kfree(bv);
346 		return -ENOMEM;
347 	}
348 
349 	remain = len = min_t(size_t, len, npages * PAGE_SIZE);
350 
351 	for (i = 0; i < npages; i++) {
352 		chunk = min_t(size_t, PAGE_SIZE, remain);
353 		bv[i].bv_page = pages[i];
354 		bv[i].bv_offset = 0;
355 		bv[i].bv_len = chunk;
356 		remain -= chunk;
357 	}
358 
359 	/* Do the I/O */
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);
364 
365 	if (ret > 0) {
366 		keep = DIV_ROUND_UP(ret, PAGE_SIZE);
367 		*ppos = kiocb.ki_pos;
368 	}
369 
370 	/*
371 	 * Callers of ->splice_read() expect -EAGAIN on "can't put anything in
372 	 * there", rather than -EFAULT.
373 	 */
374 	if (ret == -EFAULT)
375 		ret = -EAGAIN;
376 
377 	/* Free any pages that didn't get touched at all. */
378 	if (keep < npages)
379 		release_pages(pages + keep, npages - keep);
380 
381 	/* Push the remaining pages into the pipe. */
382 	remain = ret;
383 	for (i = 0; i < keep; i++) {
384 		struct pipe_buffer *buf = pipe_head_buf(pipe);
385 
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,
390 			.offset	= 0,
391 			.len	= chunk,
392 		};
393 		pipe->head++;
394 		remain -= chunk;
395 	}
396 
397 	kfree(bv);
398 	return ret;
399 }
400 EXPORT_SYMBOL(copy_splice_read);
401 
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,
406 };
407 
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,
412 };
413 EXPORT_SYMBOL(nosteal_pipe_buf_ops);
414 
wakeup_pipe_writers(struct pipe_inode_info * pipe)415 static void wakeup_pipe_writers(struct pipe_inode_info *pipe)
416 {
417 	smp_mb();
418 	if (waitqueue_active(&pipe->wr_wait))
419 		wake_up_interruptible(&pipe->wr_wait);
420 	kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
421 }
422 
423 /**
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
428  *
429  * Description:
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.
437  *
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
441  *    destination.
442  */
splice_from_pipe_feed(struct pipe_inode_info * pipe,struct splice_desc * sd,splice_actor * actor)443 static int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
444 			  splice_actor *actor)
445 {
446 	unsigned int head = pipe->head;
447 	unsigned int tail = pipe->tail;
448 	int ret;
449 
450 	while (!pipe_empty(head, tail)) {
451 		struct pipe_buffer *buf = pipe_buf(pipe, tail);
452 
453 		sd->len = buf->len;
454 		if (sd->len > sd->total_len)
455 			sd->len = sd->total_len;
456 
457 		ret = pipe_buf_confirm(pipe, buf);
458 		if (unlikely(ret)) {
459 			if (ret == -ENODATA)
460 				ret = 0;
461 			return ret;
462 		}
463 
464 		ret = actor(pipe, buf, sd);
465 		if (ret <= 0)
466 			return ret;
467 
468 		buf->offset += ret;
469 		buf->len -= ret;
470 
471 		sd->num_spliced += ret;
472 		sd->len -= ret;
473 		sd->pos += ret;
474 		sd->total_len -= ret;
475 
476 		if (!buf->len) {
477 			pipe_buf_release(pipe, buf);
478 			tail++;
479 			pipe->tail = tail;
480 			if (pipe->files)
481 				sd->need_wakeup = true;
482 		}
483 
484 		if (!sd->total_len)
485 			return 0;
486 	}
487 
488 	return 1;
489 }
490 
491 /* We know we have a pipe buffer, but maybe it's empty? */
eat_empty_buffer(struct pipe_inode_info * pipe)492 static inline bool eat_empty_buffer(struct pipe_inode_info *pipe)
493 {
494 	unsigned int tail = pipe->tail;
495 	struct pipe_buffer *buf = pipe_buf(pipe, tail);
496 
497 	if (unlikely(!buf->len)) {
498 		pipe_buf_release(pipe, buf);
499 		pipe->tail = tail+1;
500 		return true;
501 	}
502 
503 	return false;
504 }
505 
506 /**
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
510  *
511  * Description:
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.
515  */
splice_from_pipe_next(struct pipe_inode_info * pipe,struct splice_desc * sd)516 static int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
517 {
518 	/*
519 	 * Check for signal early to make process killable when there are
520 	 * always buffers available
521 	 */
522 	if (signal_pending(current))
523 		return -ERESTARTSYS;
524 
525 repeat:
526 	while (pipe_is_empty(pipe)) {
527 		if (!pipe->writers)
528 			return 0;
529 
530 		if (sd->num_spliced)
531 			return 0;
532 
533 		if (sd->flags & SPLICE_F_NONBLOCK)
534 			return -EAGAIN;
535 
536 		if (signal_pending(current))
537 			return -ERESTARTSYS;
538 
539 		if (sd->need_wakeup) {
540 			wakeup_pipe_writers(pipe);
541 			sd->need_wakeup = false;
542 		}
543 
544 		pipe_wait_readable(pipe);
545 	}
546 
547 	if (eat_empty_buffer(pipe))
548 		goto repeat;
549 
550 	return 1;
551 }
552 
553 /**
554  * splice_from_pipe_begin - start splicing from pipe
555  * @sd:		information about the splice operation
556  *
557  * Description:
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.
561  */
splice_from_pipe_begin(struct splice_desc * sd)562 static void splice_from_pipe_begin(struct splice_desc *sd)
563 {
564 	sd->num_spliced = 0;
565 	sd->need_wakeup = false;
566 }
567 
568 /**
569  * splice_from_pipe_end - finish splicing from pipe
570  * @pipe:	pipe to splice from
571  * @sd:		information about the splice operation
572  *
573  * Description:
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().
577  */
splice_from_pipe_end(struct pipe_inode_info * pipe,struct splice_desc * sd)578 static void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
579 {
580 	if (sd->need_wakeup)
581 		wakeup_pipe_writers(pipe);
582 }
583 
584 /**
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
589  *
590  * Description:
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
594  *    pipe_to_user.
595  *
596  */
__splice_from_pipe(struct pipe_inode_info * pipe,struct splice_desc * sd,splice_actor * actor)597 ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
598 			   splice_actor *actor)
599 {
600 	int ret;
601 
602 	splice_from_pipe_begin(sd);
603 	do {
604 		cond_resched();
605 		ret = splice_from_pipe_next(pipe, sd);
606 		if (ret > 0)
607 			ret = splice_from_pipe_feed(pipe, sd, actor);
608 	} while (ret > 0);
609 	splice_from_pipe_end(pipe, sd);
610 
611 	return sd->num_spliced ? sd->num_spliced : ret;
612 }
613 EXPORT_SYMBOL(__splice_from_pipe);
614 
615 /**
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
623  *
624  * Description:
625  *    See __splice_from_pipe. This function locks the pipe inode,
626  *    otherwise it's identical to __splice_from_pipe().
627  *
628  */
splice_from_pipe(struct pipe_inode_info * pipe,struct file * out,loff_t * ppos,size_t len,unsigned int flags,splice_actor * actor)629 ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
630 			 loff_t *ppos, size_t len, unsigned int flags,
631 			 splice_actor *actor)
632 {
633 	ssize_t ret;
634 	struct splice_desc sd = {
635 		.total_len = len,
636 		.flags = flags,
637 		.pos = *ppos,
638 		.u.file = out,
639 	};
640 
641 	pipe_lock(pipe);
642 	ret = __splice_from_pipe(pipe, &sd, actor);
643 	pipe_unlock(pipe);
644 
645 	return ret;
646 }
647 
648 /**
649  * iter_file_splice_write - splice data from a pipe to a file
650  * @pipe:	pipe info
651  * @out:	file to write to
652  * @ppos:	position in @out
653  * @len:	number of bytes to splice
654  * @flags:	splice modifier flags
655  *
656  * Description:
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.
660  *
661  */
662 ssize_t
iter_file_splice_write(struct pipe_inode_info * pipe,struct file * out,loff_t * ppos,size_t len,unsigned int flags)663 iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
664 			  loff_t *ppos, size_t len, unsigned int flags)
665 {
666 	struct splice_desc sd = {
667 		.total_len = len,
668 		.flags = flags,
669 		.pos = *ppos,
670 		.u.file = out,
671 	};
672 	int nbufs = pipe->max_usage;
673 	struct bio_vec *array;
674 	ssize_t ret;
675 
676 	if (!out->f_op->write_iter)
677 		return -EINVAL;
678 
679 	array = kcalloc(nbufs, sizeof(struct bio_vec), GFP_KERNEL);
680 	if (unlikely(!array))
681 		return -ENOMEM;
682 
683 	pipe_lock(pipe);
684 
685 	splice_from_pipe_begin(&sd);
686 	while (sd.total_len) {
687 		struct kiocb kiocb;
688 		struct iov_iter from;
689 		unsigned int head, tail;
690 		size_t left;
691 		int n;
692 
693 		ret = splice_from_pipe_next(pipe, &sd);
694 		if (ret <= 0)
695 			break;
696 
697 		if (unlikely(nbufs < pipe->max_usage)) {
698 			kfree(array);
699 			nbufs = pipe->max_usage;
700 			array = kcalloc(nbufs, sizeof(struct bio_vec),
701 					GFP_KERNEL);
702 			if (!array) {
703 				ret = -ENOMEM;
704 				break;
705 			}
706 		}
707 
708 		head = pipe->head;
709 		tail = pipe->tail;
710 
711 		/* build the vector */
712 		left = sd.total_len;
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;
716 
717 			/* zero-length bvecs are not supported, skip them */
718 			if (!this_len)
719 				continue;
720 			this_len = min(this_len, left);
721 
722 			ret = pipe_buf_confirm(pipe, buf);
723 			if (unlikely(ret)) {
724 				if (ret == -ENODATA)
725 					ret = 0;
726 				goto done;
727 			}
728 
729 			bvec_set_page(&array[n], buf->page, this_len,
730 				      buf->offset);
731 			left -= this_len;
732 			n++;
733 		}
734 
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;
740 		if (ret <= 0)
741 			break;
742 
743 		sd.num_spliced += ret;
744 		sd.total_len -= ret;
745 		*ppos = sd.pos;
746 
747 		/* dismiss the fully eaten buffers, adjust the partial one */
748 		tail = pipe->tail;
749 		while (ret) {
750 			struct pipe_buffer *buf = pipe_buf(pipe, tail);
751 			if (ret >= buf->len) {
752 				ret -= buf->len;
753 				buf->len = 0;
754 				pipe_buf_release(pipe, buf);
755 				tail++;
756 				pipe->tail = tail;
757 				if (pipe->files)
758 					sd.need_wakeup = true;
759 			} else {
760 				buf->offset += ret;
761 				buf->len -= ret;
762 				ret = 0;
763 			}
764 		}
765 	}
766 done:
767 	kfree(array);
768 	splice_from_pipe_end(pipe, &sd);
769 
770 	pipe_unlock(pipe);
771 
772 	if (sd.num_spliced)
773 		ret = sd.num_spliced;
774 
775 	return ret;
776 }
777 
778 EXPORT_SYMBOL(iter_file_splice_write);
779 
780 #ifdef CONFIG_NET
781 /**
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
788  *
789  * Description:
790  *    Will send @len bytes from the pipe to a network socket. No data copying
791  *    is involved.
792  *
793  */
splice_to_socket(struct pipe_inode_info * pipe,struct file * out,loff_t * ppos,size_t len,unsigned int flags)794 ssize_t splice_to_socket(struct pipe_inode_info *pipe, struct file *out,
795 			 loff_t *ppos, size_t len, unsigned int flags)
796 {
797 	struct socket *sock = sock_from_file(out);
798 	struct bio_vec bvec[16];
799 	struct msghdr msg = {};
800 	ssize_t ret = 0;
801 	size_t spliced = 0;
802 	bool need_wakeup = false;
803 
804 	pipe_lock(pipe);
805 
806 	while (len > 0) {
807 		unsigned int head, tail, bc = 0;
808 		size_t remain = len;
809 
810 		/*
811 		 * Check for signal early to make process killable when there
812 		 * are always buffers available
813 		 */
814 		ret = -ERESTARTSYS;
815 		if (signal_pending(current))
816 			break;
817 
818 		while (pipe_is_empty(pipe)) {
819 			ret = 0;
820 			if (!pipe->writers)
821 				goto out;
822 
823 			if (spliced)
824 				goto out;
825 
826 			ret = -EAGAIN;
827 			if (flags & SPLICE_F_NONBLOCK)
828 				goto out;
829 
830 			ret = -ERESTARTSYS;
831 			if (signal_pending(current))
832 				goto out;
833 
834 			if (need_wakeup) {
835 				wakeup_pipe_writers(pipe);
836 				need_wakeup = false;
837 			}
838 
839 			pipe_wait_readable(pipe);
840 		}
841 
842 		head = pipe->head;
843 		tail = pipe->tail;
844 
845 		while (!pipe_empty(head, tail)) {
846 			struct pipe_buffer *buf = pipe_buf(pipe, tail);
847 			size_t seg;
848 
849 			if (!buf->len) {
850 				tail++;
851 				continue;
852 			}
853 
854 			seg = min_t(size_t, remain, buf->len);
855 
856 			ret = pipe_buf_confirm(pipe, buf);
857 			if (unlikely(ret)) {
858 				if (ret == -ENODATA)
859 					ret = 0;
860 				break;
861 			}
862 
863 			bvec_set_page(&bvec[bc++], buf->page, seg, buf->offset);
864 			remain -= seg;
865 			if (remain == 0 || bc >= ARRAY_SIZE(bvec))
866 				break;
867 			tail++;
868 		}
869 
870 		if (!bc)
871 			break;
872 
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;
880 
881 		iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, bvec, bc,
882 			      len - remain);
883 		ret = sock_sendmsg(sock, &msg);
884 		if (ret <= 0)
885 			break;
886 
887 		spliced += ret;
888 		len -= ret;
889 		tail = pipe->tail;
890 		while (ret > 0) {
891 			struct pipe_buffer *buf = pipe_buf(pipe, tail);
892 			size_t seg = min_t(size_t, ret, buf->len);
893 
894 			buf->offset += seg;
895 			buf->len -= seg;
896 			ret -= seg;
897 
898 			if (!buf->len) {
899 				pipe_buf_release(pipe, buf);
900 				tail++;
901 			}
902 		}
903 
904 		if (tail != pipe->tail) {
905 			pipe->tail = tail;
906 			if (pipe->files)
907 				need_wakeup = true;
908 		}
909 	}
910 
911 out:
912 	pipe_unlock(pipe);
913 	if (need_wakeup)
914 		wakeup_pipe_writers(pipe);
915 	return spliced ?: ret;
916 }
917 #endif
918 
warn_unsupported(struct file * file,const char * op)919 static int warn_unsupported(struct file *file, const char *op)
920 {
921 	pr_debug_ratelimited(
922 		"splice %s not supported for file %pD4 (pid: %d comm: %.20s)\n",
923 		op, file, current->pid, current->comm);
924 	return -EINVAL;
925 }
926 
927 /*
928  * Attempt to initiate a splice from pipe to file.
929  */
do_splice_from(struct pipe_inode_info * pipe,struct file * out,loff_t * ppos,size_t len,unsigned int flags)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)
932 {
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);
936 }
937 
938 /*
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
941  * this.
942  */
do_splice_eof(struct splice_desc * sd)943 static void do_splice_eof(struct splice_desc *sd)
944 {
945 	if (sd->splice_eof)
946 		sd->splice_eof(sd);
947 }
948 
949 /*
950  * Callers already called rw_verify_area() on the entire range.
951  * No need to call it for sub ranges.
952  */
do_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)953 static ssize_t do_splice_read(struct file *in, loff_t *ppos,
954 			      struct pipe_inode_info *pipe, size_t len,
955 			      unsigned int flags)
956 {
957 	unsigned int p_space;
958 
959 	if (unlikely(!(in->f_mode & FMODE_READ)))
960 		return -EBADF;
961 	if (!len)
962 		return 0;
963 
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);
967 
968 	if (unlikely(len > MAX_RW_COUNT))
969 		len = MAX_RW_COUNT;
970 
971 	if (unlikely(!in->f_op->splice_read))
972 		return warn_unsupported(in, "read");
973 	/*
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.
976 	 */
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);
980 }
981 
982 /**
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_*)
989  *
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
992  * operation.
993  *
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.
996  */
vfs_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)997 ssize_t vfs_splice_read(struct file *in, loff_t *ppos,
998 			struct pipe_inode_info *pipe, size_t len,
999 			unsigned int flags)
1000 {
1001 	ssize_t ret;
1002 
1003 	ret = rw_verify_area(READ, in, ppos, len);
1004 	if (unlikely(ret < 0))
1005 		return ret;
1006 
1007 	return do_splice_read(in, ppos, pipe, len, flags);
1008 }
1009 EXPORT_SYMBOL_GPL(vfs_splice_read);
1010 
1011 /**
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
1016  *
1017  * Description:
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
1021  *    that process.
1022  *
1023  */
splice_direct_to_actor(struct file * in,struct splice_desc * sd,splice_direct_actor * actor)1024 ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,
1025 			       splice_direct_actor *actor)
1026 {
1027 	struct pipe_inode_info *pipe;
1028 	ssize_t ret, bytes;
1029 	size_t len;
1030 	int i, flags, more;
1031 
1032 	/*
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
1035 	 * for that!
1036 	 */
1037 	if (unlikely(!(in->f_mode & FMODE_LSEEK)))
1038 		return -EINVAL;
1039 
1040 	/*
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
1043 	 */
1044 	pipe = current->splice_pipe;
1045 	if (unlikely(!pipe)) {
1046 		pipe = alloc_pipe_info();
1047 		if (!pipe)
1048 			return -ENOMEM;
1049 
1050 		/*
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.
1054 		 */
1055 		pipe->readers = 1;
1056 
1057 		current->splice_pipe = pipe;
1058 	}
1059 
1060 	/*
1061 	 * Do the splice.
1062 	 */
1063 	bytes = 0;
1064 	len = sd->total_len;
1065 
1066 	/* Don't block on output, we have to drain the direct pipe. */
1067 	flags = sd->flags;
1068 	sd->flags &= ~SPLICE_F_NONBLOCK;
1069 
1070 	/*
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.
1073 	 */
1074 	more = sd->flags & SPLICE_F_MORE;
1075 	sd->flags |= SPLICE_F_MORE;
1076 
1077 	WARN_ON_ONCE(!pipe_is_empty(pipe));
1078 
1079 	while (len) {
1080 		size_t read_len;
1081 		loff_t pos = sd->pos, prev_pos = pos;
1082 
1083 		ret = do_splice_read(in, &pos, pipe, len, flags);
1084 		if (unlikely(ret <= 0))
1085 			goto read_failure;
1086 
1087 		read_len = ret;
1088 		sd->total_len = read_len;
1089 
1090 		/*
1091 		 * If we now have sufficient data to fulfill the request then
1092 		 * we clear SPLICE_F_MORE if it was not set initially.
1093 		 */
1094 		if (read_len >= len && !more)
1095 			sd->flags &= ~SPLICE_F_MORE;
1096 
1097 		/*
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:
1101 		 */
1102 		ret = actor(pipe, sd);
1103 		if (unlikely(ret <= 0)) {
1104 			sd->pos = prev_pos;
1105 			goto out_release;
1106 		}
1107 
1108 		bytes += ret;
1109 		len -= ret;
1110 		sd->pos = pos;
1111 
1112 		if (ret < read_len) {
1113 			sd->pos = prev_pos + ret;
1114 			goto out_release;
1115 		}
1116 	}
1117 
1118 done:
1119 	pipe->tail = pipe->head = 0;
1120 	file_accessed(in);
1121 	return bytes;
1122 
1123 read_failure:
1124 	/*
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.
1129 	 */
1130 	if (ret == 0 && !more && len > 0 && bytes)
1131 		do_splice_eof(sd);
1132 out_release:
1133 	/*
1134 	 * If we did an incomplete transfer we must release
1135 	 * the pipe buffers in question:
1136 	 */
1137 	for (i = 0; i < pipe->ring_size; i++) {
1138 		struct pipe_buffer *buf = &pipe->bufs[i];
1139 
1140 		if (buf->ops)
1141 			pipe_buf_release(pipe, buf);
1142 	}
1143 
1144 	if (!bytes)
1145 		bytes = ret;
1146 
1147 	goto done;
1148 }
1149 EXPORT_SYMBOL(splice_direct_to_actor);
1150 
direct_splice_actor(struct pipe_inode_info * pipe,struct splice_desc * sd)1151 static int direct_splice_actor(struct pipe_inode_info *pipe,
1152 			       struct splice_desc *sd)
1153 {
1154 	struct file *file = sd->u.file;
1155 	long ret;
1156 
1157 	file_start_write(file);
1158 	ret = do_splice_from(pipe, file, sd->opos, sd->total_len, sd->flags);
1159 	file_end_write(file);
1160 	return ret;
1161 }
1162 
splice_file_range_actor(struct pipe_inode_info * pipe,struct splice_desc * sd)1163 static int splice_file_range_actor(struct pipe_inode_info *pipe,
1164 					struct splice_desc *sd)
1165 {
1166 	struct file *file = sd->u.file;
1167 
1168 	return do_splice_from(pipe, file, sd->opos, sd->total_len, sd->flags);
1169 }
1170 
direct_file_splice_eof(struct splice_desc * sd)1171 static void direct_file_splice_eof(struct splice_desc *sd)
1172 {
1173 	struct file *file = sd->u.file;
1174 
1175 	if (file->f_op->splice_eof)
1176 		file->f_op->splice_eof(file);
1177 }
1178 
do_splice_direct_actor(struct file * in,loff_t * ppos,struct file * out,loff_t * opos,size_t len,unsigned int flags,splice_direct_actor * actor)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)
1183 {
1184 	struct splice_desc sd = {
1185 		.len		= len,
1186 		.total_len	= len,
1187 		.flags		= flags,
1188 		.pos		= *ppos,
1189 		.u.file		= out,
1190 		.splice_eof	= direct_file_splice_eof,
1191 		.opos		= opos,
1192 	};
1193 	ssize_t ret;
1194 
1195 	if (unlikely(!(out->f_mode & FMODE_WRITE)))
1196 		return -EBADF;
1197 
1198 	if (unlikely(out->f_flags & O_APPEND))
1199 		return -EINVAL;
1200 
1201 	ret = splice_direct_to_actor(in, &sd, actor);
1202 	if (ret > 0)
1203 		*ppos = sd.pos;
1204 
1205 	return ret;
1206 }
1207 /**
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
1215  *
1216  * Description:
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.
1221  *
1222  * Callers already called rw_verify_area() on the entire range.
1223  */
do_splice_direct(struct file * in,loff_t * ppos,struct file * out,loff_t * opos,size_t len,unsigned int flags)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)
1226 {
1227 	return do_splice_direct_actor(in, ppos, out, opos, len, flags,
1228 				      direct_splice_actor);
1229 }
1230 EXPORT_SYMBOL(do_splice_direct);
1231 
1232 /**
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
1239  *
1240  * Description:
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.
1244  *
1245  * Callers already called rw_verify_area() on the entire range.
1246  */
splice_file_range(struct file * in,loff_t * ppos,struct file * out,loff_t * opos,size_t len)1247 ssize_t splice_file_range(struct file *in, loff_t *ppos, struct file *out,
1248 			  loff_t *opos, size_t len)
1249 {
1250 	lockdep_assert(file_write_started(out));
1251 
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);
1255 }
1256 EXPORT_SYMBOL(splice_file_range);
1257 
wait_for_space(struct pipe_inode_info * pipe,unsigned flags)1258 static int wait_for_space(struct pipe_inode_info *pipe, unsigned flags)
1259 {
1260 	for (;;) {
1261 		if (unlikely(!pipe->readers)) {
1262 			send_sig(SIGPIPE, current, 0);
1263 			return -EPIPE;
1264 		}
1265 		if (!pipe_is_full(pipe))
1266 			return 0;
1267 		if (flags & SPLICE_F_NONBLOCK)
1268 			return -EAGAIN;
1269 		if (signal_pending(current))
1270 			return -ERESTARTSYS;
1271 		pipe_wait_writable(pipe);
1272 	}
1273 }
1274 
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);
1278 
splice_file_to_pipe(struct file * in,struct pipe_inode_info * opipe,loff_t * offset,size_t len,unsigned int flags)1279 ssize_t splice_file_to_pipe(struct file *in,
1280 			    struct pipe_inode_info *opipe,
1281 			    loff_t *offset,
1282 			    size_t len, unsigned int flags)
1283 {
1284 	ssize_t ret;
1285 
1286 	pipe_lock(opipe);
1287 	ret = wait_for_space(opipe, flags);
1288 	if (!ret)
1289 		ret = do_splice_read(in, offset, opipe, len, flags);
1290 	pipe_unlock(opipe);
1291 	if (ret > 0)
1292 		wakeup_pipe_readers(opipe);
1293 	return ret;
1294 }
1295 
1296 /*
1297  * Determine where to splice to/from.
1298  */
do_splice(struct file * in,loff_t * off_in,struct file * out,loff_t * off_out,size_t len,unsigned int flags)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)
1301 {
1302 	struct pipe_inode_info *ipipe;
1303 	struct pipe_inode_info *opipe;
1304 	loff_t offset;
1305 	ssize_t ret;
1306 
1307 	if (unlikely(!(in->f_mode & FMODE_READ) ||
1308 		     !(out->f_mode & FMODE_WRITE)))
1309 		return -EBADF;
1310 
1311 	ipipe = get_pipe_info(in, true);
1312 	opipe = get_pipe_info(out, true);
1313 
1314 	if (ipipe && opipe) {
1315 		if (off_in || off_out)
1316 			return -ESPIPE;
1317 
1318 		/* Splicing to self would be fun, but... */
1319 		if (ipipe == opipe)
1320 			return -EINVAL;
1321 
1322 		if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1323 			flags |= SPLICE_F_NONBLOCK;
1324 
1325 		ret = splice_pipe_to_pipe(ipipe, opipe, len, flags);
1326 	} else if (ipipe) {
1327 		if (off_in)
1328 			return -ESPIPE;
1329 		if (off_out) {
1330 			if (!(out->f_mode & FMODE_PWRITE))
1331 				return -EINVAL;
1332 			offset = *off_out;
1333 		} else {
1334 			offset = out->f_pos;
1335 		}
1336 
1337 		if (unlikely(out->f_flags & O_APPEND))
1338 			return -EINVAL;
1339 
1340 		ret = rw_verify_area(WRITE, out, &offset, len);
1341 		if (unlikely(ret < 0))
1342 			return ret;
1343 
1344 		if (in->f_flags & O_NONBLOCK)
1345 			flags |= SPLICE_F_NONBLOCK;
1346 
1347 		file_start_write(out);
1348 		ret = do_splice_from(ipipe, out, &offset, len, flags);
1349 		file_end_write(out);
1350 
1351 		if (!off_out)
1352 			out->f_pos = offset;
1353 		else
1354 			*off_out = offset;
1355 	} else if (opipe) {
1356 		if (off_out)
1357 			return -ESPIPE;
1358 		if (off_in) {
1359 			if (!(in->f_mode & FMODE_PREAD))
1360 				return -EINVAL;
1361 			offset = *off_in;
1362 		} else {
1363 			offset = in->f_pos;
1364 		}
1365 
1366 		ret = rw_verify_area(READ, in, &offset, len);
1367 		if (unlikely(ret < 0))
1368 			return ret;
1369 
1370 		if (out->f_flags & O_NONBLOCK)
1371 			flags |= SPLICE_F_NONBLOCK;
1372 
1373 		ret = splice_file_to_pipe(in, opipe, &offset, len, flags);
1374 
1375 		if (!off_in)
1376 			in->f_pos = offset;
1377 		else
1378 			*off_in = offset;
1379 	} else {
1380 		ret = -EINVAL;
1381 	}
1382 
1383 	if (ret > 0) {
1384 		/*
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.
1388 		 */
1389 		fsnotify_modify(out);
1390 		fsnotify_access(in);
1391 	}
1392 
1393 	return ret;
1394 }
1395 
__do_splice(struct file * in,loff_t __user * off_in,struct file * out,loff_t __user * off_out,size_t len,unsigned int flags)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)
1399 {
1400 	struct pipe_inode_info *ipipe;
1401 	struct pipe_inode_info *opipe;
1402 	loff_t offset, *__off_in = NULL, *__off_out = NULL;
1403 	ssize_t ret;
1404 
1405 	ipipe = get_pipe_info(in, true);
1406 	opipe = get_pipe_info(out, true);
1407 
1408 	if (ipipe) {
1409 		if (off_in)
1410 			return -ESPIPE;
1411 		pipe_clear_nowait(in);
1412 	}
1413 	if (opipe) {
1414 		if (off_out)
1415 			return -ESPIPE;
1416 		pipe_clear_nowait(out);
1417 	}
1418 
1419 	if (off_out) {
1420 		if (copy_from_user(&offset, off_out, sizeof(loff_t)))
1421 			return -EFAULT;
1422 		__off_out = &offset;
1423 	}
1424 	if (off_in) {
1425 		if (copy_from_user(&offset, off_in, sizeof(loff_t)))
1426 			return -EFAULT;
1427 		__off_in = &offset;
1428 	}
1429 
1430 	ret = do_splice(in, __off_in, out, __off_out, len, flags);
1431 	if (ret < 0)
1432 		return ret;
1433 
1434 	if (__off_out && copy_to_user(off_out, __off_out, sizeof(loff_t)))
1435 		return -EFAULT;
1436 	if (__off_in && copy_to_user(off_in, __off_in, sizeof(loff_t)))
1437 		return -EFAULT;
1438 
1439 	return ret;
1440 }
1441 
iter_to_pipe(struct iov_iter * from,struct pipe_inode_info * pipe,unsigned int flags)1442 static ssize_t iter_to_pipe(struct iov_iter *from,
1443 			    struct pipe_inode_info *pipe,
1444 			    unsigned int flags)
1445 {
1446 	struct pipe_buffer buf = {
1447 		.ops = &user_page_pipe_buf_ops,
1448 		.flags = flags
1449 	};
1450 	size_t total = 0;
1451 	ssize_t ret = 0;
1452 
1453 	while (iov_iter_count(from)) {
1454 		struct page *pages[16];
1455 		ssize_t left;
1456 		size_t start;
1457 		int i, n;
1458 
1459 		left = iov_iter_get_pages2(from, pages, ~0UL, 16, &start);
1460 		if (left <= 0) {
1461 			ret = left;
1462 			break;
1463 		}
1464 
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);
1468 
1469 			buf.page = pages[i];
1470 			buf.offset = start;
1471 			buf.len = size;
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()
1476 				while (++i < n)
1477 					put_page(pages[i]);
1478 				goto out;
1479 			}
1480 			total += ret;
1481 			left -= size;
1482 			start = 0;
1483 		}
1484 	}
1485 out:
1486 	return total ? total : ret;
1487 }
1488 
pipe_to_user(struct pipe_inode_info * pipe,struct pipe_buffer * buf,struct splice_desc * sd)1489 static int pipe_to_user(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1490 			struct splice_desc *sd)
1491 {
1492 	int n = copy_page_to_iter(buf->page, buf->offset, sd->len, sd->u.data);
1493 	return n == sd->len ? n : -EFAULT;
1494 }
1495 
1496 /*
1497  * For lack of a better implementation, implement vmsplice() to userspace
1498  * as a simple copy of the pipes pages to the user iov.
1499  */
vmsplice_to_user(struct file * file,struct iov_iter * iter,unsigned int flags)1500 static ssize_t vmsplice_to_user(struct file *file, struct iov_iter *iter,
1501 				unsigned int flags)
1502 {
1503 	struct pipe_inode_info *pipe = get_pipe_info(file, true);
1504 	struct splice_desc sd = {
1505 		.total_len = iov_iter_count(iter),
1506 		.flags = flags,
1507 		.u.data = iter
1508 	};
1509 	ssize_t ret = 0;
1510 
1511 	if (!pipe)
1512 		return -EBADF;
1513 
1514 	pipe_clear_nowait(file);
1515 
1516 	if (sd.total_len) {
1517 		pipe_lock(pipe);
1518 		ret = __splice_from_pipe(pipe, &sd, pipe_to_user);
1519 		pipe_unlock(pipe);
1520 	}
1521 
1522 	if (ret > 0)
1523 		fsnotify_access(file);
1524 
1525 	return ret;
1526 }
1527 
1528 /*
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.
1532  */
vmsplice_to_pipe(struct file * file,struct iov_iter * iter,unsigned int flags)1533 static ssize_t vmsplice_to_pipe(struct file *file, struct iov_iter *iter,
1534 				unsigned int flags)
1535 {
1536 	struct pipe_inode_info *pipe;
1537 	ssize_t ret = 0;
1538 	unsigned buf_flag = 0;
1539 
1540 	if (flags & SPLICE_F_GIFT)
1541 		buf_flag = PIPE_BUF_FLAG_GIFT;
1542 
1543 	pipe = get_pipe_info(file, true);
1544 	if (!pipe)
1545 		return -EBADF;
1546 
1547 	pipe_clear_nowait(file);
1548 
1549 	pipe_lock(pipe);
1550 	ret = wait_for_space(pipe, flags);
1551 	if (!ret)
1552 		ret = iter_to_pipe(iter, pipe, buf_flag);
1553 	pipe_unlock(pipe);
1554 	if (ret > 0) {
1555 		wakeup_pipe_readers(pipe);
1556 		fsnotify_modify(file);
1557 	}
1558 	return ret;
1559 }
1560 
1561 /*
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:
1568  *
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).
1573  *
1574  * Currently we punt and implement it as a normal copy, see pipe_to_user().
1575  *
1576  */
SYSCALL_DEFINE4(vmsplice,int,fd,const struct iovec __user *,uiov,unsigned long,nr_segs,unsigned int,flags)1577 SYSCALL_DEFINE4(vmsplice, int, fd, const struct iovec __user *, uiov,
1578 		unsigned long, nr_segs, unsigned int, flags)
1579 {
1580 	struct iovec iovstack[UIO_FASTIOV];
1581 	struct iovec *iov = iovstack;
1582 	struct iov_iter iter;
1583 	ssize_t error;
1584 	int type;
1585 
1586 	if (unlikely(flags & ~SPLICE_F_ALL))
1587 		return -EINVAL;
1588 
1589 	CLASS(fd, f)(fd);
1590 	if (fd_empty(f))
1591 		return -EBADF;
1592 	if (fd_file(f)->f_mode & FMODE_WRITE)
1593 		type = ITER_SOURCE;
1594 	else if (fd_file(f)->f_mode & FMODE_READ)
1595 		type = ITER_DEST;
1596 	else
1597 		return -EBADF;
1598 
1599 	error = import_iovec(type, uiov, nr_segs,
1600 			     ARRAY_SIZE(iovstack), &iov, &iter);
1601 	if (error < 0)
1602 		return error;
1603 
1604 	if (!iov_iter_count(&iter))
1605 		error = 0;
1606 	else if (type == ITER_SOURCE)
1607 		error = vmsplice_to_pipe(fd_file(f), &iter, flags);
1608 	else
1609 		error = vmsplice_to_user(fd_file(f), &iter, flags);
1610 
1611 	kfree(iov);
1612 	return error;
1613 }
1614 
SYSCALL_DEFINE6(splice,int,fd_in,loff_t __user *,off_in,int,fd_out,loff_t __user *,off_out,size_t,len,unsigned int,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)
1618 {
1619 	if (unlikely(!len))
1620 		return 0;
1621 
1622 	if (unlikely(flags & ~SPLICE_F_ALL))
1623 		return -EINVAL;
1624 
1625 	CLASS(fd, in)(fd_in);
1626 	if (fd_empty(in))
1627 		return -EBADF;
1628 
1629 	CLASS(fd, out)(fd_out);
1630 	if (fd_empty(out))
1631 		return -EBADF;
1632 
1633 	return __do_splice(fd_file(in), off_in, fd_file(out), off_out,
1634 					    len, flags);
1635 }
1636 
1637 /*
1638  * Make sure there's data to read. Wait for input if we can, otherwise
1639  * return an appropriate error.
1640  */
ipipe_prep(struct pipe_inode_info * pipe,unsigned int flags)1641 static int ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1642 {
1643 	int ret;
1644 
1645 	/*
1646 	 * Check the pipe occupancy without the inode lock first. This function
1647 	 * is speculative anyways, so missing one is ok.
1648 	 */
1649 	if (!pipe_is_empty(pipe))
1650 		return 0;
1651 
1652 	ret = 0;
1653 	pipe_lock(pipe);
1654 
1655 	while (pipe_is_empty(pipe)) {
1656 		if (signal_pending(current)) {
1657 			ret = -ERESTARTSYS;
1658 			break;
1659 		}
1660 		if (!pipe->writers)
1661 			break;
1662 		if (flags & SPLICE_F_NONBLOCK) {
1663 			ret = -EAGAIN;
1664 			break;
1665 		}
1666 		pipe_wait_readable(pipe);
1667 	}
1668 
1669 	pipe_unlock(pipe);
1670 	return ret;
1671 }
1672 
1673 /*
1674  * Make sure there's writeable room. Wait for room if we can, otherwise
1675  * return an appropriate error.
1676  */
opipe_prep(struct pipe_inode_info * pipe,unsigned int flags)1677 static int opipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1678 {
1679 	int ret;
1680 
1681 	/*
1682 	 * Check pipe occupancy without the inode lock first. This function
1683 	 * is speculative anyways, so missing one is ok.
1684 	 */
1685 	if (!pipe_is_full(pipe))
1686 		return 0;
1687 
1688 	ret = 0;
1689 	pipe_lock(pipe);
1690 
1691 	while (pipe_is_full(pipe)) {
1692 		if (!pipe->readers) {
1693 			send_sig(SIGPIPE, current, 0);
1694 			ret = -EPIPE;
1695 			break;
1696 		}
1697 		if (flags & SPLICE_F_NONBLOCK) {
1698 			ret = -EAGAIN;
1699 			break;
1700 		}
1701 		if (signal_pending(current)) {
1702 			ret = -ERESTARTSYS;
1703 			break;
1704 		}
1705 		pipe_wait_writable(pipe);
1706 	}
1707 
1708 	pipe_unlock(pipe);
1709 	return ret;
1710 }
1711 
1712 /*
1713  * Splice contents of ipipe to opipe.
1714  */
splice_pipe_to_pipe(struct pipe_inode_info * ipipe,struct pipe_inode_info * opipe,size_t len,unsigned int flags)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)
1718 {
1719 	struct pipe_buffer *ibuf, *obuf;
1720 	unsigned int i_head, o_head;
1721 	unsigned int i_tail, o_tail;
1722 	int ret = 0;
1723 	bool input_wakeup = false;
1724 
1725 
1726 retry:
1727 	ret = ipipe_prep(ipipe, flags);
1728 	if (ret)
1729 		return ret;
1730 
1731 	ret = opipe_prep(opipe, flags);
1732 	if (ret)
1733 		return ret;
1734 
1735 	/*
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).
1739 	 */
1740 	pipe_double_lock(ipipe, opipe);
1741 
1742 	i_tail = ipipe->tail;
1743 	o_head = opipe->head;
1744 
1745 	do {
1746 		size_t o_len;
1747 
1748 		if (!opipe->readers) {
1749 			send_sig(SIGPIPE, current, 0);
1750 			if (!ret)
1751 				ret = -EPIPE;
1752 			break;
1753 		}
1754 
1755 		i_head = ipipe->head;
1756 		o_tail = opipe->tail;
1757 
1758 		if (pipe_empty(i_head, i_tail) && !ipipe->writers)
1759 			break;
1760 
1761 		/*
1762 		 * Cannot make any progress, because either the input
1763 		 * pipe is empty or the output pipe is full.
1764 		 */
1765 		if (pipe_empty(i_head, i_tail) ||
1766 		    pipe_full(o_head, o_tail, opipe->max_usage)) {
1767 			/* Already processed some buffers, break */
1768 			if (ret)
1769 				break;
1770 
1771 			if (flags & SPLICE_F_NONBLOCK) {
1772 				ret = -EAGAIN;
1773 				break;
1774 			}
1775 
1776 			/*
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.
1780 			 */
1781 			pipe_unlock(ipipe);
1782 			pipe_unlock(opipe);
1783 			goto retry;
1784 		}
1785 
1786 		ibuf = pipe_buf(ipipe, i_tail);
1787 		obuf = pipe_buf(opipe, o_head);
1788 
1789 		if (len >= ibuf->len) {
1790 			/*
1791 			 * Simply move the whole buffer from ipipe to opipe
1792 			 */
1793 			*obuf = *ibuf;
1794 			ibuf->ops = NULL;
1795 			i_tail++;
1796 			ipipe->tail = i_tail;
1797 			input_wakeup = true;
1798 			o_len = obuf->len;
1799 			o_head++;
1800 			opipe->head = o_head;
1801 		} else {
1802 			/*
1803 			 * Get a reference to this pipe buffer,
1804 			 * so we can copy the contents over.
1805 			 */
1806 			if (!pipe_buf_get(ipipe, ibuf)) {
1807 				if (ret == 0)
1808 					ret = -EFAULT;
1809 				break;
1810 			}
1811 			*obuf = *ibuf;
1812 
1813 			/*
1814 			 * Don't inherit the gift and merge flags, we need to
1815 			 * prevent multiple steals of this page.
1816 			 */
1817 			obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1818 			obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1819 
1820 			obuf->len = len;
1821 			ibuf->offset += len;
1822 			ibuf->len -= len;
1823 			o_len = len;
1824 			o_head++;
1825 			opipe->head = o_head;
1826 		}
1827 		ret += o_len;
1828 		len -= o_len;
1829 	} while (len);
1830 
1831 	pipe_unlock(ipipe);
1832 	pipe_unlock(opipe);
1833 
1834 	/*
1835 	 * If we put data in the output pipe, wakeup any potential readers.
1836 	 */
1837 	if (ret > 0)
1838 		wakeup_pipe_readers(opipe);
1839 
1840 	if (input_wakeup)
1841 		wakeup_pipe_writers(ipipe);
1842 
1843 	return ret;
1844 }
1845 
1846 /*
1847  * Link contents of ipipe to opipe.
1848  */
link_pipe(struct pipe_inode_info * ipipe,struct pipe_inode_info * opipe,size_t len,unsigned int flags)1849 static ssize_t link_pipe(struct pipe_inode_info *ipipe,
1850 			 struct pipe_inode_info *opipe,
1851 			 size_t len, unsigned int flags)
1852 {
1853 	struct pipe_buffer *ibuf, *obuf;
1854 	unsigned int i_head, o_head;
1855 	unsigned int i_tail, o_tail;
1856 	ssize_t ret = 0;
1857 
1858 	/*
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).
1862 	 */
1863 	pipe_double_lock(ipipe, opipe);
1864 
1865 	i_tail = ipipe->tail;
1866 	o_head = opipe->head;
1867 
1868 	do {
1869 		if (!opipe->readers) {
1870 			send_sig(SIGPIPE, current, 0);
1871 			if (!ret)
1872 				ret = -EPIPE;
1873 			break;
1874 		}
1875 
1876 		i_head = ipipe->head;
1877 		o_tail = opipe->tail;
1878 
1879 		/*
1880 		 * If we have iterated all input buffers or run out of
1881 		 * output room, break.
1882 		 */
1883 		if (pipe_empty(i_head, i_tail) ||
1884 		    pipe_full(o_head, o_tail, opipe->max_usage))
1885 			break;
1886 
1887 		ibuf = pipe_buf(ipipe, i_tail);
1888 		obuf = pipe_buf(opipe, o_head);
1889 
1890 		/*
1891 		 * Get a reference to this pipe buffer,
1892 		 * so we can copy the contents over.
1893 		 */
1894 		if (!pipe_buf_get(ipipe, ibuf)) {
1895 			if (ret == 0)
1896 				ret = -EFAULT;
1897 			break;
1898 		}
1899 
1900 		*obuf = *ibuf;
1901 
1902 		/*
1903 		 * Don't inherit the gift and merge flag, we need to prevent
1904 		 * multiple steals of this page.
1905 		 */
1906 		obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1907 		obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1908 
1909 		if (obuf->len > len)
1910 			obuf->len = len;
1911 		ret += obuf->len;
1912 		len -= obuf->len;
1913 
1914 		o_head++;
1915 		opipe->head = o_head;
1916 		i_tail++;
1917 	} while (len);
1918 
1919 	pipe_unlock(ipipe);
1920 	pipe_unlock(opipe);
1921 
1922 	/*
1923 	 * If we put data in the output pipe, wakeup any potential readers.
1924 	 */
1925 	if (ret > 0)
1926 		wakeup_pipe_readers(opipe);
1927 
1928 	return ret;
1929 }
1930 
1931 /*
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.
1936  */
do_tee(struct file * in,struct file * out,size_t len,unsigned int flags)1937 ssize_t do_tee(struct file *in, struct file *out, size_t len,
1938 	       unsigned int flags)
1939 {
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;
1943 
1944 	if (unlikely(!(in->f_mode & FMODE_READ) ||
1945 		     !(out->f_mode & FMODE_WRITE)))
1946 		return -EBADF;
1947 
1948 	/*
1949 	 * Duplicate the contents of ipipe to opipe without actually
1950 	 * copying the data.
1951 	 */
1952 	if (ipipe && opipe && ipipe != opipe) {
1953 		if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1954 			flags |= SPLICE_F_NONBLOCK;
1955 
1956 		/*
1957 		 * Keep going, unless we encounter an error. The ipipe/opipe
1958 		 * ordering doesn't really matter.
1959 		 */
1960 		ret = ipipe_prep(ipipe, flags);
1961 		if (!ret) {
1962 			ret = opipe_prep(opipe, flags);
1963 			if (!ret)
1964 				ret = link_pipe(ipipe, opipe, len, flags);
1965 		}
1966 	}
1967 
1968 	if (ret > 0) {
1969 		fsnotify_access(in);
1970 		fsnotify_modify(out);
1971 	}
1972 
1973 	return ret;
1974 }
1975 
SYSCALL_DEFINE4(tee,int,fdin,int,fdout,size_t,len,unsigned int,flags)1976 SYSCALL_DEFINE4(tee, int, fdin, int, fdout, size_t, len, unsigned int, flags)
1977 {
1978 	if (unlikely(flags & ~SPLICE_F_ALL))
1979 		return -EINVAL;
1980 
1981 	if (unlikely(!len))
1982 		return 0;
1983 
1984 	CLASS(fd, in)(fdin);
1985 	if (fd_empty(in))
1986 		return -EBADF;
1987 
1988 	CLASS(fd, out)(fdout);
1989 	if (fd_empty(out))
1990 		return -EBADF;
1991 
1992 	return do_tee(fd_file(in), fd_file(out), len, flags);
1993 }
1994