splice.c 46.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * "splice": joining two ropes together by interweaving their strands.
 *
 * This is the "extended pipe" functionality, where a pipe is used as
 * an arbitrary in-memory buffer. Think of a pipe as a small kernel
 * buffer that you can use to transfer data from one end to the other.
 *
 * The traditional unix read/write is extended with a "splice()" operation
 * that transfers data buffers to or from a pipe buffer.
 *
 * Named by Larry McVoy, original implementation from Linus, extended by
12 13
 * Jens to support splicing to files, network, direct splicing, etc and
 * fixing lots of bugs.
14
 *
15
 * Copyright (C) 2005-2006 Jens Axboe <axboe@kernel.dk>
16 17
 * Copyright (C) 2005-2006 Linus Torvalds <torvalds@osdl.org>
 * Copyright (C) 2006 Ingo Molnar <mingo@elte.hu>
18 19 20 21 22
 *
 */
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/pagemap.h>
23
#include <linux/splice.h>
KAMEZAWA Hiroyuki's avatar
KAMEZAWA Hiroyuki committed
24
#include <linux/memcontrol.h>
25
#include <linux/mm_inline.h>
26
#include <linux/swap.h>
27
#include <linux/writeback.h>
28
#include <linux/export.h>
29
#include <linux/syscalls.h>
30
#include <linux/uio.h>
31
#include <linux/security.h>
32
#include <linux/gfp.h>
33
#include <linux/socket.h>
34
#include <linux/compat.h>
35
#include "internal.h"
36

37 38 39 40 41 42
/*
 * Attempt to steal a page from a pipe buffer. This should perhaps go into
 * a vm helper function, it's already simplified quite a bit by the
 * addition of remove_mapping(). If success is returned, the caller may
 * attempt to reuse this page for another destination.
 */
43
static int page_cache_pipe_buf_steal(struct pipe_inode_info *pipe,
44 45 46
				     struct pipe_buffer *buf)
{
	struct page *page = buf->page;
47
	struct address_space *mapping;
48

49 50
	lock_page(page);

51 52 53
	mapping = page_mapping(page);
	if (mapping) {
		WARN_ON(!PageUptodate(page));
54

55 56 57 58 59 60 61 62 63
		/*
		 * At least for ext2 with nobh option, we need to wait on
		 * writeback completing on this page, since we'll remove it
		 * from the pagecache.  Otherwise truncate wont wait on the
		 * page, allowing the disk blocks to be reused by someone else
		 * before we actually wrote our data to them. fs corruption
		 * ensues.
		 */
		wait_on_page_writeback(page);
64

65 66
		if (page_has_private(page) &&
		    !try_to_release_page(page, GFP_KERNEL))
67
			goto out_unlock;
68

69 70 71 72 73 74 75 76
		/*
		 * If we succeeded in removing the mapping, set LRU flag
		 * and return good.
		 */
		if (remove_mapping(mapping, page)) {
			buf->flags |= PIPE_BUF_FLAG_LRU;
			return 0;
		}
77
	}
78

79 80 81 82
	/*
	 * Raced with truncate or failed to remove page from current
	 * address space, unlock and return failure.
	 */
83
out_unlock:
84 85
	unlock_page(page);
	return 1;
86 87
}

88
static void page_cache_pipe_buf_release(struct pipe_inode_info *pipe,
89 90 91
					struct pipe_buffer *buf)
{
	page_cache_release(buf->page);
Jens Axboe's avatar
Jens Axboe committed
92
	buf->flags &= ~PIPE_BUF_FLAG_LRU;
93 94
}

95 96 97 98
/*
 * Check whether the contents of buf is OK to access. Since the content
 * is a page cache page, IO may be in flight.
 */
99 100
static int page_cache_pipe_buf_confirm(struct pipe_inode_info *pipe,
				       struct pipe_buffer *buf)
101 102
{
	struct page *page = buf->page;
103
	int err;
104 105

	if (!PageUptodate(page)) {
106 107 108 109
		lock_page(page);

		/*
		 * Page got truncated/unhashed. This will cause a 0-byte
Ingo Molnar's avatar
Ingo Molnar committed
110
		 * splice, if this is the first page.
111 112 113 114 115
		 */
		if (!page->mapping) {
			err = -ENODATA;
			goto error;
		}
116

117
		/*
Ingo Molnar's avatar
Ingo Molnar committed
118
		 * Uh oh, read-error from disk.
119 120 121 122 123 124 125
		 */
		if (!PageUptodate(page)) {
			err = -EIO;
			goto error;
		}

		/*
126
		 * Page is ok afterall, we are done.
127
		 */
128 129 130
		unlock_page(page);
	}

131
	return 0;
132 133
error:
	unlock_page(page);
134
	return err;
135 136
}

