splice.c 46.3 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

34 35 36 37 38 39
/*
 * 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.
 */
40
static int page_cache_pipe_buf_steal(struct pipe_inode_info *pipe,
41 42 43
				     struct pipe_buffer *buf)
{
	struct page *page = buf->page;
44
	struct address_space *mapping;
45

46 47
	lock_page(page);

48 49 50
	mapping = page_mapping(page);
	if (mapping) {
		WARN_ON(!PageUptodate(page));
51

52 53 54 55 56 57 58 59 60
		/*
		 * 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);
61

62 63
		if (page_has_private(page) &&
		    !try_to_release_page(page, GFP_KERNEL))
64
			goto out_unlock;
65

66 67 68 69 70 71 72 73
		/*
		 * 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;
		}
74
	}
75

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

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

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

	if (!PageUptodate(page)) {
103 104 105 106
		lock_page(page);

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

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

		/*
123
		 * Page is ok afterall, we are done.
124
		 */
125 126 127
		unlock_page(page);
	}

128
	return 0;
129 130
error:
	unlock_page(page);
131
	return err;
132 133
}

134
const struct pipe_buf_operations page_cache_pipe_buf_ops = {
135
	.can_merge = 0,
136 137
	.map = generic_pipe_buf_map,
	.unmap = generic_pipe_buf_unmap,
138
	.confirm = page_cache_pipe_buf_confirm,
139
	.release = page_cache_pipe_buf_release,
140
	.steal = page_cache_pipe_buf_steal,
141
	.get = generic_pipe_buf_get,
142 143
};

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

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

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

164 165 166 167 168 169 170 171
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);
}

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

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

193
	pipe_lock(pipe);
194 195

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

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

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

215
			pipe->nrbufs++;
216 217 218
			page_nr++;
			ret += buf->len;

219 220
			if (pipe->inode)
				do_wakeup = 1;
221

222
			if (!--spd->nr_pages)
223
				break;
224
			if (pipe->nrbufs < pipe->buffers)
225 226 227 228 229
				continue;

			break;
		}

230
		if (spd->flags & SPLICE_F_NONBLOCK) {
231 232 233 234 235
			if (!ret)
				ret = -EAGAIN;
			break;
		}

236 237 238 239 240 241 242
		if (signal_pending(current)) {
			if (!ret)
				ret = -ERESTARTSYS;
			break;
		}

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

250 251 252
		pipe->waiting_writers++;
		pipe_wait(pipe);
		pipe->waiting_writers--;
253 254
	}

255
	pipe_unlock(pipe);
256

257 258
	if (do_wakeup)
		wakeup_pipe_readers(pipe);
259

260
	while (page_nr < spd_pages)
261
		spd->spd_release(spd, page_nr++);
262 263 264 265

	return ret;
}

266
void spd_release_page(struct splice_pipe_desc *spd, unsigned int i)
267 268 269 270
{
	page_cache_release(spd->pages[i]);
}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
/*
 * Check if we need to grow the arrays holding pages and partial page
 * descriptions.
 */
