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 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 if (wq_has_sleeper(&pipe->rd_wait))
181 wake_up_interruptible_poll(&pipe->rd_wait,
182 EPOLLIN | EPOLLRDNORM);
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_objs(struct page *, max_usage);
279 spd->partial = kmalloc_objs(struct partial_page, max_usage);
280
281 if (spd->pages && spd->partial)
282 return 0;
283
284 kfree(spd->pages);
285 kfree(spd->partial);
286 return -ENOMEM;
287 }
288
splice_shrink_spd(struct splice_pipe_desc * spd)289 void splice_shrink_spd(struct splice_pipe_desc *spd)
290 {
291 if (spd->nr_pages_max <= PIPE_DEF_BUFFERS)
292 return;
293
294 kfree(spd->pages);
295 kfree(spd->partial);
296 }
297
298 /**
299 * copy_splice_read - Copy data from a file and splice the copy into a pipe
300 * @in: The file to read from
301 * @ppos: Pointer to the file position to read from
302 * @pipe: The pipe to splice into
303 * @len: The amount to splice
304 * @flags: The SPLICE_F_* flags
305 *
306 * This function allocates a bunch of pages sufficient to hold the requested
307 * amount of data (but limited by the remaining pipe capacity), passes it to
308 * the file's ->read_iter() to read into and then splices the used pages into
309 * the pipe.
310 *
311 * Return: On success, the number of bytes read will be returned and *@ppos
312 * will be updated if appropriate; 0 will be returned if there is no more data
313 * to be read; -EAGAIN will be returned if the pipe had no space, and some
314 * other negative error code will be returned on error. A short read may occur
315 * if the pipe has insufficient space, we reach the end of the data or we hit a
316 * hole.
317 */
copy_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)318 ssize_t copy_splice_read(struct file *in, loff_t *ppos,
319 struct pipe_inode_info *pipe,
320 size_t len, unsigned int flags)
321 {
322 struct iov_iter to;
323 struct bio_vec *bv;
324 struct kiocb kiocb;
325 struct page **pages;
326 ssize_t ret;
327 size_t used, npages, chunk, remain, keep = 0;
328 int i;
329
330 /* Work out how much data we can actually add into the pipe */
331 used = pipe_buf_usage(pipe);
332 npages = max_t(ssize_t, pipe->max_usage - used, 0);
333 len = min_t(size_t, len, npages * PAGE_SIZE);
334 npages = DIV_ROUND_UP(len, PAGE_SIZE);
335
336 bv = kzalloc(array_size(npages, sizeof(bv[0])) +
337 array_size(npages, sizeof(struct page *)), GFP_KERNEL);
338 if (!bv)
339 return -ENOMEM;
340
341 pages = (struct page **)(bv + npages);
342 npages = alloc_pages_bulk(GFP_USER, npages, pages);
343 if (!npages) {
344 kfree(bv);
345 return -ENOMEM;
346 }
347
348 remain = len = min_t(size_t, len, npages * PAGE_SIZE);
349
350 for (i = 0; i < npages; i++) {
351 chunk = min_t(size_t, PAGE_SIZE, remain);
352 bv[i].bv_page = pages[i];
353 bv[i].bv_offset = 0;
354 bv[i].bv_len = chunk;
355 remain -= chunk;
356 }
357
358 /* Do the I/O */
359 iov_iter_bvec(&to, ITER_DEST, bv, npages, len);
360 init_sync_kiocb(&kiocb, in);
361 kiocb.ki_pos = *ppos;
362 ret = in->f_op->read_iter(&kiocb, &to);
363
364 if (ret > 0) {
365 keep = DIV_ROUND_UP(ret, PAGE_SIZE);
366 *ppos = kiocb.ki_pos;
367 }
368
369 /*
370 * Callers of ->splice_read() expect -EAGAIN on "can't put anything in
371 * there", rather than -EFAULT.
372 */
373 if (ret == -EFAULT)
374 ret = -EAGAIN;
375
376 /* Free any pages that didn't get touched at all. */
377 if (keep < npages)
378 release_pages(pages + keep, npages - keep);
379
380 /* Push the remaining pages into the pipe. */
381 remain = ret;
382 for (i = 0; i < keep; i++) {
383 struct pipe_buffer *buf = pipe_head_buf(pipe);
384
385 chunk = min_t(size_t, remain, PAGE_SIZE);
386 *buf = (struct pipe_buffer) {
387 .ops = &default_pipe_buf_ops,
388 .page = bv[i].bv_page,
389 .offset = 0,
390 .len = chunk,
391 };
392 pipe->head++;
393 remain -= chunk;
394 }
395
396 kfree(bv);
397 return ret;
398 }
399 EXPORT_SYMBOL(copy_splice_read);
400
401 const struct pipe_buf_operations default_pipe_buf_ops = {
402 .release = generic_pipe_buf_release,
403 .try_steal = generic_pipe_buf_try_steal,
404 .get = generic_pipe_buf_get,
405 };
406
407 /* Pipe buffer operations for a socket and similar. */
408 const struct pipe_buf_operations nosteal_pipe_buf_ops = {
409 .release = generic_pipe_buf_release,
410 .get = generic_pipe_buf_get,
411 };
412 EXPORT_SYMBOL(nosteal_pipe_buf_ops);
413
wakeup_pipe_writers(struct pipe_inode_info * pipe)414 static void wakeup_pipe_writers(struct pipe_inode_info *pipe)
415 {
416 if (wq_has_sleeper(&pipe->wr_wait))
417 wake_up_interruptible_poll(&pipe->wr_wait,
418 EPOLLOUT | EPOLLWRNORM);
419 kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
420 }
421
422 /**
423 * splice_from_pipe_feed - feed available data from a pipe to a file
424 * @pipe: pipe to splice from
425 * @sd: information to @actor
426 * @actor: handler that splices the data
427 *
428 * Description:
429 * This function loops over the pipe and calls @actor to do the
430 * actual moving of a single struct pipe_buffer to the desired
431 * destination. It returns when there's no more buffers left in
432 * the pipe or if the requested number of bytes (@sd->total_len)
433 * have been copied. It returns a positive number (one) if the
434 * pipe needs to be filled with more data, zero if the required
435 * number of bytes have been copied and -errno on error.
436 *
437 * This, together with splice_from_pipe_{begin,end,next}, may be
438 * used to implement the functionality of __splice_from_pipe() when
439 * locking is required around copying the pipe buffers to the
440 * destination.
441 */
splice_from_pipe_feed(struct pipe_inode_info * pipe,struct splice_desc * sd,splice_actor * actor)442 static int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
443 splice_actor *actor)
444 {
445 unsigned int head = pipe->head;
446 unsigned int tail = pipe->tail;
447 int ret;
448
449 while (!pipe_empty(head, tail)) {
450 struct pipe_buffer *buf = pipe_buf(pipe, tail);
451
452 sd->len = buf->len;
453 if (sd->len > sd->total_len)
454 sd->len = sd->total_len;
455
456 ret = pipe_buf_confirm(pipe, buf);
457 if (unlikely(ret)) {
458 if (ret == -ENODATA)
459 ret = 0;
460 return ret;
461 }
462
463 ret = actor(pipe, buf, sd);
464 if (ret <= 0)
465 return ret;
466
467 buf->offset += ret;
468 buf->len -= ret;
469
470 sd->num_spliced += ret;
471 sd->len -= ret;
472 sd->pos += ret;
473 sd->total_len -= ret;
474
475 if (!buf->len) {
476 pipe_buf_release(pipe, buf);
477 tail++;
478 pipe->tail = tail;
479 if (pipe->files)
480 sd->need_wakeup = true;
481 }
482
483 if (!sd->total_len)
484 return 0;
485 }
486
487 return 1;
488 }
489
490 /* We know we have a pipe buffer, but maybe it's empty? */
eat_empty_buffer(struct pipe_inode_info * pipe)491 static inline bool eat_empty_buffer(struct pipe_inode_info *pipe)
492 {
493 unsigned int tail = pipe->tail;
494 struct pipe_buffer *buf = pipe_buf(pipe, tail);
495
496 if (unlikely(!buf->len)) {
497 pipe_buf_release(pipe, buf);
498 pipe->tail = tail+1;
499 return true;
500 }
501
502 return false;
503 }
504
505 /**
506 * splice_from_pipe_next - wait for some data to splice from
507 * @pipe: pipe to splice from
508 * @sd: information about the splice operation
509 *
510 * Description:
511 * This function will wait for some data and return a positive
512 * value (one) if pipe buffers are available. It will return zero
513 * or -errno if no more data needs to be spliced.
514 */
splice_from_pipe_next(struct pipe_inode_info * pipe,struct splice_desc * sd)515 static int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
516 {
517 /*
518 * Check for signal early to make process killable when there are
519 * always buffers available
520 */
521 if (signal_pending(current))
522 return -ERESTARTSYS;
523
524 repeat:
525 while (pipe_is_empty(pipe)) {
526 if (!pipe->writers)
527 return 0;
528
529 if (sd->num_spliced)
530 return 0;
531
532 if (sd->flags & SPLICE_F_NONBLOCK)
533 return -EAGAIN;
534
535 if (signal_pending(current))
536 return -ERESTARTSYS;
537
538 if (sd->need_wakeup) {
539 wakeup_pipe_writers(pipe);
540 sd->need_wakeup = false;
541 }
542
543 pipe_wait_readable(pipe);
544 }
545
546 if (eat_empty_buffer(pipe))
547 goto repeat;
548
549 return 1;
550 }
551
552 /**
553 * splice_from_pipe_begin - start splicing from pipe
554 * @sd: information about the splice operation
555 *
556 * Description:
557 * This function should be called before a loop containing
558 * splice_from_pipe_next() and splice_from_pipe_feed() to
559 * initialize the necessary fields of @sd.
560 */
splice_from_pipe_begin(struct splice_desc * sd)561 static void splice_from_pipe_begin(struct splice_desc *sd)
562 {
563 sd->num_spliced = 0;
564 sd->need_wakeup = false;
565 }
566
567 /**
568 * splice_from_pipe_end - finish splicing from pipe
569 * @pipe: pipe to splice from
570 * @sd: information about the splice operation
571 *
572 * Description:
573 * This function will wake up pipe writers if necessary. It should
574 * be called after a loop containing splice_from_pipe_next() and
575 * splice_from_pipe_feed().
576 */
splice_from_pipe_end(struct pipe_inode_info * pipe,struct splice_desc * sd)577 static void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
578 {
579 if (sd->need_wakeup)
580 wakeup_pipe_writers(pipe);
581 }
582
583 /**
584 * __splice_from_pipe - splice data from a pipe to given actor
585 * @pipe: pipe to splice from
586 * @sd: information to @actor
587 * @actor: handler that splices the data
588 *
589 * Description:
590 * This function does little more than loop over the pipe and call
591 * @actor to do the actual moving of a single struct pipe_buffer to
592 * the desired destination. See pipe_to_file, pipe_to_sendmsg, or
593 * pipe_to_user.
594 *
595 */
__splice_from_pipe(struct pipe_inode_info * pipe,struct splice_desc * sd,splice_actor * actor)596 ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
597 splice_actor *actor)
598 {
599 int ret;
600
601 splice_from_pipe_begin(sd);
602 do {
603 cond_resched();
604 ret = splice_from_pipe_next(pipe, sd);
605 if (ret > 0)
606 ret = splice_from_pipe_feed(pipe, sd, actor);
607 } while (ret > 0);
608 splice_from_pipe_end(pipe, sd);
609
610 return sd->num_spliced ? sd->num_spliced : ret;
611 }
612 EXPORT_SYMBOL(__splice_from_pipe);
613
614 /**
615 * splice_from_pipe - splice data from a pipe to a file
616 * @pipe: pipe to splice from
617 * @out: file to splice to
618 * @ppos: position in @out
619 * @len: how many bytes to splice
620 * @flags: splice modifier flags
621 * @actor: handler that splices the data
622 *
623 * Description:
624 * See __splice_from_pipe. This function locks the pipe inode,
625 * otherwise it's identical to __splice_from_pipe().
626 *
627 */
splice_from_pipe(struct pipe_inode_info * pipe,struct file * out,loff_t * ppos,size_t len,unsigned int flags,splice_actor * actor)628 ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
629 loff_t *ppos, size_t len, unsigned int flags,
630 splice_actor *actor)
631 {
632 ssize_t ret;
633 struct splice_desc sd = {
634 .total_len = len,
635 .flags = flags,
636 .pos = *ppos,
637 .u.file = out,
638 };
639
640 pipe_lock(pipe);
641 ret = __splice_from_pipe(pipe, &sd, actor);
642 pipe_unlock(pipe);
643
644 return ret;
645 }
646
647 /**
648 * iter_file_splice_write - splice data from a pipe to a file
649 * @pipe: pipe info
650 * @out: file to write to
651 * @ppos: position in @out
652 * @len: number of bytes to splice
653 * @flags: splice modifier flags
654 *
655 * Description:
656 * Will either move or copy pages (determined by @flags options) from
657 * the given pipe inode to the given file.
658 * This one is ->write_iter-based.
659 *
660 */
661 ssize_t
iter_file_splice_write(struct pipe_inode_info * pipe,struct file * out,loff_t * ppos,size_t len,unsigned int flags)662 iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
663 loff_t *ppos, size_t len, unsigned int flags)
664 {
665 struct splice_desc sd = {
666 .total_len = len,
667 .flags = flags,
668 .pos = *ppos,
669 .u.file = out,
670 };
671 int nbufs = pipe->max_usage;
672 struct bio_vec *array;
673 ssize_t ret;
674
675 if (!out->f_op->write_iter)
676 return -EINVAL;
677
678 array = kzalloc_objs(struct bio_vec, nbufs);
679 if (unlikely(!array))
680 return -ENOMEM;
681
682 pipe_lock(pipe);
683
684 splice_from_pipe_begin(&sd);
685 while (sd.total_len) {
686 struct kiocb kiocb;
687 struct iov_iter from;
688 unsigned int head, tail;
689 size_t left;
690 int n;
691
692 ret = splice_from_pipe_next(pipe, &sd);
693 if (ret <= 0)
694 break;
695
696 if (unlikely(nbufs < pipe->max_usage)) {
697 kfree(array);
698 nbufs = pipe->max_usage;
699 array = kzalloc_objs(struct bio_vec, nbufs);
700 if (!array) {
701 ret = -ENOMEM;
702 break;
703 }
704 }
705
706 head = pipe->head;
707 tail = pipe->tail;
708
709 /* build the vector */
710 left = sd.total_len;
711 for (n = 0; !pipe_empty(head, tail) && left && n < nbufs; tail++) {
712 struct pipe_buffer *buf = pipe_buf(pipe, tail);
713 size_t this_len = buf->len;
714
715 /* zero-length bvecs are not supported, skip them */
716 if (!this_len)
717 continue;
718 this_len = min(this_len, left);
719
720 ret = pipe_buf_confirm(pipe, buf);
721 if (unlikely(ret)) {
722 if (ret == -ENODATA)
723 ret = 0;
724 goto done;
725 }
726
727 bvec_set_page(&array[n], buf->page, this_len,
728 buf->offset);
729 left -= this_len;
730 n++;
731 }
732
733 iov_iter_bvec(&from, ITER_SOURCE, array, n, sd.total_len - left);
734 init_sync_kiocb(&kiocb, out);
735 kiocb.ki_pos = sd.pos;
736 ret = out->f_op->write_iter(&kiocb, &from);
737 sd.pos = kiocb.ki_pos;
738 if (ret <= 0)
739 break;
740 WARN_ONCE(ret > sd.total_len - left,
741 "Splice Exceeded! ret=%zd tot=%zu left=%zu\n",
742 ret, sd.total_len, left);
743
744 sd.num_spliced += ret;
745 sd.total_len -= ret;
746 *ppos = sd.pos;
747
748 /* dismiss the fully eaten buffers, adjust the partial one */
749 tail = pipe->tail;
750 while (ret) {
751 struct pipe_buffer *buf = pipe_buf(pipe, tail);
752 if (ret >= buf->len) {
753 ret -= buf->len;
754 buf->len = 0;
755 pipe_buf_release(pipe, buf);
756 tail++;
757 pipe->tail = tail;
758 if (pipe->files)
759 sd.need_wakeup = true;
760 } else {
761 buf->offset += ret;
762 buf->len -= ret;
763 ret = 0;
764 }
765 }
766 }
767 done:
768 kfree(array);
769 splice_from_pipe_end(pipe, &sd);
770
771 pipe_unlock(pipe);
772
773 if (sd.num_spliced)
774 ret = sd.num_spliced;
775
776 return ret;
777 }
778
779 EXPORT_SYMBOL(iter_file_splice_write);
780
781 #ifdef CONFIG_NET
782 /**
783 * splice_to_socket - splice data from a pipe to a socket
784 * @pipe: pipe to splice from
785 * @out: socket to write to
786 * @ppos: position in @out
787 * @len: number of bytes to splice
788 * @flags: splice modifier flags
789 *
790 * Description:
791 * Will send @len bytes from the pipe to a network socket. No data copying
792 * is involved.
793 *
794 */
splice_to_socket(struct pipe_inode_info * pipe,struct file * out,loff_t * ppos,size_t len,unsigned int flags)795 ssize_t splice_to_socket(struct pipe_inode_info *pipe, struct file *out,
796 loff_t *ppos, size_t len, unsigned int flags)
797 {
798 struct socket *sock = sock_from_file(out);
799 struct bio_vec bvec[16];
800 struct msghdr msg = {};
801 ssize_t ret = 0;
802 size_t spliced = 0;
803 bool need_wakeup = false;
804
805 pipe_lock(pipe);
806
807 while (len > 0) {
808 unsigned int head, tail, bc = 0;
809 size_t remain = len;
810
811 /*
812 * Check for signal early to make process killable when there
813 * are always buffers available
814 */
815 ret = -ERESTARTSYS;
816 if (signal_pending(current))
817 break;
818
819 while (pipe_is_empty(pipe)) {
820 ret = 0;
821 if (!pipe->writers)
822 goto out;
823
824 if (spliced)
825 goto out;
826
827 ret = -EAGAIN;
828 if (flags & SPLICE_F_NONBLOCK)
829 goto out;
830
831 ret = -ERESTARTSYS;
832 if (signal_pending(current))
833 goto out;
834
835 if (need_wakeup) {
836 wakeup_pipe_writers(pipe);
837 need_wakeup = false;
838 }
839
840 pipe_wait_readable(pipe);
841 }
842
843 head = pipe->head;
844 tail = pipe->tail;
845
846 while (!pipe_empty(head, tail)) {
847 struct pipe_buffer *buf = pipe_buf(pipe, tail);
848 size_t seg;
849
850 if (!buf->len) {
851 tail++;
852 continue;
853 }
854
855 seg = min_t(size_t, remain, buf->len);
856
857 ret = pipe_buf_confirm(pipe, buf);
858 if (unlikely(ret)) {
859 if (ret == -ENODATA)
860 ret = 0;
861 break;
862 }
863
864 bvec_set_page(&bvec[bc++], buf->page, seg, buf->offset);
865 remain -= seg;
866 if (remain == 0 || bc >= ARRAY_SIZE(bvec))
867 break;
868 tail++;
869 }
870
871 if (!bc)
872 break;
873
874 msg.msg_flags = MSG_SPLICE_PAGES;
875 if (flags & SPLICE_F_MORE)
876 msg.msg_flags |= MSG_MORE;
877 if (remain && pipe_occupancy(pipe->head, tail) > 0)
878 msg.msg_flags |= MSG_MORE;
879 if (out->f_flags & O_NONBLOCK)
880 msg.msg_flags |= MSG_DONTWAIT;
881
882 iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, bvec, bc,
883 len - remain);
884 ret = sock_sendmsg(sock, &msg);
885 if (ret <= 0)
886 break;
887
888 spliced += ret;
889 len -= ret;
890 tail = pipe->tail;
891 while (ret > 0) {
892 struct pipe_buffer *buf = pipe_buf(pipe, tail);
893 size_t seg = min_t(size_t, ret, buf->len);
894
895 buf->offset += seg;
896 buf->len -= seg;
897 ret -= seg;
898
899 if (!buf->len) {
900 pipe_buf_release(pipe, buf);
901 tail++;
902 }
903 }
904
905 if (tail != pipe->tail) {
906 pipe->tail = tail;
907 if (pipe->files)
908 need_wakeup = true;
909 }
910 }
911
912 out:
913 pipe_unlock(pipe);
914 if (need_wakeup)
915 wakeup_pipe_writers(pipe);
916 return spliced ?: ret;
917 }
918 #endif
919
warn_unsupported(struct file * file,const char * op)920 static int warn_unsupported(struct file *file, const char *op)
921 {
922 pr_debug_ratelimited(
923 "splice %s not supported for file %pD4 (pid: %d comm: %.20s)\n",
924 op, file, current->pid, current->comm);
925 return -EINVAL;
926 }
927
928 /*
929 * Attempt to initiate a splice from pipe to file.
930 */
do_splice_from(struct pipe_inode_info * pipe,struct file * out,loff_t * ppos,size_t len,unsigned int flags)931 static ssize_t do_splice_from(struct pipe_inode_info *pipe, struct file *out,
932 loff_t *ppos, size_t len, unsigned int flags)
933 {
934 if (unlikely(!out->f_op->splice_write))
935 return warn_unsupported(out, "write");
936 return out->f_op->splice_write(pipe, out, ppos, len, flags);
937 }
938
939 /*
940 * Indicate to the caller that there was a premature EOF when reading from the
941 * source and the caller didn't indicate they would be sending more data after
942 * this.
943 */
do_splice_eof(struct splice_desc * sd)944 static void do_splice_eof(struct splice_desc *sd)
945 {
946 if (sd->splice_eof)
947 sd->splice_eof(sd);
948 }
949
950 /*
951 * Callers already called rw_verify_area() on the entire range.
952 * No need to call it for sub ranges.
953 */
do_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)954 static ssize_t do_splice_read(struct file *in, loff_t *ppos,
955 struct pipe_inode_info *pipe, size_t len,
956 unsigned int flags)
957 {
958 unsigned int p_space;
959
960 if (unlikely(!(in->f_mode & FMODE_READ)))
961 return -EBADF;
962 if (!len)
963 return 0;
964
965 /* Don't try to read more the pipe has space for. */
966 p_space = pipe->max_usage - pipe_buf_usage(pipe);
967 len = min_t(size_t, len, p_space << PAGE_SHIFT);
968
969 if (unlikely(len > MAX_RW_COUNT))
970 len = MAX_RW_COUNT;
971
972 if (unlikely(!in->f_op->splice_read))
973 return warn_unsupported(in, "read");
974 /*
975 * O_DIRECT and DAX don't deal with the pagecache, so we allocate a
976 * buffer, copy into it and splice that into the pipe.
977 */
978 if ((in->f_flags & O_DIRECT) || IS_DAX(in->f_mapping->host))
979 return copy_splice_read(in, ppos, pipe, len, flags);
980 return in->f_op->splice_read(in, ppos, pipe, len, flags);
981 }
982
983 /**
984 * vfs_splice_read - Read data from a file and splice it into a pipe
985 * @in: File to splice from
986 * @ppos: Input file offset
987 * @pipe: Pipe to splice to
988 * @len: Number of bytes to splice
989 * @flags: Splice modifier flags (SPLICE_F_*)
990 *
991 * Splice the requested amount of data from the input file to the pipe. This
992 * is synchronous as the caller must hold the pipe lock across the entire
993 * operation.
994 *
995 * If successful, it returns the amount of data spliced, 0 if it hit the EOF or
996 * a hole and a negative error code otherwise.
997 */
vfs_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)998 ssize_t vfs_splice_read(struct file *in, loff_t *ppos,
999 struct pipe_inode_info *pipe, size_t len,
1000 unsigned int flags)
1001 {
1002 ssize_t ret;
1003
1004 ret = rw_verify_area(READ, in, ppos, len);
1005 if (unlikely(ret < 0))
1006 return ret;
1007
1008 return do_splice_read(in, ppos, pipe, len, flags);
1009 }
1010 EXPORT_SYMBOL_GPL(vfs_splice_read);
1011
1012 /*
1013 * This is a special case helper to splice directly between two
1014 * points, without requiring an explicit pipe. Internally an allocated
1015 * pipe is cached in the process, and reused during the lifetime of
1016 * that process.
1017 */
splice_direct_to_actor(struct file * in,struct splice_desc * sd,splice_direct_actor * actor)1018 static ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,
1019 splice_direct_actor *actor)
1020 {
1021 struct pipe_inode_info *pipe;
1022 ssize_t ret, bytes;
1023 size_t len;
1024 int i, flags, more;
1025
1026 /*
1027 * We require the input to be seekable, as we don't want to randomly
1028 * drop data for eg socket -> socket splicing. Use the piped splicing
1029 * for that!
1030 */
1031 if (unlikely(!(in->f_mode & FMODE_LSEEK)))
1032 return -EINVAL;
1033
1034 /*
1035 * neither in nor out is a pipe, setup an internal pipe attached to
1036 * 'out' and transfer the wanted data from 'in' to 'out' through that
1037 */
1038 pipe = current->splice_pipe;
1039 if (unlikely(!pipe)) {
1040 pipe = alloc_pipe_info();
1041 if (!pipe)
1042 return -ENOMEM;
1043
1044 /*
1045 * We don't have an immediate reader, but we'll read the stuff
1046 * out of the pipe right after the splice_to_pipe(). So set
1047 * PIPE_READERS appropriately.
1048 */
1049 pipe->readers = 1;
1050
1051 current->splice_pipe = pipe;
1052 }
1053
1054 /*
1055 * Do the splice.
1056 */
1057 bytes = 0;
1058 len = sd->total_len;
1059
1060 /* Don't block on output, we have to drain the direct pipe. */
1061 flags = sd->flags;
1062 sd->flags &= ~SPLICE_F_NONBLOCK;
1063
1064 /*
1065 * We signal MORE until we've read sufficient data to fulfill the
1066 * request and we keep signalling it if the caller set it.
1067 */
1068 more = sd->flags & SPLICE_F_MORE;
1069 sd->flags |= SPLICE_F_MORE;
1070
1071 WARN_ON_ONCE(!pipe_is_empty(pipe));
1072
1073 while (len) {
1074 size_t read_len;
1075 loff_t pos = sd->pos, prev_pos = pos;
1076
1077 ret = do_splice_read(in, &pos, pipe, len, flags);
1078 if (unlikely(ret <= 0))
1079 goto read_failure;
1080
1081 read_len = ret;
1082 sd->total_len = read_len;
1083
1084 /*
1085 * If we now have sufficient data to fulfill the request then
1086 * we clear SPLICE_F_MORE if it was not set initially.
1087 */
1088 if (read_len >= len && !more)
1089 sd->flags &= ~SPLICE_F_MORE;
1090
1091 /*
1092 * NOTE: nonblocking mode only applies to the input. We
1093 * must not do the output in nonblocking mode as then we
1094 * could get stuck data in the internal pipe:
1095 */
1096 ret = actor(pipe, sd);
1097 if (unlikely(ret <= 0)) {
1098 sd->pos = prev_pos;
1099 goto out_release;
1100 }
1101
1102 bytes += ret;
1103 len -= ret;
1104 sd->pos = pos;
1105
1106 if (ret < read_len) {
1107 sd->pos = prev_pos + ret;
1108 goto out_release;
1109 }
1110 }
1111
1112 done:
1113 pipe->tail = pipe->head = 0;
1114 file_accessed(in);
1115 return bytes;
1116
1117 read_failure:
1118 /*
1119 * If the user did *not* set SPLICE_F_MORE *and* we didn't hit that
1120 * "use all of len" case that cleared SPLICE_F_MORE, *and* we did a
1121 * "->splice_in()" that returned EOF (ie zero) *and* we have sent at
1122 * least 1 byte *then* we will also do the ->splice_eof() call.
1123 */
1124 if (ret == 0 && !more && len > 0 && bytes)
1125 do_splice_eof(sd);
1126 out_release:
1127 /*
1128 * If we did an incomplete transfer we must release
1129 * the pipe buffers in question:
1130 */
1131 for (i = 0; i < pipe->ring_size; i++) {
1132 struct pipe_buffer *buf = &pipe->bufs[i];
1133
1134 if (buf->ops)
1135 pipe_buf_release(pipe, buf);
1136 }
1137
1138 if (!bytes)
1139 bytes = ret;
1140
1141 goto done;
1142 }
1143
1144 /**
1145 * vfs_splice_to_actor - call an actor on data read from a file
1146 * @in: file to read from
1147 * @pos: file offset
1148 * @count: maximum number of bytes to read
1149 * @actor: callback to process a pipe's worth of data
1150 * @private: private data passed to @actor
1151 *
1152 * Read up to @count worth of data from @in at @pos, and call @actor
1153 * when the hidden pipe used to buffer the data is full. Ensures the
1154 * read is allowed using rw_verify_area() and emits fsnotify access
1155 * events. @in must be seekable (FMODE_LSEEK).
1156 *
1157 * Return: The number of bytes spliced, or a negative errno.
1158 */
vfs_splice_to_actor(struct file * in,loff_t pos,size_t count,splice_direct_actor * actor,void * private)1159 ssize_t vfs_splice_to_actor(struct file *in, loff_t pos, size_t count,
1160 splice_direct_actor *actor, void *private)
1161 {
1162 struct splice_desc sd = {
1163 .total_len = count,
1164 .pos = pos,
1165 .u.data = private,
1166 };
1167 ssize_t ret;
1168
1169 ret = rw_verify_area(READ, in, &sd.pos, sd.total_len);
1170 if (ret < 0)
1171 return ret;
1172
1173 ret = splice_direct_to_actor(in, &sd, actor);
1174 if (ret >= 0)
1175 fsnotify_access(in);
1176 return ret;
1177 }
1178 EXPORT_SYMBOL(vfs_splice_to_actor);
1179
direct_splice_actor(struct pipe_inode_info * pipe,struct splice_desc * sd)1180 static int direct_splice_actor(struct pipe_inode_info *pipe,
1181 struct splice_desc *sd)
1182 {
1183 struct file *file = sd->u.file;
1184 long ret;
1185
1186 file_start_write(file);
1187 ret = do_splice_from(pipe, file, sd->opos, sd->total_len, sd->flags);
1188 file_end_write(file);
1189 return ret;
1190 }
1191
splice_file_range_actor(struct pipe_inode_info * pipe,struct splice_desc * sd)1192 static int splice_file_range_actor(struct pipe_inode_info *pipe,
1193 struct splice_desc *sd)
1194 {
1195 struct file *file = sd->u.file;
1196
1197 return do_splice_from(pipe, file, sd->opos, sd->total_len, sd->flags);
1198 }
1199
direct_file_splice_eof(struct splice_desc * sd)1200 static void direct_file_splice_eof(struct splice_desc *sd)
1201 {
1202 struct file *file = sd->u.file;
1203
1204 if (file->f_op->splice_eof)
1205 file->f_op->splice_eof(file);
1206 }
1207
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)1208 static ssize_t do_splice_direct_actor(struct file *in, loff_t *ppos,
1209 struct file *out, loff_t *opos,
1210 size_t len, unsigned int flags,
1211 splice_direct_actor *actor)
1212 {
1213 struct splice_desc sd = {
1214 .len = len,
1215 .total_len = len,
1216 .flags = flags,
1217 .pos = *ppos,
1218 .u.file = out,
1219 .splice_eof = direct_file_splice_eof,
1220 .opos = opos,
1221 };
1222 ssize_t ret;
1223
1224 if (unlikely(!(out->f_mode & FMODE_WRITE)))
1225 return -EBADF;
1226
1227 if (unlikely(out->f_flags & O_APPEND))
1228 return -EINVAL;
1229
1230 ret = splice_direct_to_actor(in, &sd, actor);
1231 if (ret > 0)
1232 *ppos = sd.pos;
1233
1234 return ret;
1235 }
1236 /**
1237 * do_splice_direct - splices data directly between two files
1238 * @in: file to splice from
1239 * @ppos: input file offset
1240 * @out: file to splice to
1241 * @opos: output file offset
1242 * @len: number of bytes to splice
1243 * @flags: splice modifier flags
1244 *
1245 * Description:
1246 * For use by do_sendfile(). splice can easily emulate sendfile, but
1247 * doing it in the application would incur an extra system call
1248 * (splice in + splice out, as compared to just sendfile()). So this helper
1249 * can splice directly through a process-private pipe.
1250 *
1251 * Callers already called rw_verify_area() on the entire range.
1252 */
do_splice_direct(struct file * in,loff_t * ppos,struct file * out,loff_t * opos,size_t len,unsigned int flags)1253 ssize_t do_splice_direct(struct file *in, loff_t *ppos, struct file *out,
1254 loff_t *opos, size_t len, unsigned int flags)
1255 {
1256 return do_splice_direct_actor(in, ppos, out, opos, len, flags,
1257 direct_splice_actor);
1258 }
1259 EXPORT_SYMBOL(do_splice_direct);
1260
1261 /**
1262 * splice_file_range - splices data between two files for copy_file_range()
1263 * @in: file to splice from
1264 * @ppos: input file offset
1265 * @out: file to splice to
1266 * @opos: output file offset
1267 * @len: number of bytes to splice
1268 *
1269 * Description:
1270 * For use by ->copy_file_range() methods.
1271 * Like do_splice_direct(), but vfs_copy_file_range() already holds
1272 * start_file_write() on @out file.
1273 *
1274 * Callers already called rw_verify_area() on the entire range.
1275 */
splice_file_range(struct file * in,loff_t * ppos,struct file * out,loff_t * opos,size_t len)1276 ssize_t splice_file_range(struct file *in, loff_t *ppos, struct file *out,
1277 loff_t *opos, size_t len)
1278 {
1279 lockdep_assert(file_write_started(out));
1280
1281 return do_splice_direct_actor(in, ppos, out, opos,
1282 min_t(size_t, len, MAX_RW_COUNT),
1283 0, splice_file_range_actor);
1284 }
1285 EXPORT_SYMBOL(splice_file_range);
1286
wait_for_space(struct pipe_inode_info * pipe,unsigned flags)1287 static int wait_for_space(struct pipe_inode_info *pipe, unsigned flags)
1288 {
1289 for (;;) {
1290 if (unlikely(!pipe->readers)) {
1291 send_sig(SIGPIPE, current, 0);
1292 return -EPIPE;
1293 }
1294 if (!pipe_is_full(pipe))
1295 return 0;
1296 if (flags & SPLICE_F_NONBLOCK)
1297 return -EAGAIN;
1298 if (signal_pending(current))
1299 return -ERESTARTSYS;
1300 pipe_wait_writable(pipe);
1301 }
1302 }
1303
1304 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1305 struct pipe_inode_info *opipe,
1306 size_t len, unsigned int flags);
1307
splice_file_to_pipe(struct file * in,struct pipe_inode_info * opipe,loff_t * offset,size_t len,unsigned int flags)1308 ssize_t splice_file_to_pipe(struct file *in,
1309 struct pipe_inode_info *opipe,
1310 loff_t *offset,
1311 size_t len, unsigned int flags)
1312 {
1313 ssize_t ret;
1314
1315 pipe_lock(opipe);
1316 ret = wait_for_space(opipe, flags);
1317 if (!ret)
1318 ret = do_splice_read(in, offset, opipe, len, flags);
1319 pipe_unlock(opipe);
1320 if (ret > 0)
1321 wakeup_pipe_readers(opipe);
1322 return ret;
1323 }
1324
1325 /*
1326 * Determine where to splice to/from.
1327 */
do_splice(struct file * in,loff_t * off_in,struct file * out,loff_t * off_out,size_t len,unsigned int flags)1328 ssize_t do_splice(struct file *in, loff_t *off_in, struct file *out,
1329 loff_t *off_out, size_t len, unsigned int flags)
1330 {
1331 struct pipe_inode_info *ipipe;
1332 struct pipe_inode_info *opipe;
1333 loff_t offset;
1334 ssize_t ret;
1335
1336 if (unlikely(!(in->f_mode & FMODE_READ) ||
1337 !(out->f_mode & FMODE_WRITE)))
1338 return -EBADF;
1339
1340 ipipe = get_pipe_info(in, true);
1341 opipe = get_pipe_info(out, true);
1342
1343 if (ipipe && opipe) {
1344 if (off_in || off_out)
1345 return -ESPIPE;
1346
1347 /* Splicing to self would be fun, but... */
1348 if (ipipe == opipe)
1349 return -EINVAL;
1350
1351 if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1352 flags |= SPLICE_F_NONBLOCK;
1353
1354 ret = splice_pipe_to_pipe(ipipe, opipe, len, flags);
1355 } else if (ipipe) {
1356 if (off_in)
1357 return -ESPIPE;
1358 if (off_out) {
1359 if (!(out->f_mode & FMODE_PWRITE))
1360 return -EINVAL;
1361 offset = *off_out;
1362 } else {
1363 offset = out->f_pos;
1364 }
1365
1366 if (unlikely(out->f_flags & O_APPEND))
1367 return -EINVAL;
1368
1369 ret = rw_verify_area(WRITE, out, &offset, len);
1370 if (unlikely(ret < 0))
1371 return ret;
1372
1373 if (in->f_flags & O_NONBLOCK)
1374 flags |= SPLICE_F_NONBLOCK;
1375
1376 file_start_write(out);
1377 ret = do_splice_from(ipipe, out, &offset, len, flags);
1378 file_end_write(out);
1379
1380 if (!off_out)
1381 out->f_pos = offset;
1382 else
1383 *off_out = offset;
1384 } else if (opipe) {
1385 if (off_out)
1386 return -ESPIPE;
1387 if (off_in) {
1388 if (!(in->f_mode & FMODE_PREAD))
1389 return -EINVAL;
1390 offset = *off_in;
1391 } else {
1392 offset = in->f_pos;
1393 }
1394
1395 ret = rw_verify_area(READ, in, &offset, len);
1396 if (unlikely(ret < 0))
1397 return ret;
1398
1399 if (out->f_flags & O_NONBLOCK)
1400 flags |= SPLICE_F_NONBLOCK;
1401
1402 ret = splice_file_to_pipe(in, opipe, &offset, len, flags);
1403
1404 if (!off_in)
1405 in->f_pos = offset;
1406 else
1407 *off_in = offset;
1408 } else {
1409 ret = -EINVAL;
1410 }
1411
1412 if (ret > 0) {
1413 /*
1414 * Generate modify out before access in:
1415 * do_splice_from() may've already sent modify out,
1416 * and this ensures the events get merged.
1417 */
1418 fsnotify_modify(out);
1419 fsnotify_access(in);
1420 }
1421
1422 return ret;
1423 }
1424
__do_splice(struct file * in,loff_t __user * off_in,struct file * out,loff_t __user * off_out,size_t len,unsigned int flags)1425 static ssize_t __do_splice(struct file *in, loff_t __user *off_in,
1426 struct file *out, loff_t __user *off_out,
1427 size_t len, unsigned int flags)
1428 {
1429 struct pipe_inode_info *ipipe;
1430 struct pipe_inode_info *opipe;
1431 loff_t offset, *__off_in = NULL, *__off_out = NULL;
1432 ssize_t ret;
1433
1434 ipipe = get_pipe_info(in, true);
1435 opipe = get_pipe_info(out, true);
1436
1437 if (ipipe) {
1438 if (off_in)
1439 return -ESPIPE;
1440 pipe_clear_nowait(in);
1441 }
1442 if (opipe) {
1443 if (off_out)
1444 return -ESPIPE;
1445 pipe_clear_nowait(out);
1446 }
1447
1448 if (off_out) {
1449 if (copy_from_user(&offset, off_out, sizeof(loff_t)))
1450 return -EFAULT;
1451 __off_out = &offset;
1452 }
1453 if (off_in) {
1454 if (copy_from_user(&offset, off_in, sizeof(loff_t)))
1455 return -EFAULT;
1456 __off_in = &offset;
1457 }
1458
1459 ret = do_splice(in, __off_in, out, __off_out, len, flags);
1460 if (ret < 0)
1461 return ret;
1462
1463 if (__off_out && copy_to_user(off_out, __off_out, sizeof(loff_t)))
1464 return -EFAULT;
1465 if (__off_in && copy_to_user(off_in, __off_in, sizeof(loff_t)))
1466 return -EFAULT;
1467
1468 return ret;
1469 }
1470
iter_to_pipe(struct iov_iter * from,struct pipe_inode_info * pipe,unsigned int flags)1471 static ssize_t iter_to_pipe(struct iov_iter *from,
1472 struct pipe_inode_info *pipe,
1473 unsigned int flags)
1474 {
1475 struct pipe_buffer buf = {
1476 .ops = &user_page_pipe_buf_ops,
1477 .flags = flags
1478 };
1479 size_t total = 0;
1480 ssize_t ret = 0;
1481
1482 while (iov_iter_count(from)) {
1483 struct page *pages[16];
1484 ssize_t left;
1485 size_t start;
1486 int i, n;
1487
1488 left = iov_iter_get_pages2(from, pages, ~0UL, 16, &start);
1489 if (left <= 0) {
1490 ret = left;
1491 break;
1492 }
1493
1494 n = DIV_ROUND_UP(left + start, PAGE_SIZE);
1495 for (i = 0; i < n; i++) {
1496 int size = umin(left, PAGE_SIZE - start);
1497
1498 buf.page = pages[i];
1499 buf.offset = start;
1500 buf.len = size;
1501 ret = add_to_pipe(pipe, &buf);
1502 if (unlikely(ret < 0)) {
1503 iov_iter_revert(from, left);
1504 // this one got dropped by add_to_pipe()
1505 while (++i < n)
1506 put_page(pages[i]);
1507 goto out;
1508 }
1509 total += ret;
1510 left -= size;
1511 start = 0;
1512 }
1513 }
1514 out:
1515 return total ? total : ret;
1516 }
1517
pipe_to_user(struct pipe_inode_info * pipe,struct pipe_buffer * buf,struct splice_desc * sd)1518 static int pipe_to_user(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1519 struct splice_desc *sd)
1520 {
1521 int n = copy_page_to_iter(buf->page, buf->offset, sd->len, sd->u.data);
1522 return n == sd->len ? n : -EFAULT;
1523 }
1524
1525 /*
1526 * For lack of a better implementation, implement vmsplice() to userspace
1527 * as a simple copy of the pipe's pages to the user iov.
1528 */
vmsplice_to_user(struct file * file,struct iov_iter * iter,unsigned int flags)1529 static ssize_t vmsplice_to_user(struct file *file, struct iov_iter *iter,
1530 unsigned int flags)
1531 {
1532 struct pipe_inode_info *pipe = get_pipe_info(file, true);
1533 struct splice_desc sd = {
1534 .total_len = iov_iter_count(iter),
1535 .flags = flags,
1536 .u.data = iter
1537 };
1538 ssize_t ret = 0;
1539
1540 if (!pipe)
1541 return -EBADF;
1542
1543 pipe_clear_nowait(file);
1544
1545 if (sd.total_len) {
1546 pipe_lock(pipe);
1547 ret = __splice_from_pipe(pipe, &sd, pipe_to_user);
1548 pipe_unlock(pipe);
1549 }
1550
1551 if (ret > 0)
1552 fsnotify_access(file);
1553
1554 return ret;
1555 }
1556
1557 /*
1558 * vmsplice splices a user address range into a pipe. It can be thought of
1559 * as splice-from-memory, where the regular splice is splice-from-file (or
1560 * to file). In both cases the output is a pipe, naturally.
1561 */
vmsplice_to_pipe(struct file * file,struct iov_iter * iter,unsigned int flags)1562 static ssize_t vmsplice_to_pipe(struct file *file, struct iov_iter *iter,
1563 unsigned int flags)
1564 {
1565 struct pipe_inode_info *pipe;
1566 ssize_t ret = 0;
1567 unsigned buf_flag = 0;
1568
1569 if (flags & SPLICE_F_GIFT)
1570 buf_flag = PIPE_BUF_FLAG_GIFT;
1571
1572 pipe = get_pipe_info(file, true);
1573 if (!pipe)
1574 return -EBADF;
1575
1576 pipe_clear_nowait(file);
1577
1578 pipe_lock(pipe);
1579 ret = wait_for_space(pipe, flags);
1580 if (!ret)
1581 ret = iter_to_pipe(iter, pipe, buf_flag);
1582 pipe_unlock(pipe);
1583 if (ret > 0) {
1584 wakeup_pipe_readers(pipe);
1585 fsnotify_modify(file);
1586 }
1587 return ret;
1588 }
1589
1590 /*
1591 * Note that vmsplice only really supports true splicing _from_ user memory
1592 * to a pipe, not the other way around. Splicing from user memory is a simple
1593 * operation that can be supported without any funky alignment restrictions
1594 * or nasty vm tricks. We simply map in the user memory and fill them into
1595 * a pipe. The reverse isn't quite as easy, though. There are two possible
1596 * solutions for that:
1597 *
1598 * - memcpy() the data internally, at which point we might as well just
1599 * do a regular read() on the buffer anyway.
1600 * - Lots of nasty vm tricks, that are neither fast nor flexible (it
1601 * has restriction limitations on both ends of the pipe).
1602 *
1603 * Currently we punt and implement it as a normal copy, see pipe_to_user().
1604 *
1605 */
SYSCALL_DEFINE4(vmsplice,int,fd,const struct iovec __user *,uiov,unsigned long,nr_segs,unsigned int,flags)1606 SYSCALL_DEFINE4(vmsplice, int, fd, const struct iovec __user *, uiov,
1607 unsigned long, nr_segs, unsigned int, flags)
1608 {
1609 struct iovec iovstack[UIO_FASTIOV];
1610 struct iovec *iov = iovstack;
1611 struct iov_iter iter;
1612 ssize_t error;
1613 int type;
1614
1615 if (unlikely(flags & ~SPLICE_F_ALL))
1616 return -EINVAL;
1617
1618 CLASS(fd, f)(fd);
1619 if (fd_empty(f))
1620 return -EBADF;
1621 if (fd_file(f)->f_mode & FMODE_WRITE)
1622 type = ITER_SOURCE;
1623 else if (fd_file(f)->f_mode & FMODE_READ)
1624 type = ITER_DEST;
1625 else
1626 return -EBADF;
1627
1628 error = import_iovec(type, uiov, nr_segs,
1629 ARRAY_SIZE(iovstack), &iov, &iter);
1630 if (error < 0)
1631 return error;
1632
1633 if (!iov_iter_count(&iter))
1634 error = 0;
1635 else if (type == ITER_SOURCE)
1636 error = vmsplice_to_pipe(fd_file(f), &iter, flags);
1637 else
1638 error = vmsplice_to_user(fd_file(f), &iter, flags);
1639
1640 kfree(iov);
1641 return error;
1642 }
1643
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)1644 SYSCALL_DEFINE6(splice, int, fd_in, loff_t __user *, off_in,
1645 int, fd_out, loff_t __user *, off_out,
1646 size_t, len, unsigned int, flags)
1647 {
1648 if (unlikely(!len))
1649 return 0;
1650
1651 if (unlikely(flags & ~SPLICE_F_ALL))
1652 return -EINVAL;
1653
1654 CLASS(fd, in)(fd_in);
1655 if (fd_empty(in))
1656 return -EBADF;
1657
1658 CLASS(fd, out)(fd_out);
1659 if (fd_empty(out))
1660 return -EBADF;
1661
1662 return __do_splice(fd_file(in), off_in, fd_file(out), off_out,
1663 len, flags);
1664 }
1665
1666 /*
1667 * Make sure there's data to read. Wait for input if we can, otherwise
1668 * return an appropriate error.
1669 */
ipipe_prep(struct pipe_inode_info * pipe,unsigned int flags)1670 static int ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1671 {
1672 int ret;
1673
1674 /*
1675 * Check the pipe occupancy without the inode lock first. This function
1676 * is speculative anyways, so missing one is ok.
1677 */
1678 if (!pipe_is_empty(pipe))
1679 return 0;
1680
1681 ret = 0;
1682 pipe_lock(pipe);
1683
1684 while (pipe_is_empty(pipe)) {
1685 if (signal_pending(current)) {
1686 ret = -ERESTARTSYS;
1687 break;
1688 }
1689 if (!pipe->writers)
1690 break;
1691 if (flags & SPLICE_F_NONBLOCK) {
1692 ret = -EAGAIN;
1693 break;
1694 }
1695 pipe_wait_readable(pipe);
1696 }
1697
1698 pipe_unlock(pipe);
1699 return ret;
1700 }
1701
1702 /*
1703 * Make sure there's writeable room. Wait for room if we can, otherwise
1704 * return an appropriate error.
1705 */
opipe_prep(struct pipe_inode_info * pipe,unsigned int flags)1706 static int opipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1707 {
1708 int ret;
1709
1710 /*
1711 * Check pipe occupancy without the inode lock first. This function
1712 * is speculative anyways, so missing one is ok.
1713 */
1714 if (!pipe_is_full(pipe))
1715 return 0;
1716
1717 ret = 0;
1718 pipe_lock(pipe);
1719
1720 while (pipe_is_full(pipe)) {
1721 if (!pipe->readers) {
1722 send_sig(SIGPIPE, current, 0);
1723 ret = -EPIPE;
1724 break;
1725 }
1726 if (flags & SPLICE_F_NONBLOCK) {
1727 ret = -EAGAIN;
1728 break;
1729 }
1730 if (signal_pending(current)) {
1731 ret = -ERESTARTSYS;
1732 break;
1733 }
1734 pipe_wait_writable(pipe);
1735 }
1736
1737 pipe_unlock(pipe);
1738 return ret;
1739 }
1740
1741 /*
1742 * Splice contents of ipipe to opipe.
1743 */
splice_pipe_to_pipe(struct pipe_inode_info * ipipe,struct pipe_inode_info * opipe,size_t len,unsigned int flags)1744 static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1745 struct pipe_inode_info *opipe,
1746 size_t len, unsigned int flags)
1747 {
1748 struct pipe_buffer *ibuf, *obuf;
1749 unsigned int i_head, o_head;
1750 unsigned int i_tail, o_tail;
1751 int ret = 0;
1752 bool input_wakeup = false;
1753
1754
1755 retry:
1756 ret = ipipe_prep(ipipe, flags);
1757 if (ret)
1758 return ret;
1759
1760 ret = opipe_prep(opipe, flags);
1761 if (ret)
1762 return ret;
1763
1764 /*
1765 * Potential ABBA deadlock, work around it by ordering lock
1766 * grabbing by pipe info address. Otherwise two different processes
1767 * could deadlock (one doing tee from A -> B, the other from B -> A).
1768 */
1769 pipe_double_lock(ipipe, opipe);
1770
1771 i_tail = ipipe->tail;
1772 o_head = opipe->head;
1773
1774 do {
1775 size_t o_len;
1776
1777 if (!opipe->readers) {
1778 send_sig(SIGPIPE, current, 0);
1779 if (!ret)
1780 ret = -EPIPE;
1781 break;
1782 }
1783
1784 i_head = ipipe->head;
1785 o_tail = opipe->tail;
1786
1787 if (pipe_empty(i_head, i_tail) && !ipipe->writers)
1788 break;
1789
1790 /*
1791 * Cannot make any progress, because either the input
1792 * pipe is empty or the output pipe is full.
1793 */
1794 if (pipe_empty(i_head, i_tail) ||
1795 pipe_full(o_head, o_tail, opipe->max_usage)) {
1796 /* Already processed some buffers, break */
1797 if (ret)
1798 break;
1799
1800 if (flags & SPLICE_F_NONBLOCK) {
1801 ret = -EAGAIN;
1802 break;
1803 }
1804
1805 /*
1806 * We raced with another reader/writer and haven't
1807 * managed to process any buffers. A zero return
1808 * value means EOF, so retry instead.
1809 */
1810 pipe_unlock(ipipe);
1811 pipe_unlock(opipe);
1812 goto retry;
1813 }
1814
1815 ibuf = pipe_buf(ipipe, i_tail);
1816 obuf = pipe_buf(opipe, o_head);
1817
1818 if (len >= ibuf->len) {
1819 /*
1820 * Simply move the whole buffer from ipipe to opipe
1821 */
1822 *obuf = *ibuf;
1823 ibuf->ops = NULL;
1824 i_tail++;
1825 ipipe->tail = i_tail;
1826 input_wakeup = true;
1827 o_len = obuf->len;
1828 o_head++;
1829 opipe->head = o_head;
1830 } else {
1831 /*
1832 * Get a reference to this pipe buffer,
1833 * so we can copy the contents over.
1834 */
1835 if (!pipe_buf_get(ipipe, ibuf)) {
1836 if (ret == 0)
1837 ret = -EFAULT;
1838 break;
1839 }
1840 *obuf = *ibuf;
1841
1842 /*
1843 * Don't inherit the gift and merge flags, we need to
1844 * prevent multiple steals of this page.
1845 */
1846 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1847 obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1848
1849 obuf->len = len;
1850 ibuf->offset += len;
1851 ibuf->len -= len;
1852 o_len = len;
1853 o_head++;
1854 opipe->head = o_head;
1855 }
1856 ret += o_len;
1857 len -= o_len;
1858 } while (len);
1859
1860 pipe_unlock(ipipe);
1861 pipe_unlock(opipe);
1862
1863 /*
1864 * If we put data in the output pipe, wakeup any potential readers.
1865 */
1866 if (ret > 0)
1867 wakeup_pipe_readers(opipe);
1868
1869 if (input_wakeup)
1870 wakeup_pipe_writers(ipipe);
1871
1872 return ret;
1873 }
1874
1875 /*
1876 * Link contents of ipipe to opipe.
1877 */
link_pipe(struct pipe_inode_info * ipipe,struct pipe_inode_info * opipe,size_t len,unsigned int flags)1878 static ssize_t link_pipe(struct pipe_inode_info *ipipe,
1879 struct pipe_inode_info *opipe,
1880 size_t len, unsigned int flags)
1881 {
1882 struct pipe_buffer *ibuf, *obuf;
1883 unsigned int i_head, o_head;
1884 unsigned int i_tail, o_tail;
1885 ssize_t ret = 0;
1886
1887 /*
1888 * Potential ABBA deadlock, work around it by ordering lock
1889 * grabbing by pipe info address. Otherwise two different processes
1890 * could deadlock (one doing tee from A -> B, the other from B -> A).
1891 */
1892 pipe_double_lock(ipipe, opipe);
1893
1894 i_tail = ipipe->tail;
1895 o_head = opipe->head;
1896
1897 do {
1898 if (!opipe->readers) {
1899 send_sig(SIGPIPE, current, 0);
1900 if (!ret)
1901 ret = -EPIPE;
1902 break;
1903 }
1904
1905 i_head = ipipe->head;
1906 o_tail = opipe->tail;
1907
1908 /*
1909 * If we have iterated all input buffers or run out of
1910 * output room, break.
1911 */
1912 if (pipe_empty(i_head, i_tail) ||
1913 pipe_full(o_head, o_tail, opipe->max_usage))
1914 break;
1915
1916 ibuf = pipe_buf(ipipe, i_tail);
1917 obuf = pipe_buf(opipe, o_head);
1918
1919 /*
1920 * Get a reference to this pipe buffer,
1921 * so we can copy the contents over.
1922 */
1923 if (!pipe_buf_get(ipipe, ibuf)) {
1924 if (ret == 0)
1925 ret = -EFAULT;
1926 break;
1927 }
1928
1929 *obuf = *ibuf;
1930
1931 /*
1932 * Don't inherit the gift and merge flag, we need to prevent
1933 * multiple steals of this page.
1934 */
1935 obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1936 obuf->flags &= ~PIPE_BUF_FLAG_CAN_MERGE;
1937
1938 if (obuf->len > len)
1939 obuf->len = len;
1940 ret += obuf->len;
1941 len -= obuf->len;
1942
1943 o_head++;
1944 opipe->head = o_head;
1945 i_tail++;
1946 } while (len);
1947
1948 pipe_unlock(ipipe);
1949 pipe_unlock(opipe);
1950
1951 /*
1952 * If we put data in the output pipe, wakeup any potential readers.
1953 */
1954 if (ret > 0)
1955 wakeup_pipe_readers(opipe);
1956
1957 return ret;
1958 }
1959
1960 /*
1961 * This is a tee(1) implementation that works on pipes. It doesn't copy
1962 * any data, it simply references the 'in' pages on the 'out' pipe.
1963 * The 'flags' used are the SPLICE_F_* variants, currently the only
1964 * applicable one is SPLICE_F_NONBLOCK.
1965 */
do_tee(struct file * in,struct file * out,size_t len,unsigned int flags)1966 ssize_t do_tee(struct file *in, struct file *out, size_t len,
1967 unsigned int flags)
1968 {
1969 struct pipe_inode_info *ipipe = get_pipe_info(in, true);
1970 struct pipe_inode_info *opipe = get_pipe_info(out, true);
1971 ssize_t ret = -EINVAL;
1972
1973 if (unlikely(!(in->f_mode & FMODE_READ) ||
1974 !(out->f_mode & FMODE_WRITE)))
1975 return -EBADF;
1976
1977 /*
1978 * Duplicate the contents of ipipe to opipe without actually
1979 * copying the data.
1980 */
1981 if (ipipe && opipe && ipipe != opipe) {
1982 if ((in->f_flags | out->f_flags) & O_NONBLOCK)
1983 flags |= SPLICE_F_NONBLOCK;
1984
1985 /*
1986 * Keep going, unless we encounter an error. The ipipe/opipe
1987 * ordering doesn't really matter.
1988 */
1989 ret = ipipe_prep(ipipe, flags);
1990 if (!ret) {
1991 ret = opipe_prep(opipe, flags);
1992 if (!ret)
1993 ret = link_pipe(ipipe, opipe, len, flags);
1994 }
1995 }
1996
1997 if (ret > 0) {
1998 fsnotify_access(in);
1999 fsnotify_modify(out);
2000 }
2001
2002 return ret;
2003 }
2004
SYSCALL_DEFINE4(tee,int,fdin,int,fdout,size_t,len,unsigned int,flags)2005 SYSCALL_DEFINE4(tee, int, fdin, int, fdout, size_t, len, unsigned int, flags)
2006 {
2007 if (unlikely(flags & ~SPLICE_F_ALL))
2008 return -EINVAL;
2009
2010 if (unlikely(!len))
2011 return 0;
2012
2013 CLASS(fd, in)(fdin);
2014 if (fd_empty(in))
2015 return -EBADF;
2016
2017 CLASS(fd, out)(fdout);
2018 if (fd_empty(out))
2019 return -EBADF;
2020
2021 return do_tee(fd_file(in), fd_file(out), len, flags);
2022 }
2023