137
const struct pipe_buf_operations page_cache_pipe_buf_ops = {
138
	.can_merge = 0,
139
	.confirm = page_cache_pipe_buf_confirm,
140
	.release = page_cache_pipe_buf_release,
141
	.steal = page_cache_pipe_buf_steal,
142
	.get = generic_pipe_buf_get,
143 144
};

145 146 147
static int user_page_pipe_buf_steal(struct pipe_inode_info *pipe,
				    struct pipe_buffer *buf)
{
148 149 150
	if (!(buf->flags & PIPE_BUF_FLAG_GIFT))
		return 1;

Jens Axboe's avatar
Jens Axboe committed
151
	buf->flags |= PIPE_BUF_FLAG_LRU;
152
	return generic_pipe_buf_steal(pipe, buf);
153 154
}

155
static const struct pipe_buf_operations user_page_pipe_buf_ops = {
156
	.can_merge = 0,
157
	.confirm = generic_pipe_buf_confirm,
158 159
	.release = page_cache_pipe_buf_release,
	.steal = user_page_pipe_buf_steal,
160
	.get = generic_pipe_buf_get,
161 162
};

163 164 165 166 167 168 169 170
static void wakeup_pipe_readers(struct pipe_inode_info *pipe)
{
	smp_mb();
	if (waitqueue_active(&pipe->wait))
		wake_up_interruptible(&pipe->wait);
	kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
}

171 172 173 174 175 176
/**
 * splice_to_pipe - fill passed data into a pipe
 * @pipe:	pipe to fill
 * @spd:	data to fill
 *
 * Description:
177
 *    @spd contains a map of pages and len/offset tuples, along with
178 179 180
 *    the struct pipe_buf_operations associated with these pages. This
 *    function will link that data to the pipe.
 *
181
 */
182 183
ssize_t splice_to_pipe(struct pipe_inode_info *pipe,
		       struct splice_pipe_desc *spd)
184
{
185
	unsigned int spd_pages = spd->nr_pages;
186
	int ret, do_wakeup, page_nr;
187

188 189 190
	if (!spd_pages)
		return 0;

191 192
	ret = 0;
	do_wakeup = 0;
193
	page_nr = 0;
194

195
	pipe_lock(pipe);
196 197

	for (;;) {
198
		if (!pipe->readers) {
199 200 201 202 203 204
			send_sig(SIGPIPE, current, 0);
			if (!ret)
				ret = -EPIPE;
			break;
		}

205 206
		if (pipe->nrbufs < pipe->buffers) {
			int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
207
			struct pipe_buffer *buf = pipe->bufs + newbuf;
208

209 210 211
			buf->page = spd->pages[page_nr];
			buf->offset = spd->partial[page_nr].offset;
			buf->len = spd->partial[page_nr].len;
212
			buf->private = spd->partial[page_nr].private;
213
			buf->ops = spd->ops;
214
			buf->flags = 0;
215 216 217
			if (spd->flags & SPLICE_F_GIFT)
				buf->flags |= PIPE_BUF_FLAG_GIFT;

218
			pipe->nrbufs++;
219 220 221
			page_nr++;
			ret += buf->len;

Al Viro's avatar
Al Viro committed
222
			if (pipe->files)
223
				do_wakeup = 1;
224

225
			if (!--spd->nr_pages)
226
				break;
227
			if (pipe->nrbufs < pipe->buffers)
228 229 230 231 232
				continue;

			break;
		}

233
		if (spd->flags & SPLICE_F_NONBLOCK) {
234 235 236 237 238
			if (!ret)
				ret = -EAGAIN;
			break;
		}

239 240 241 242 243 244 245
		if (signal_pending(current)) {
			if (!ret)
				ret = -ERESTARTSYS;
			break;
		}

		if (do_wakeup) {
246
			smp_mb();
247 248 249
			if (waitqueue_active(&pipe->wait))
				wake_up_interruptible_sync(&pipe->wait);
			kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
250 251 252
			do_wakeup = 0;
		}

253 254 255
		pipe->waiting_writers++;
		pipe_wait(pipe);
		pipe->waiting_writers--;
256 257
	}

258
	pipe_unlock(pipe);
259

260 261
	if (do_wakeup)
		wakeup_pipe_readers(pipe);
262

263
	while (page_nr < spd_pages)
264
		spd->spd_release(spd, page_nr++);
265 266 267

	return ret;
}
268
EXPORT_SYMBOL_GPL(splice_to_pipe);
269

270
void spd_release_page(struct splice_pipe_desc *spd, unsigned int i)
271 272 273 274
{
	page_cache_release(spd->pages[i]);
}

275 276 277 278
/*
 * Check if we need to grow the arrays holding pages and partial page
 * descriptions.
 */