int splice_grow_spd(struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
{
	if (pipe->buffers <= PIPE_DEF_BUFFERS)
		return 0;

	spd->pages = kmalloc(pipe->buffers * sizeof(struct page *), GFP_KERNEL);
	spd->partial = kmalloc(pipe->buffers * sizeof(struct partial_page), GFP_KERNEL);

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

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

void splice_shrink_spd(struct pipe_inode_info *pipe,
		       struct splice_pipe_desc *spd)
{
	if (pipe->buffers <= PIPE_DEF_BUFFERS)
		return;

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

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

322 323 324
	if (splice_grow_spd(pipe, &spd))
		return -ENOMEM;

325
	index = *ppos >> PAGE_CACHE_SHIFT;
326
	loff = *ppos & ~PAGE_CACHE_MASK;
327
	req_pages = (len + loff + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
328
	nr_pages = min(req_pages, pipe->buffers);
329

330 331 332
	/*
	 * Lookup the (hopefully) full range of pages we need.
	 */
333
	spd.nr_pages = find_get_pages_contig(mapping, index, nr_pages, spd.pages);
334
	index += spd.nr_pages;
335

336 337
	/*
	 * If find_get_pages_contig() returned fewer pages than we needed,
338
	 * readahead/allocate the rest and fill in the holes.
339
	 */
340
	if (spd.nr_pages < nr_pages)
341 342
		page_cache_sync_readahead(mapping, &in->f_ra, in,
				index, req_pages - spd.nr_pages);
343

344
	error = 0;
345
	while (spd.nr_pages < nr_pages) {
346
		/*
347 348
		 * Page could be there, find_get_pages_contig() breaks on
		 * the first hole.
349
		 */
350 351 352
		page = find_get_page(mapping, index);
		if (!page) {
			/*
353
			 * page didn't exist, allocate one.
354 355 356 357 358 359
			 */
			page = page_cache_alloc_cold(mapping);
			if (!page)
				break;

			error = add_to_page_cache_lru(page, mapping, index,
360
						GFP_KERNEL);
361 362
			if (unlikely(error)) {
				page_cache_release(page);
363 364
				if (error == -EEXIST)
					continue;
365 366
				break;
			}
367 368 369 370 371
			/*
			 * add_to_page_cache() locks the page, unlock it
			 * to avoid convoluting the logic below even more.
			 */
			unlock_page(page);
372 373
		}

374
		spd.pages[spd.nr_pages++] = page;
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
		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);
395
		page = spd.pages[page_nr];
396

397
		if (PageReadahead(page))
398
			page_cache_async_readahead(mapping, &in->f_ra, in,
399
					page, index, req_pages - page_nr);
400

401 402 403 404
		/*
		 * If the page isn't uptodate, we may need to start io on it
		 */
		if (!PageUptodate(page)) {
405
			lock_page(page);
406 407

			/*
408 409 410 411
			 * 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.
412 413 414
			 */
			if (!page->mapping) {
				unlock_page(page);
415 416 417 418 419 420 421
				page = find_or_create_page(mapping, index,
						mapping_gfp_mask(mapping));

				if (!page) {
					error = -ENOMEM;
					break;
				}
422 423
				page_cache_release(spd.pages[page_nr]);
				spd.pages[page_nr] = page;
424 425 426 427 428 429 430 431
			}
			/*
			 * page was already under io and is now done, great
			 */
			if (PageUptodate(page)) {
				unlock_page(page);
				goto fill_it;
			}
432

433 434 435 436
			/*
			 * need to read in the page
			 */
			error = mapping->a_ops->readpage(in, page);
437
			if (unlikely(error)) {
438 439 440 441 442 443
				/*
				 * 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.
				 */
444
				if (error == AOP_TRUNCATED_PAGE)
445 446
					error = 0;

447 448
				break;
			}
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
		}
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;
465 466

			/*
467
			 * max good bytes in this page
468
			 */
469 470
			plen = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
			if (plen <= loff)
471 472 473
				break;

			/*
474
			 * force quit after adding this page
475
			 */
476 477
			this_len = min(this_len, plen - loff);
			len = this_len;
478
		}
479

480 481
		spd.partial[page_nr].offset = loff;
		spd.partial[page_nr].len = this_len;
482
		len -= this_len;
483
		loff = 0;
484 485
		spd.nr_pages++;
		index++;
486 487
	}

488
	/*
489
	 * Release any pages at the end, if we quit early. 'page_nr' is how far
490 491 492
	 * we got, 'nr_pages' is how many pages are in the map.
	 */
	while (page_nr < nr_pages)
493
		page_cache_release(spd.pages[page_nr++]);
494
	in->f_ra.prev_pos = (loff_t)index << PAGE_CACHE_SHIFT;
495

496
	if (spd.nr_pages)
497
		error = splice_to_pipe(pipe, &spd);
498

499
	splice_shrink_spd(pipe, &spd);
500
	return error;
501 502
}

503 504 505
/**
 * generic_file_splice_read - splice data from file to a pipe
 * @in:		file to splice from
506
 * @ppos:	position in @in
507 508 509 510
 * @pipe:	pipe to splice to
 * @len:	number of bytes to splice
 * @flags:	splice modifier flags
 *
511 512 513 514 515
 * 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.
 *
516
 */
517 518 519
ssize_t generic_file_splice_read(struct file *in, loff_t *ppos,
				 struct pipe_inode_info *pipe, size_t len,
				 unsigned int flags)
520
{
521
	loff_t isize, left;
522
	int ret;
523 524 525 526 527 528 529 530

	isize = i_size_read(in->f_mapping->host);
	if (unlikely(*ppos >= isize))
		return 0;

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

532
	ret = __generic_file_splice_read(in, ppos, pipe, len, flags);
533
	if (ret > 0) {
534
		*ppos += ret;
535 536
		file_accessed(in);
	}
537 538 539

	return ret;
}
540 541
EXPORT_SYMBOL(generic_file_splice_read);

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
static const struct pipe_buf_operations default_pipe_buf_ops = {
	.can_merge = 0,
	.map = generic_pipe_buf_map,
	.unmap = generic_pipe_buf_unmap,
	.confirm = generic_pipe_buf_confirm,
	.release = generic_pipe_buf_release,
	.steal = generic_pipe_buf_steal,
	.get = generic_pipe_buf_get,
};

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;
}