279
int splice_grow_spd(const struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
280
{
281 282 283 284
	unsigned int buffers = ACCESS_ONCE(pipe->buffers);

	spd->nr_pages_max = buffers;
	if (buffers <= PIPE_DEF_BUFFERS)
285 286
		return 0;

287 288
	spd->pages = kmalloc(buffers * sizeof(struct page *), GFP_KERNEL);
	spd->partial = kmalloc(buffers * sizeof(struct partial_page), GFP_KERNEL);
289 290 291 292 293 294 295 296 297

	if (spd->pages && spd->partial)
		return 0;

	kfree(spd->pages);
	kfree(spd->partial);
	return -ENOMEM;
}

298
void splice_shrink_spd(struct splice_pipe_desc *spd)
299
{
300
	if (spd->nr_pages_max <= PIPE_DEF_BUFFERS)
301 302 303 304 305 306
		return;

	kfree(spd->pages);
	kfree(spd->partial);
}

307
static int
308 309 310
__generic_file_splice_read(struct file *in, loff_t *ppos,
			   struct pipe_inode_info *pipe, size_t len,
			   unsigned int flags)
311 312
{
	struct address_space *mapping = in->f_mapping;
313
	unsigned int loff, nr_pages, req_pages;
314 315
	struct page *pages[PIPE_DEF_BUFFERS];
	struct partial_page partial[PIPE_DEF_BUFFERS];
316
	struct page *page;
317 318
	pgoff_t index, end_index;
	loff_t isize;
319
	int error, page_nr;
320 321 322
	struct splice_pipe_desc spd = {
		.pages = pages,
		.partial = partial,
323
		.nr_pages_max = PIPE_DEF_BUFFERS,
324 325
		.flags = flags,
		.ops = &page_cache_pipe_buf_ops,
326
		.spd_release = spd_release_page,
327
	};
328

329 330 331
	if (splice_grow_spd(pipe, &spd))
		return -ENOMEM;

332
	index = *ppos >> PAGE_CACHE_SHIFT;
333
	loff = *ppos & ~PAGE_CACHE_MASK;
334
	req_pages = (len + loff + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
335
	nr_pages = min(req_pages, spd.nr_pages_max);
336

337 338 339
	/*
	 * Lookup the (hopefully) full range of pages we need.
	 */
340
	spd.nr_pages = find_get_pages_contig(mapping, index, nr_pages, spd.pages);
341
	index += spd.nr_pages;
342

343 344
	/*
	 * If find_get_pages_contig() returned fewer pages than we needed,
345
	 * readahead/allocate the rest and fill in the holes.
346
	 */
347
	if (spd.nr_pages < nr_pages)
348 349
		page_cache_sync_readahead(mapping, &in->f_ra, in,
				index, req_pages - spd.nr_pages);
350

351
	error = 0;
352
	while (spd.nr_pages < nr_pages) {
353
		/*
354 355
		 * Page could be there, find_get_pages_contig() breaks on
		 * the first hole.
356
		 */
357 358 359
		page = find_get_page(mapping, index);
		if (!page) {
			/*
360
			 * page didn't exist, allocate one.
361 362 363 364 365 366
			 */
			page = page_cache_alloc_cold(mapping);
			if (!page)
				break;

			error = add_to_page_cache_lru(page, mapping, index,
367
				   mapping_gfp_constraint(mapping, GFP_KERNEL));
368 369
			if (unlikely(error)) {
				page_cache_release(page);
370 371
				if (error == -EEXIST)
					continue;
372 373
				break;
			}
374 375 376 377 378
			/*
			 * add_to_page_cache() locks the page, unlock it
			 * to avoid convoluting the logic below even more.
			 */
			unlock_page(page);
379 380
		}

381
		spd.pages[spd.nr_pages++] = page;
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
		index++;
	}

	/*
	 * Now loop over the map and see if we need to start IO on any
	 * pages, fill in the partial map, etc.
	 */
	index = *ppos >> PAGE_CACHE_SHIFT;
	nr_pages = spd.nr_pages;
	spd.nr_pages = 0;
	for (page_nr = 0; page_nr < nr_pages; page_nr++) {
		unsigned int this_len;

		if (!len)
			break;

		/*
		 * this_len is the max we'll use from this page
		 */
		this_len = min_t(unsigned long, len, PAGE_CACHE_SIZE - loff);
402
		page = spd.pages[page_nr];
403

404
		if (PageReadahead(page))
405
			page_cache_async_readahead(mapping, &in->f_ra, in,
406
					page, index, req_pages - page_nr);
407

408 409 410 411
		/*
		 * If the page isn't uptodate, we may need to start io on it
		 */
		if (!PageUptodate(page)) {
412
			lock_page(page);
413 414

			/*
415 416 417 418
			 * Page was truncated, or invalidated by the
			 * filesystem.  Redo the find/create, but this time the
			 * page is kept locked, so there's no chance of another
			 * race with truncate/invalidate.
419 420 421
			 */
			if (!page->mapping) {
				unlock_page(page);
422 423 424 425 426 427 428
				page = find_or_create_page(mapping, index,
						mapping_gfp_mask(mapping));

				if (!page) {
					error = -ENOMEM;
					break;
				}
429 430
				page_cache_release(spd.pages[page_nr]);
				spd.pages[page_nr] = page;
431 432 433 434 435 436 437 438
			}
			/*
			 * page was already under io and is now done, great
			 */
			if (PageUptodate(page)) {
				unlock_page(page);
				goto fill_it;
			}
439

440 441 442 443
			/*
			 * need to read in the page
			 */
			error = mapping->a_ops->readpage(in, page);
444
			if (unlikely(error)) {
445 446 447 448 449 450
				/*
				 * We really should re-lookup the page here,
				 * but it complicates things a lot. Instead
				 * lets just do what we already stored, and
				 * we'll get it the next time we are called.
				 */
451
				if (error == AOP_TRUNCATED_PAGE)
452 453
					error = 0;

454 455
				break;
			}
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
		}
fill_it:
		/*
		 * i_size must be checked after PageUptodate.
		 */
		isize = i_size_read(mapping->host);
		end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
		if (unlikely(!isize || index > end_index))
			break;

		/*
		 * if this is the last page, see if we need to shrink
		 * the length and stop
		 */
		if (end_index == index) {
			unsigned int plen;
472 473

			/*
474
			 * max good bytes in this page
475
			 */
476 477
			plen = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
			if (plen <= loff)
478 479 480
				break;

			/*
481
			 * force quit after adding this page
482
			 */
483 484
			this_len = min(this_len, plen - loff);
			len = this_len;
485
		}
486

487 488
		spd.partial[page_nr].offset = loff;
		spd.partial[page_nr].len = this_len;
489
		len -= this_len;
490
		loff = 0;
491 492
		spd.nr_pages++;
		index++;
493 494
	}

495
	/*
496
	 * Release any pages at the end, if we quit early. 'page_nr' is how far
497 498 499
	 * we got, 'nr_pages' is how many pages are in the map.
	 */
	while (page_nr < nr_pages)
500
		page_cache_release(spd.pages[page_nr++]);
501
	in->f_ra.prev_pos = (loff_t)index << PAGE_CACHE_SHIFT;
502

503
	if (spd.nr_pages)
504
		error = splice_to_pipe(pipe, &spd);
505

506
	splice_shrink_spd(&spd);
507
	return error;
508 509
}

510 511 512
/**
 * generic_file_splice_read - splice data from file to a pipe
 * @in:		file to splice from
513
 * @ppos:	position in @in
514 515 516 517
 * @pipe:	pipe to splice to
 * @len:	number of bytes to splice
 * @flags:	splice modifier flags
 *
518 519 520 521 522
 * Description:
 *    Will read pages from given file and fill them into a pipe. Can be
 *    used as long as the address_space operations for the source implements
 *    a readpage() hook.
 *
523
 */
524 525 526
ssize_t generic_file_splice_read(struct file *in, loff_t *ppos,
				 struct pipe_inode_info *pipe, size_t len,
				 unsigned int flags)
527
{
528
	loff_t isize, left;
529
	int ret;
530

531 532 533
	if (IS_DAX(in->f_mapping->host))
		return default_file_splice_read(in, ppos, pipe, len, flags);

534 535 536 537 538 539 540
	isize = i_size_read(in->f_mapping->host);
	if (unlikely(*ppos >= isize))
		return 0;

	left = isize - *ppos;
	if (unlikely(left < len))
		len = left;
541

542
	ret = __generic_file_splice_read(in, ppos, pipe, len, flags);
543
	if (ret > 0) {
544
		*ppos += ret;
545 546
		file_accessed(in);
	}
547 548 549

	return ret;
}
550 551
EXPORT_SYMBOL(generic_file_splice_read);

552 553 554 555 556 557 558 559
static const struct pipe_buf_operations default_pipe_buf_ops = {
	.can_merge = 0,
	.confirm = generic_pipe_buf_confirm,
	.release = generic_pipe_buf_release,
	.steal = generic_pipe_buf_steal,
	.get = generic_pipe_buf_get,
};

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
static int generic_pipe_buf_nosteal(struct pipe_inode_info *pipe,
				    struct pipe_buffer *buf)
{
	return 1;
}

/* Pipe buffer operations for a socket and similar. */
const struct pipe_buf_operations nosteal_pipe_buf_ops = {
	.can_merge = 0,
	.confirm = generic_pipe_buf_confirm,
	.release = generic_pipe_buf_release,
	.steal = generic_pipe_buf_nosteal,
	.get = generic_pipe_buf_get,
};
EXPORT_SYMBOL(nosteal_pipe_buf_ops);

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
static ssize_t kernel_readv(struct file *file, const struct iovec *vec,
			    unsigned long vlen, loff_t offset)
{
	mm_segment_t old_fs;
	loff_t pos = offset;
	ssize_t res;

	old_fs = get_fs();
	set_fs(get_ds());
	/* The cast to a user pointer is valid due to the set_fs() */
	res = vfs_readv(file, (const struct iovec __user *)vec, vlen, &pos);
	set_fs(old_fs);

	return res;
}

592
ssize_t kernel_write(struct file *file, const char *buf, size_t count,
593
			    loff_t pos)
594 595 596 597 598 599 600
{
	mm_segment_t old_fs;
	ssize_t res;

	old_fs = get_fs();
	set_fs(get_ds());
	/* The cast to a user pointer is valid due to the set_fs() */
601
	res = vfs_write(file, (__force const char __user *)buf, count, &pos);
602 603 604 605
	set_fs(old_fs);

	return res;
}
606
EXPORT_SYMBOL(kernel_write);
607

608 609 610 611 612 613 614
ssize_t default_file_splice_read(struct file *in, loff_t *ppos,
				 struct pipe_inode_info *pipe, size_t len,
				 unsigned int flags)
{
	unsigned int nr_pages;
	unsigned int nr_freed;
	size_t offset;
615 616 617
	struct page *pages[PIPE_DEF_BUFFERS];
	struct partial_page partial[PIPE_DEF_BUFFERS];
	struct iovec *vec, __vec[PIPE_DEF_BUFFERS];
618 619 620 621 622 623 624
	ssize_t res;
	size_t this_len;
	int error;
	int i;
	struct splice_pipe_desc spd = {
		.pages = pages,
		.partial = partial,
625
		.nr_pages_max = PIPE_DEF_BUFFERS,
626 627 628 629 630
		.flags = flags,
		.ops = &default_pipe_buf_ops,
		.spd_release = spd_release_page,
	};

631 632 633 634 635
	if (splice_grow_spd(pipe, &spd))
		return -ENOMEM;

	res = -ENOMEM;
	vec = __vec;
636 637
	if (spd.nr_pages_max > PIPE_DEF_BUFFERS) {
		vec = kmalloc(spd.nr_pages_max * sizeof(struct iovec), GFP_KERNEL);
638 639 640 641
		if (!vec)
			goto shrink_ret;
	}

642 643 644
	offset = *ppos & ~PAGE_CACHE_MASK;
	nr_pages = (len + offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;

645
	for (i = 0; i < nr_pages && i < spd.nr_pages_max && len; i++) {
646 647
		struct page *page;

648
		page = alloc_page(GFP_USER);
649 650 651 652 653
		error = -ENOMEM;
		if (!page)
			goto err;

		this_len = min_t(size_t, len, PAGE_CACHE_SIZE - offset);
654
		vec[i].iov_base = (void __user *) page_address(page);
655
		vec[i].iov_len = this_len;
656
		spd.pages[i] = page;
657 658 659 660 661 662
		spd.nr_pages++;
		len -= this_len;
		offset = 0;
	}

	res = kernel_readv(in, vec, spd.nr_pages, *ppos);
663 664
	if (res < 0) {
		error = res;
665
		goto err;
666
	}
667 668 669 670 671 672 673 674

	error = 0;
	if (!res)
		goto err;

	nr_freed = 0;
	for (i = 0; i < spd.nr_pages; i++) {
		this_len = min_t(size_t, vec[i].iov_len, res);
675 676
		spd.partial[i].offset = 0;
		spd.partial[i].len = this_len;
677
		if (!this_len) {
678 679
			__free_page(spd.pages[i]);
			spd.pages[i] = NULL;
680 681 682 683 684 685 686 687 688 689
			nr_freed++;
		}
		res -= this_len;
	}
	spd.nr_pages -= nr_freed;

	res = splice_to_pipe(pipe, &spd);
	if (res > 0)
		*ppos += res;

690 691 692
shrink_ret:
	if (vec != __vec)
		kfree(vec);
693
	splice_shrink_spd(&spd);
694 695 696
	return res;

err:
697
	for (i = 0; i < spd.nr_pages; i++)
698
		__free_page(spd.pages[i]);
699

700 701
	res = error;
	goto shrink_ret;
702 703 704
}
EXPORT_SYMBOL(default_file_splice_read);

705
/*
706
 * Send 'sd->len' bytes to socket from 'sd->file' at position 'sd->pos'
707
 * using sendpage(). Return the number of bytes sent.
708
 */
709
static int pipe_to_sendpage(struct pipe_inode_info *pipe,
710 711
			    struct pipe_buffer *buf, struct splice_desc *sd)
{
712
	struct file *file = sd->u.file;
713
	loff_t pos = sd->pos;
714
	int more;
715

Al Viro's avatar
Al Viro committed
716
	if (!likely(file->f_op->sendpage))
717 718
		return -EINVAL;

719
	more = (sd->flags & SPLICE_F_MORE) ? MSG_MORE : 0;
720 721

	if (sd->len < sd->total_len && pipe->nrbufs > 1)
722
		more |= MSG_SENDPAGE_NOTLAST;
723

724 725
	return file->f_op->sendpage(file, buf->page, buf->offset,
				    sd->len, &pos, more);
726 727
}

728 729 730 731 732 733 734 735
static void wakeup_pipe_writers(struct pipe_inode_info *pipe)
{
	smp_mb();
	if (waitqueue_active(&pipe->wait))
		wake_up_interruptible(&pipe->wait);
	kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}

736
/**
737
 * splice_from_pipe_feed - feed available data from a pipe to a file
738 739 740 741 742
 * @pipe:	pipe to splice from
 * @sd:		information to @actor
 * @actor:	handler that splices the data
 *
 * Description:
743 744 745 746 747 748 749
 *    This function loops over the pipe and calls @actor to do the
 *    actual moving of a single struct pipe_buffer to the desired
 *    destination.  It returns when there's no more buffers left in
 *    the pipe or if the requested number of bytes (@sd->total_len)
 *    have been copied.  It returns a positive number (one) if the
 *    pipe needs to be filled with more data, zero if the required
 *    number of bytes have been copied and -errno on error.
750
 *
751 752 753 754
 *    This, together with splice_from_pipe_{begin,end,next}, may be
 *    used to implement the functionality of __splice_from_pipe() when
 *    locking is required around copying the pipe buffers to the
 *    destination.
755
 */
756
static int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
757
			  splice_actor *actor)
758
{
759
	int ret;
760

761 762 763
	while (pipe->nrbufs) {
		struct pipe_buffer *buf = pipe->bufs + pipe->curbuf;
		const struct pipe_buf_operations *ops = buf->ops;
764

765 766 767
		sd->len = buf->len;
		if (sd->len > sd->total_len)
			sd->len = sd->total_len;
768

769 770
		ret = buf->ops->confirm(pipe, buf);
		if (unlikely(ret)) {
771 772 773 774
			if (ret == -ENODATA)
				ret = 0;
			return ret;
		}
775 776 777 778 779

		ret = actor(pipe, buf, sd);
		if (ret <= 0)
			return ret;

780 781 782 783 784 785 786 787 788 789 790
		buf->offset += ret;
		buf->len -= ret;

		sd->num_spliced += ret;
		sd->len -= ret;
		sd->pos += ret;
		sd->total_len -= ret;

		if (!buf->len) {
			buf->ops = NULL;
			ops->release(pipe, buf);
791
			pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
792
			pipe->nrbufs--;
Al Viro's avatar
Al Viro committed
793
			if (pipe->files)
794 795
				sd->need_wakeup = true;
		}
796

797 798 799
		if (!sd->total_len)
			return 0;
	}
800

801 802
	return 1;
}
803

804 805 806 807 808 809 810 811 812 813
/**
 * splice_from_pipe_next - wait for some data to splice from
 * @pipe:	pipe to splice from
 * @sd:		information about the splice operation
 *
 * Description:
 *    This function will wait for some data and return a positive
 *    value (one) if pipe buffers are available.  It will return zero
 *    or -errno if no more data needs to be spliced.
 */
814
static int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
815
{
816 817 818 819 820 821 822
	/*
	 * Check for signal early to make process killable when there are
	 * always buffers available
	 */
	if (signal_pending(current))
		return -ERESTARTSYS;

823 824 825
	while (!pipe->nrbufs) {
		if (!pipe->writers)
			return 0;
826

827 828
		if (!pipe->waiting_writers && sd->num_spliced)
			return 0;
Ingo Molnar's avatar
Ingo Molnar committed
829

830 831
		if (sd->flags & SPLICE_F_NONBLOCK)
			return -EAGAIN;
832

833 834
		if (signal_pending(current))
			return -ERESTARTSYS;
835

836 837 838
		if (sd->need_wakeup) {
			wakeup_pipe_writers(pipe);
			sd->need_wakeup = false;
839 840
		}

841 842
		pipe_wait(pipe);
	}
843

844 845
	return 1;
}
846

847 848
/**
 * splice_from_pipe_begin - start splicing from pipe
849
 * @sd:		information about the splice operation
850 851 852 853 854 855
 *
 * Description:
 *    This function should be called before a loop containing
 *    splice_from_pipe_next() and splice_from_pipe_feed() to
 *    initialize the necessary fields of @sd.
 */
856
static void splice_from_pipe_begin(struct splice_desc *sd)
857 858 859 860
{
	sd->num_spliced = 0;
	sd->need_wakeup = false;
}
861

862 863 864 865 866 867 868 869 870 871
/**
 * splice_from_pipe_end - finish splicing from pipe
 * @pipe:	pipe to splice from
 * @sd:		information about the splice operation
 *
 * Description:
 *    This function will wake up pipe writers if necessary.  It should
 *    be called after a loop containing splice_from_pipe_next() and
 *    splice_from_pipe_feed().
 */
872
static void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
873 874 875 876
{
	if (sd->need_wakeup)
		wakeup_pipe_writers(pipe);
}
877

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
/**
 * __splice_from_pipe - splice data from a pipe to given actor
 * @pipe:	pipe to splice from
 * @sd:		information to @actor
 * @actor:	handler that splices the data
 *
 * Description:
 *    This function does little more than loop over the pipe and call
 *    @actor to do the actual moving of a single struct pipe_buffer to
 *    the desired destination. See pipe_to_file, pipe_to_sendpage, or
 *    pipe_to_user.
 *
 */
ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
			   splice_actor *actor)
{
	int ret;
895

896 897
	splice_from_pipe_begin(sd);
	do {
898
		cond_resched();
899 900 901 902 903 904 905
		ret = splice_from_pipe_next(pipe, sd);
		if (ret > 0)
			ret = splice_from_pipe_feed(pipe, sd, actor);
	} while (ret > 0);
	splice_from_pipe_end(pipe, sd);

	return sd->num_spliced ? sd->num_spliced : ret;
906
}
Mark Fasheh's avatar
Mark Fasheh committed
907
EXPORT_SYMBOL(__splice_from_pipe);
908

909 910 911 912 913 914 915 916 917 918
/**
 * splice_from_pipe - splice data from a pipe to a file
 * @pipe:	pipe to splice from
 * @out:	file to splice to
 * @ppos:	position in @out
 * @len:	how many bytes to splice
 * @flags:	splice modifier flags
 * @actor:	handler that splices the data
 *
 * Description:
919
 *    See __splice_from_pipe. This function locks the pipe inode,
920 921 922
 *    otherwise it's identical to __splice_from_pipe().
 *
 */
923 924 925 926 927
ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
			 loff_t *ppos, size_t len, unsigned int flags,
			 splice_actor *actor)
{
	ssize_t ret;
Jens Axboe's avatar
Jens Axboe committed
928 929 930 931
	struct splice_desc sd = {
		.total_len = len,
		.flags = flags,
		.pos = *ppos,
932
		.u.file = out,
Jens Axboe's avatar
Jens Axboe committed
933
	};
934

935
	pipe_lock(pipe);
Jens Axboe's avatar
Jens Axboe committed
936
	ret = __splice_from_pipe(pipe, &sd, actor);
937
	pipe_unlock(pipe);
938 939 940 941

	return ret;
}

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
/**
 * iter_file_splice_write - splice data from a pipe to a file
 * @pipe:	pipe info
 * @out:	file to write to
 * @ppos:	position in @out
 * @len:	number of bytes to splice
 * @flags:	splice modifier flags
 *
 * Description:
 *    Will either move or copy pages (determined by @flags options) from
 *    the given pipe inode to the given file.
 *    This one is ->write_iter-based.
 *
 */
ssize_t
iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
			  loff_t *ppos, size_t len, unsigned int flags)
{
	struct splice_desc sd = {
		.total_len = len,
		.flags = flags,
		.pos = *ppos,
		.u.file = out,
	};
	int nbufs = pipe->buffers;
	struct bio_vec *array = kcalloc(nbufs, sizeof(struct bio_vec),
					GFP_KERNEL);
	ssize_t ret;

	if (unlikely(!array))
		return -ENOMEM;

	pipe_lock(pipe);

	splice_from_pipe_begin(&sd);
	while (sd.total_len) {
		struct iov_iter from;
		size_t left;
		int n, idx;

		ret = splice_from_pipe_next(pipe, &sd);
		if (ret <= 0)
			break;

		if (unlikely(nbufs < pipe->buffers)) {
			kfree(array);
			nbufs = pipe->buffers;
			array = kcalloc(nbufs, sizeof(struct bio_vec),
					GFP_KERNEL);
			if (!array) {
				ret = -ENOMEM;
				break;
			}
		}

		/* build the vector */
		left = sd.total_len;
		for (n = 0, idx = pipe->curbuf; left && n < pipe->nrbufs; n++, idx++) {
			struct pipe_buffer *buf = pipe->bufs + idx;
			size_t this_len = buf->len;

			if (this_len > left)
				this_len = left;

			if (idx == pipe->buffers - 1)
				idx = -1;

			ret = buf->ops->confirm(pipe, buf);
			if (unlikely(ret)) {
				if (ret == -ENODATA)
					ret = 0;
				goto done;
			}

			array[n].bv_page = buf->page;
			array[n].bv_len = this_len;
			array[n].bv_offset = buf->offset;
			left -= this_len;
		}

Al Viro's avatar
Al Viro committed
1022 1023
		iov_iter_bvec(&from, ITER_BVEC | WRITE, array, n,
			      sd.total_len - left);
1024
		ret = vfs_iter_write(out, &from, &sd.pos);
1025 1026 1027 1028 1029
		if (ret <= 0)
			break;

		sd.num_spliced += ret;
		sd.total_len -= ret;
1030
		*ppos = sd.pos;
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

		/* dismiss the fully eaten buffers, adjust the partial one */
		while (ret) {
			struct pipe_buffer *buf = pipe->bufs + pipe->curbuf;
			if (ret >= buf->len) {
				const struct pipe_buf_operations *ops = buf->ops;
				ret -= buf->len;
				buf->len = 0;
				buf->ops = NULL;
				ops->release(pipe, buf);
				pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
				pipe->nrbufs--;
				if (pipe->files)
					sd.need_wakeup = true;
			} else {
				buf->offset += ret;
				buf->len -= ret;
				ret = 0;
			}
		}
	}
done:
	kfree(array);
	splice_from_pipe_end(pipe, &sd);

	pipe_unlock(pipe);

	if (sd.num_spliced)
		ret = sd.num_spliced;

	return ret;
}