568 569
static ssize_t kernel_write(struct file *file, const char *buf, size_t count,
			    loff_t pos)
570 571 572 573 574 575 576
{
	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() */
577
	res = vfs_write(file, (const char __user *)buf, count, &pos);
578 579 580 581 582
	set_fs(old_fs);

	return res;
}

583 584 585 586 587 588 589
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;
590 591 592
	struct page *pages[PIPE_DEF_BUFFERS];
	struct partial_page partial[PIPE_DEF_BUFFERS];
	struct iovec *vec, __vec[PIPE_DEF_BUFFERS];
593 594 595 596 597 598 599 600 601 602 603 604
	ssize_t res;
	size_t this_len;
	int error;
	int i;
	struct splice_pipe_desc spd = {
		.pages = pages,
		.partial = partial,
		.flags = flags,
		.ops = &default_pipe_buf_ops,
		.spd_release = spd_release_page,
	};

605 606 607 608 609 610 611 612 613 614 615
	if (splice_grow_spd(pipe, &spd))
		return -ENOMEM;

	res = -ENOMEM;
	vec = __vec;
	if (pipe->buffers > PIPE_DEF_BUFFERS) {
		vec = kmalloc(pipe->buffers * sizeof(struct iovec), GFP_KERNEL);
		if (!vec)
			goto shrink_ret;
	}

616 617 618
	offset = *ppos & ~PAGE_CACHE_MASK;
	nr_pages = (len + offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;

619
	for (i = 0; i < nr_pages && i < pipe->buffers && len; i++) {
620 621
		struct page *page;

622
		page = alloc_page(GFP_USER);
623 624 625 626 627
		error = -ENOMEM;
		if (!page)
			goto err;

		this_len = min_t(size_t, len, PAGE_CACHE_SIZE - offset);
628
		vec[i].iov_base = (void __user *) page_address(page);
629
		vec[i].iov_len = this_len;
630
		spd.pages[i] = page;
631 632 633 634 635 636
		spd.nr_pages++;
		len -= this_len;
		offset = 0;
	}

	res = kernel_readv(in, vec, spd.nr_pages, *ppos);
Andrew Morton's avatar
Andrew Morton committed
637 638
	if (res < 0) {
		error = res;
639
		goto err;
Andrew Morton's avatar
Andrew Morton committed
640
	}
641 642 643 644 645 646 647 648

	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);
649 650
		spd.partial[i].offset = 0;
		spd.partial[i].len = this_len;
651
		if (!this_len) {
652 653
			__free_page(spd.pages[i]);
			spd.pages[i] = NULL;
654 655 656 657 658 659 660 661 662 663
			nr_freed++;
		}
		res -= this_len;
	}
	spd.nr_pages -= nr_freed;

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

664 665 666 667
shrink_ret:
	if (vec != __vec)
		kfree(vec);
	splice_shrink_spd(pipe, &spd);
668 669 670
	return res;

err:
671
	for (i = 0; i < spd.nr_pages; i++)
672
		__free_page(spd.pages[i]);
673

674 675
	res = error;
	goto shrink_ret;
676 677 678
}
EXPORT_SYMBOL(default_file_splice_read);

679
/*
680
 * Send 'sd->len' bytes to socket from 'sd->file' at position 'sd->pos'
681
 * using sendpage(). Return the number of bytes sent.
682
 */