EXPORT_SYMBOL(iter_file_splice_write);

1066 1067
static int write_pipe_buf(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
			  struct splice_desc *sd)
1068
{
1069 1070
	int ret;
	void *data;
1071
	loff_t tmp = sd->pos;
1072

Al Viro's avatar
Al Viro committed
1073
	data = kmap(buf->page);
1074
	ret = __kernel_write(sd->u.file, data + buf->offset, sd->len, &tmp);
Al Viro's avatar
Al Viro committed
1075
	kunmap(buf->page);
1076 1077

	return ret;
1078 1079 1080 1081 1082 1083
}

static ssize_t default_file_splice_write(struct pipe_inode_info *pipe,
					 struct file *out, loff_t *ppos,
					 size_t len, unsigned int flags)
{
1084
	ssize_t ret;
1085

1086 1087 1088
	ret = splice_from_pipe(pipe, out, ppos, len, flags, write_pipe_buf);
	if (ret > 0)
		*ppos += ret;
1089

1090
	return ret;
1091 1092
}

1093 1094
/**
 * generic_splice_sendpage - splice data from a pipe to a socket
1095
 * @pipe:	pipe to splice from
1096
 * @out:	socket to write to
1097
 * @ppos:	position in @out
1098 1099 1100
 * @len:	number of bytes to splice
 * @flags:	splice modifier flags
 *
1101 1102 1103
 * Description:
 *    Will send @len bytes from the pipe to a network socket. No data copying
 *    is involved.
1104 1105
 *
 */