683
static int pipe_to_sendpage(struct pipe_inode_info *pipe,
684 685
			    struct pipe_buffer *buf, struct splice_desc *sd)
{
686
	struct file *file = sd->u.file;
687
	loff_t pos = sd->pos;
688
	int more;
689

690 691 692 693 694 695
	if (!likely(file->f_op && file->f_op->sendpage))
		return -EINVAL;

	more = (sd->flags & SPLICE_F_MORE) || sd->len < sd->total_len;
	return file->f_op->sendpage(file, buf->page, buf->offset,
				    sd->len, &pos, more);
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
}

/*
 * This is a little more tricky than the file -> pipe splicing. There are
 * basically three cases:
 *
 *	- Destination page already exists in the address space and there
 *	  are users of it. For that case we have no other option that
 *	  copying the data. Tough luck.
 *	- Destination page already exists in the address space, but there
 *	  are no users of it. Make sure it's uptodate, then drop it. Fall
 *	  through to last case.
 *	- Destination page does not exist, we can add the pipe page to
 *	  the page cache and avoid the copy.
 *
711 712 713 714 715 716
 * If asked to move pages to the output file (SPLICE_F_MOVE is set in
 * sd->flags), we attempt to migrate pages from the pipe to the output
 * file address space page cache. This is possible if no one else has
 * the pipe page referenced outside of the pipe and page cache. If
 * SPLICE_F_MOVE isn't set, or we cannot move the page, we simply create
 * a new page in the output file page cache and fill/dirty that.
717
 */
718 719
int pipe_to_file(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
		 struct splice_desc *sd)
720
{
721
	struct file *file = sd->u.file;
722
	struct address_space *mapping = file->f_mapping;
723
	unsigned int offset, this_len;
724
	struct page *page;
725
	void *fsdata;
726
	int ret;
727 728 729

	offset = sd->pos & ~PAGE_CACHE_MASK;

730 731 732 733
	this_len = sd->len;
	if (this_len + offset > PAGE_CACHE_SIZE)
		this_len = PAGE_CACHE_SIZE - offset;

734 735 736 737
	ret = pagecache_write_begin(file, mapping, sd->pos, this_len,
				AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
	if (unlikely(ret))
		goto out;
738

739
	if (buf->page != page) {
740 741 742
		/*
		 * Careful, ->map() uses KM_USER0!
		 */
743
		char *src = buf->ops->map(pipe, buf, 1);
744
		char *dst = kmap_atomic(page, KM_USER1);
745

746
		memcpy(dst + offset, src + buf->offset, this_len);
747
		flush_dcache_page(page);
748
		kunmap_atomic(dst, KM_USER1);
749
		buf->ops->unmap(pipe, buf, src);
750
	}
751 752
	ret = pagecache_write_end(file, mapping, sd->pos, this_len, this_len,
				page, fsdata);
753 754 755
out:
	return ret;
}
756
EXPORT_SYMBOL(pipe_to_file);
757

758 759 760 761 762 763 764 765
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);
}

766
/**
767
 * splice_from_pipe_feed - feed available data from a pipe to a file
768 769 770 771 772
 * @pipe:	pipe to splice from
 * @sd:		information to @actor
 * @actor:	handler that splices the data
 *
 * Description:
773 774 775 776 777 778 779
 *    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.
780
 *
781 782 783 784
 *    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.
785
 */
786 787
int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
			  splice_actor *actor)
788
{
789
	int ret;
790

791 792 793
	while (pipe->nrbufs) {
		struct pipe_buffer *buf = pipe->bufs + pipe->curbuf;
		const struct pipe_buf_operations *ops = buf->ops;
794

795 796 797
		sd->len = buf->len;
		if (sd->len > sd->total_len)
			sd->len = sd->total_len;
798

799 800
		ret = buf->ops->confirm(pipe, buf);
		if (unlikely(ret)) {
801 802 803 804
			if (ret == -ENODATA)
				ret = 0;
			return ret;
		}
805 806 807 808 809

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

810 811 812 813 814 815 816 817 818 819 820
		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);
821
			pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
822 823 824 825
			pipe->nrbufs--;
			if (pipe->inode)
				sd->need_wakeup = true;
		}
826

827 828 829
		if (!sd->total_len)
			return 0;
	}
830

831 832 833
	return 1;
}
EXPORT_SYMBOL(splice_from_pipe_feed);
834

835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
/**
 * 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.
 */