1106
ssize_t generic_splice_sendpage(struct pipe_inode_info *pipe, struct file *out,
1107
				loff_t *ppos, size_t len, unsigned int flags)
1108
{
1109
	return splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_sendpage);
1110 1111
}

1112
EXPORT_SYMBOL(generic_splice_sendpage);
Jeff Garzik's avatar
Jeff Garzik committed
1113

1114 1115 1116
/*
 * Attempt to initiate a splice from pipe to file.
 */
1117
static long do_splice_from(struct pipe_inode_info *pipe, struct file *out,
1118
			   loff_t *ppos, size_t len, unsigned int flags)
1119
{
1120 1121
	ssize_t (*splice_write)(struct pipe_inode_info *, struct file *,
				loff_t *, size_t, unsigned int);
1122

Al Viro's avatar
Al Viro committed
1123
	if (out->f_op->splice_write)
1124 1125
		splice_write = out->f_op->splice_write;
	else
1126 1127
		splice_write = default_file_splice_write;

1128
	return splice_write(pipe, out, ppos, len, flags);
1129 1130
}

1131 1132 1133
/*
 * Attempt to initiate a splice from a file to a pipe.
 */
1134 1135 1136
static long do_splice_to(struct file *in, loff_t *ppos,
			 struct pipe_inode_info *pipe, size_t len,
			 unsigned int flags)
1137
{
1138 1139
	ssize_t (*splice_read)(struct file *, loff_t *,
			       struct pipe_inode_info *, size_t, unsigned int);
1140 1141
	int ret;

1142
	if (unlikely(!(in->f_mode & FMODE_READ)))
1143 1144
		return -EBADF;

1145
	ret = rw_verify_area(READ, in, ppos, len);
1146 1147 1148
	if (unlikely(ret < 0))
		return ret;

Al Viro's avatar
Al Viro committed
1149
	if (in->f_op->splice_read)
1150 1151
		splice_read = in->f_op->splice_read;
	else
1152 1153 1154
		splice_read = default_file_splice_read;

	return splice_read(in, ppos, pipe, len, flags);
1155 1156
}

1157 1158 1159 1160 1161 1162 1163 1164 1165
/**
 * splice_direct_to_actor - splices data directly between two non-pipes
 * @in:		file to splice from
 * @sd:		actor information on where to splice to
 * @actor:	handles the data splicing
 *
 * Description:
 *    This is a special case helper to splice directly between two
 *    points, without requiring an explicit pipe. Internally an allocated