int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
{
	while (!pipe->nrbufs) {
		if (!pipe->writers)
			return 0;
850

851 852
		if (!pipe->waiting_writers && sd->num_spliced)
			return 0;
Ingo Molnar's avatar
Ingo Molnar committed
853

854 855
		if (sd->flags & SPLICE_F_NONBLOCK)
			return -EAGAIN;
856

857 858
		if (signal_pending(current))
			return -ERESTARTSYS;
859

860 861 862
		if (sd->need_wakeup) {
			wakeup_pipe_writers(pipe);
			sd->need_wakeup = false;
863 864
		}

865 866
		pipe_wait(pipe);
	}
867

868 869 870
	return 1;
}
EXPORT_SYMBOL(splice_from_pipe_next);
871

872 873
/**
 * splice_from_pipe_begin - start splicing from pipe
874
 * @sd:		information about the splice operation
875 876 877 878 879 880 881 882 883 884 885 886
 *
 * 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.
 */
void splice_from_pipe_begin(struct splice_desc *sd)
{
	sd->num_spliced = 0;
	sd->need_wakeup = false;
}
EXPORT_SYMBOL(splice_from_pipe_begin);
887

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
/**
 * 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().
 */
void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
{
	if (sd->need_wakeup)
		wakeup_pipe_writers(pipe);
}
EXPORT_SYMBOL(splice_from_pipe_end);
904

905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
/**
 * __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;
922

923 924 925 926 927 928 929 930 931
	splice_from_pipe_begin(sd);
	do {
		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;
932
}
Mark Fasheh's avatar
Mark Fasheh committed
933
EXPORT_SYMBOL(__splice_from_pipe);
934

935 936 937 938 939 940 941 942 943 944
/**
 * 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:
945
 *    See __splice_from_pipe. This function locks the pipe inode,
946 947 948
 *    otherwise it's identical to __splice_from_pipe().
 *
 */
949 950 951 952 953
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
954 955 956 957
	struct splice_desc sd = {
		.total_len = len,
		.flags = flags,
		.pos = *ppos,
958
		.u.file = out,
Jens Axboe's avatar
Jens Axboe committed
959
	};
960

961
	pipe_lock(pipe);
Jens Axboe's avatar
Jens Axboe committed
962
	ret = __splice_from_pipe(pipe, &sd, actor);
963
	pipe_unlock(pipe);
964 965 966 967

	return ret;
}

968 969
/**
 * generic_file_splice_write - splice data from a pipe to a file
970
 * @pipe:	pipe info
971
 * @out:	file to write to
972
 * @ppos:	position in @out
973 974 975
 * @len:	number of bytes to splice
 * @flags:	splice modifier flags
 *
976 977 978
 * Description:
 *    Will either move or copy pages (determined by @flags options) from
 *    the given pipe inode to the given file.
979 980
 *
 */
981 982
ssize_t
generic_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
983
			  loff_t *ppos, size_t len, unsigned int flags)
984
{
985
	struct address_space *mapping = out->f_mapping;
986
	struct inode *inode = mapping->host;
987 988 989 990 991 992
	struct splice_desc sd = {
		.total_len = len,
		.flags = flags,
		.pos = *ppos,
		.u.file = out,
	};
993 994
	ssize_t ret;

995
	pipe_lock(pipe);
996 997 998 999 1000 1001 1002 1003 1004

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

		mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
		ret = file_remove_suid(out);
1005 1006
		if (!ret) {
			file_update_time(out);
1007
			ret = splice_from_pipe_feed(pipe, &sd, pipe_to_file);
1008
		}
1009 1010 1011 1012
		mutex_unlock(&inode->i_mutex);
	} while (ret > 0);
	splice_from_pipe_end(pipe, &sd);

1013
	pipe_unlock(pipe);
1014 1015 1016 1017

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

Jens Axboe's avatar
Jens Axboe committed
1018
	if (ret > 0) {
1019
		unsigned long nr_pages;
1020
		int err;
1021 1022

		nr_pages = (ret + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
Jens Axboe's avatar
Jens Axboe committed
1023

1024 1025 1026 1027 1028
		err = generic_write_sync(out, *ppos, ret);
		if (err)
			ret = err;
		else
			*ppos += ret;
1029
		balance_dirty_pages_ratelimited_nr(mapping, nr_pages);
1030 1031 1032
	}

	return ret;
1033 1034
}

Jens Axboe's avatar