linux/fs/splice.c
<<
>>
Prefs
   1/*
   2 * "splice": joining two ropes together by interweaving their strands.
   3 *
   4 * This is the "extended pipe" functionality, where a pipe is used as
   5 * an arbitrary in-memory buffer. Think of a pipe as a small kernel
   6 * buffer that you can use to transfer data from one end to the other.
   7 *
   8 * The traditional unix read/write is extended with a "splice()" operation
   9 * that transfers data buffers to or from a pipe buffer.
  10 *
  11 * Named by Larry McVoy, original implementation from Linus, extended by
  12 * Jens to support splicing to files, network, direct splicing, etc and
  13 * fixing lots of bugs.
  14 *
  15 * Copyright (C) 2005-2006 Jens Axboe <axboe@kernel.dk>
  16 * Copyright (C) 2005-2006 Linus Torvalds <torvalds@osdl.org>
  17 * Copyright (C) 2006 Ingo Molnar <mingo@elte.hu>
  18 *
  19 */
  20#include <linux/fs.h>
  21#include <linux/file.h>
  22#include <linux/pagemap.h>
  23#include <linux/splice.h>
  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 * Attempt to steal a page from a pipe buffer. This should perhaps go into
  39 * a vm helper function, it's already simplified quite a bit by the
  40 * addition of remove_mapping(). If success is returned, the caller may
  41 * attempt to reuse this page for another destination.
  42 */
  43static int page_cache_pipe_buf_steal(struct pipe_inode_info *pipe,
  44                                     struct pipe_buffer *buf)
  45{
  46        struct page *page = buf->page;
  47        struct address_space *mapping;
  48
  49        lock_page(page);
  50
  51        mapping = page_mapping(page);
  52        if (mapping) {
  53                WARN_ON(!PageUptodate(page));
  54
  55                /*
  56                 * At least for ext2 with nobh option, we need to wait on
  57                 * writeback completing on this page, since we'll remove it
  58                 * from the pagecache.  Otherwise truncate wont wait on the
  59                 * page, allowing the disk blocks to be reused by someone else
  60                 * before we actually wrote our data to them. fs corruption
  61                 * ensues.
  62                 */
  63                wait_on_page_writeback(page);
  64
  65                if (page_has_private(page) &&
  66                    !try_to_release_page(page, GFP_KERNEL))
  67                        goto out_unlock;
  68
  69                /*
  70                 * If we succeeded in removing the mapping, set LRU flag
  71                 * and return good.
  72                 */
  73                if (remove_mapping(mapping, page)) {
  74                        buf->flags |= PIPE_BUF_FLAG_LRU;
  75                        return 0;
  76                }
  77        }
  78
  79        /*
  80         * Raced with truncate or failed to remove page from current
  81         * address space, unlock and return failure.
  82         */
  83out_unlock:
  84        unlock_page(page);
  85        return 1;
  86}
  87
  88static void page_cache_pipe_buf_release(struct pipe_inode_info *pipe,
  89                                        struct pipe_buffer *buf)
  90{
  91        page_cache_release(buf->page);
  92        buf->flags &= ~PIPE_BUF_FLAG_LRU;
  93}
  94
  95/*
  96 * Check whether the contents of buf is OK to access. Since the content
  97 * is a page cache page, IO may be in flight.
  98 */
  99static int page_cache_pipe_buf_confirm(struct pipe_inode_info *pipe,
 100                                       struct pipe_buffer *buf)
 101{
 102        struct page *page = buf->page;
 103        int err;
 104
 105        if (!PageUptodate(page)) {
 106                lock_page(page);
 107
 108                /*
 109                 * Page got truncated/unhashed. This will cause a 0-byte
 110                 * splice, if this is the first page.
 111                 */
 112                if (!page->mapping) {
 113                        err = -ENODATA;
 114                        goto error;
 115                }
 116
 117                /*
 118                 * Uh oh, read-error from disk.
 119                 */
 120                if (!PageUptodate(page)) {
 121                        err = -EIO;
 122                        goto error;
 123                }
 124
 125                /*
 126                 * Page is ok afterall, we are done.
 127                 */
 128                unlock_page(page);
 129        }
 130
 131        return 0;
 132error:
 133        unlock_page(page);
 134        return err;
 135}
 136
 137const struct pipe_buf_operations page_cache_pipe_buf_ops = {
 138        .can_merge = 0,
 139        .map = generic_pipe_buf_map,
 140        .unmap = generic_pipe_buf_unmap,
 141        .confirm = page_cache_pipe_buf_confirm,
 142        .release = page_cache_pipe_buf_release,
 143        .steal = page_cache_pipe_buf_steal,
 144        .get = generic_pipe_buf_get,
 145};
 146
 147static int user_page_pipe_buf_steal(struct pipe_inode_info *pipe,
 148                                    struct pipe_buffer *buf)
 149{
 150        if (!(buf->flags & PIPE_BUF_FLAG_GIFT))
 151                return 1;
 152
 153        buf->flags |= PIPE_BUF_FLAG_LRU;
 154        return generic_pipe_buf_steal(pipe, buf);
 155}
 156
 157static const struct pipe_buf_operations user_page_pipe_buf_ops = {
 158        .can_merge = 0,
 159        .map = generic_pipe_buf_map,
 160        .unmap = generic_pipe_buf_unmap,
 161        .confirm = generic_pipe_buf_confirm,
 162        .release = page_cache_pipe_buf_release,
 163        .steal = user_page_pipe_buf_steal,
 164        .get = generic_pipe_buf_get,
 165};
 166
 167static void wakeup_pipe_readers(struct pipe_inode_info *pipe)
 168{
 169        smp_mb();
 170        if (waitqueue_active(&pipe->wait))
 171                wake_up_interruptible(&pipe->wait);
 172        kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
 173}
 174
 175/**
 176 * splice_to_pipe - fill passed data into a pipe
 177 * @pipe:       pipe to fill
 178 * @spd:        data to fill
 179 *
 180 * Description:
 181 *    @spd contains a map of pages and len/offset tuples, along with
 182 *    the struct pipe_buf_operations associated with these pages. This
 183 *    function will link that data to the pipe.
 184 *
 185 */
 186ssize_t splice_to_pipe(struct pipe_inode_info *pipe,
 187                       struct splice_pipe_desc *spd)
 188{
 189        unsigned int spd_pages = spd->nr_pages;
 190        int ret, do_wakeup, page_nr;
 191
 192        ret = 0;
 193        do_wakeup = 0;
 194        page_nr = 0;
 195
 196        pipe_lock(pipe);
 197
 198        for (;;) {
 199                if (!pipe->readers) {
 200                        send_sig(SIGPIPE, current, 0);
 201                        if (!ret)
 202                                ret = -EPIPE;
 203                        break;
 204                }
 205
 206                if (pipe->nrbufs < pipe->buffers) {
 207                        int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
 208                        struct pipe_buffer *buf = pipe->bufs + newbuf;
 209
 210                        buf->page = spd->pages[page_nr];
 211                        buf->offset = spd->partial[page_nr].offset;
 212                        buf->len = spd->partial[page_nr].len;
 213                        buf->private = spd->partial[page_nr].private;
 214                        buf->ops = spd->ops;
 215                        if (spd->flags & SPLICE_F_GIFT)
 216                                buf->flags |= PIPE_BUF_FLAG_GIFT;
 217
 218                        pipe->nrbufs++;
 219                        page_nr++;
 220                        ret += buf->len;
 221
 222                        if (pipe->files)
 223                                do_wakeup = 1;
 224
 225                        if (!--spd->nr_pages)
 226                                break;
 227                        if (pipe->nrbufs < pipe->buffers)
 228                                continue;
 229
 230                        break;
 231                }
 232
 233                if (spd->flags & SPLICE_F_NONBLOCK) {
 234                        if (!ret)
 235                                ret = -EAGAIN;
 236                        break;
 237                }
 238
 239                if (signal_pending(current)) {
 240                        if (!ret)
 241                                ret = -ERESTARTSYS;
 242                        break;
 243                }
 244
 245                if (do_wakeup) {
 246                        smp_mb();
 247                        if (waitqueue_active(&pipe->wait))
 248                                wake_up_interruptible_sync(&pipe->wait);
 249                        kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
 250                        do_wakeup = 0;
 251                }
 252
 253                pipe->waiting_writers++;
 254                pipe_wait(pipe);
 255                pipe->waiting_writers--;
 256        }
 257
 258        pipe_unlock(pipe);
 259
 260        if (do_wakeup)
 261                wakeup_pipe_readers(pipe);
 262
 263        while (page_nr < spd_pages)
 264                spd->spd_release(spd, page_nr++);
 265
 266        return ret;
 267}
 268EXPORT_SYMBOL_GPL(splice_to_pipe);
 269
 270void spd_release_page(struct splice_pipe_desc *spd, unsigned int i)
 271{
 272        page_cache_release(spd->pages[i]);
 273}
 274
 275/*
 276 * Check if we need to grow the arrays holding pages and partial page
 277 * descriptions.
 278 */
 279int splice_grow_spd(const struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
 280{
 281        unsigned int buffers = ACCESS_ONCE(pipe->buffers);
 282
 283        spd->nr_pages_max = buffers;
 284        if (buffers <= PIPE_DEF_BUFFERS)
 285                return 0;
 286
 287        spd->pages = kmalloc(buffers * sizeof(struct page *), GFP_KERNEL);
 288        spd->partial = kmalloc(buffers * sizeof(struct partial_page), GFP_KERNEL);
 289
 290        if (spd->pages && spd->partial)
 291                return 0;
 292
 293        kfree(spd->pages);
 294        kfree(spd->partial);
 295        return -ENOMEM;
 296}
 297
 298void splice_shrink_spd(struct splice_pipe_desc *spd)
 299{
 300        if (spd->nr_pages_max <= PIPE_DEF_BUFFERS)
 301                return;
 302
 303        kfree(spd->pages);
 304        kfree(spd->partial);
 305}
 306
 307static int
 308__generic_file_splice_read(struct file *in, loff_t *ppos,
 309                           struct pipe_inode_info *pipe, size_t len,
 310                           unsigned int flags)
 311{
 312        struct address_space *mapping = in->f_mapping;
 313        unsigned int loff, nr_pages, req_pages;
 314        struct page *pages[PIPE_DEF_BUFFERS];
 315        struct partial_page partial[PIPE_DEF_BUFFERS];
 316        struct page *page;
 317        pgoff_t index, end_index;
 318        loff_t isize;
 319        int error, page_nr;
 320        struct splice_pipe_desc spd = {
 321                .pages = pages,
 322                .partial = partial,
 323                .nr_pages_max = PIPE_DEF_BUFFERS,
 324                .flags = flags,
 325                .ops = &page_cache_pipe_buf_ops,
 326                .spd_release = spd_release_page,
 327        };
 328
 329        if (splice_grow_spd(pipe, &spd))
 330                return -ENOMEM;
 331
 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         * Lookup the (hopefully) full range of pages we need.
 339         */
 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                page_cache_sync_readahead(mapping, &in->f_ra, in,
 349                                index, req_pages - spd.nr_pages);
 350
 351        error = 0;
 352        while (spd.nr_pages < nr_pages) {
 353                /*
 354                 * Page could be there, find_get_pages_contig() breaks on
 355                 * the first hole.
 356                 */
 357                page = find_get_page(mapping, index);
 358                if (!page) {
 359                        /*
 360                         * page didn't exist, allocate one.
 361                         */
 362                        page = page_cache_alloc_cold(mapping);
 363                        if (!page)
 364                                break;
 365
 366                        error = add_to_page_cache_lru(page, mapping, index,
 367                                                GFP_KERNEL);
 368                        if (unlikely(error)) {
 369                                page_cache_release(page);
 370                                if (error == -EEXIST)
 371                                        continue;
 372                                break;
 373                        }
 374                        /*
 375                         * add_to_page_cache() locks the page, unlock it
 376                         * to avoid convoluting the logic below even more.
 377                         */
 378                        unlock_page(page);
 379                }
 380
 381                spd.pages[spd.nr_pages++] = page;
 382                index++;
 383        }
 384
 385        /*
 386         * Now loop over the map and see if we need to start IO on any
 387         * pages, fill in the partial map, etc.
 388         */
 389        index = *ppos >> PAGE_CACHE_SHIFT;
 390        nr_pages = spd.nr_pages;
 391        spd.nr_pages = 0;
 392        for (page_nr = 0; page_nr < nr_pages; page_nr++) {
 393                unsigned int this_len;
 394
 395                if (!len)
 396                        break;
 397
 398                /*
 399                 * this_len is the max we'll use from this page
 400                 */
 401                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                 * If the page isn't uptodate, we may need to start io on it
 410                 */
 411                if (!PageUptodate(page)) {
 412                        lock_page(page);
 413
 414                        /*
 415                         * Page was truncated, or invalidated by the
 416                         * filesystem.  Redo the find/create, but this time the
 417                         * page is kept locked, so there's no chance of another
 418                         * race with truncate/invalidate.
 419                         */
 420                        if (!page->mapping) {
 421                                unlock_page(page);
 422retry_lookup:
 423                                page = find_or_create_page(mapping, index,
 424                                                mapping_gfp_mask(mapping));
 425
 426                                if (!page) {
 427                                        error = -ENOMEM;
 428                                        break;
 429                                }
 430                                page_cache_release(spd.pages[page_nr]);
 431                                spd.pages[page_nr] = page;
 432                        }
 433                        /*
 434                         * page was already under io and is now done, great
 435                         */
 436                        if (PageUptodate(page)) {
 437                                unlock_page(page);
 438                                goto fill_it;
 439                        }
 440
 441                        /*
 442                         * need to read in the page
 443                         */
 444                        error = mapping->a_ops->readpage(in, page);
 445                        if (unlikely(error)) {
 446                                /*
 447                                 * Re-lookup the page
 448                                 */
 449                                if (error == AOP_TRUNCATED_PAGE)
 450                                        goto retry_lookup;
 451
 452                                break;
 453                        }
 454                }
 455fill_it:
 456                /*
 457                 * i_size must be checked after PageUptodate.
 458                 */
 459                isize = i_size_read(mapping->host);
 460                end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
 461                if (unlikely(!isize || index > end_index))
 462                        break;
 463
 464                /*
 465                 * if this is the last page, see if we need to shrink
 466                 * the length and stop
 467                 */
 468                if (end_index == index) {
 469                        unsigned int plen;
 470
 471                        /*
 472                         * max good bytes in this page
 473                         */
 474                        plen = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
 475                        if (plen <= loff)
 476                                break;
 477
 478                        /*
 479                         * force quit after adding this page
 480                         */
 481                        this_len = min(this_len, plen - loff);
 482                        len = this_len;
 483                }
 484
 485                spd.partial[page_nr].offset = loff;
 486                spd.partial[page_nr].len = this_len;
 487                len -= this_len;
 488                loff = 0;
 489                spd.nr_pages++;
 490                index++;
 491        }
 492
 493        /*
 494         * Release any pages at the end, if we quit early. 'page_nr' is how far
 495         * we got, 'nr_pages' is how many pages are in the map.
 496         */
 497        while (page_nr < nr_pages)
 498                page_cache_release(spd.pages[page_nr++]);
 499        in->f_ra.prev_pos = (loff_t)index << PAGE_CACHE_SHIFT;
 500
 501        if (spd.nr_pages)
 502                error = splice_to_pipe(pipe, &spd);
 503
 504        splice_shrink_spd(&spd);
 505        return error;
 506}
 507
 508/**
 509 * generic_file_splice_read - splice data from file to a pipe
 510 * @in:         file to splice from
 511 * @ppos:       position in @in
 512 * @pipe:       pipe to splice to
 513 * @len:        number of bytes to splice
 514 * @flags:      splice modifier flags
 515 *
 516 * Description:
 517 *    Will read pages from given file and fill them into a pipe. Can be
 518 *    used as long as the address_space operations for the source implements
 519 *    a readpage() hook.
 520 *
 521 */
 522ssize_t generic_file_splice_read(struct file *in, loff_t *ppos,
 523                                 struct pipe_inode_info *pipe, size_t len,
 524                                 unsigned int flags)
 525{
 526        loff_t isize, left;
 527        int ret;
 528
 529        if (IS_DAX(in->f_mapping->host))
 530                return default_file_splice_read(in, ppos, pipe, len, flags);
 531
 532        isize = i_size_read(in->f_mapping->host);
 533        if (unlikely(*ppos >= isize))
 534                return 0;
 535
 536        left = isize - *ppos;
 537        if (unlikely(left < len))
 538                len = left;
 539
 540        ret = __generic_file_splice_read(in, ppos, pipe, len, flags);
 541        if (ret > 0) {
 542                *ppos += ret;
 543                file_accessed(in);
 544        }
 545
 546        return ret;
 547}
 548EXPORT_SYMBOL(generic_file_splice_read);
 549
 550static const struct pipe_buf_operations default_pipe_buf_ops = {
 551        .can_merge = 0,
 552        .map = generic_pipe_buf_map,
 553        .unmap = generic_pipe_buf_unmap,
 554        .confirm = generic_pipe_buf_confirm,
 555        .release = generic_pipe_buf_release,
 556        .steal = generic_pipe_buf_steal,
 557        .get = generic_pipe_buf_get,
 558};
 559
 560static ssize_t kernel_readv(struct file *file, const struct iovec *vec,
 561                            unsigned long vlen, loff_t offset)
 562{
 563        mm_segment_t old_fs;
 564        loff_t pos = offset;
 565        ssize_t res;
 566
 567        old_fs = get_fs();
 568        set_fs(get_ds());
 569        /* The cast to a user pointer is valid due to the set_fs() */
 570        res = vfs_readv(file, (const struct iovec __user *)vec, vlen, &pos);
 571        set_fs(old_fs);
 572
 573        return res;
 574}
 575
 576ssize_t kernel_write(struct file *file, const char *buf, size_t count,
 577                            loff_t pos)
 578{
 579        mm_segment_t old_fs;
 580        ssize_t res;
 581
 582        old_fs = get_fs();
 583        set_fs(get_ds());
 584        /* The cast to a user pointer is valid due to the set_fs() */
 585        res = vfs_write(file, (__force const char __user *)buf, count, &pos);
 586        set_fs(old_fs);
 587
 588        return res;
 589}
 590EXPORT_SYMBOL(kernel_write);
 591
 592ssize_t default_file_splice_read(struct file *in, loff_t *ppos,
 593                                 struct pipe_inode_info *pipe, size_t len,
 594                                 unsigned int flags)
 595{
 596        unsigned int nr_pages;
 597        unsigned int nr_freed;
 598        size_t offset;
 599        struct page *pages[PIPE_DEF_BUFFERS];
 600        struct partial_page partial[PIPE_DEF_BUFFERS];
 601        struct iovec *vec, __vec[PIPE_DEF_BUFFERS];
 602        ssize_t res;
 603        size_t this_len;
 604        int error;
 605        int i;
 606        struct splice_pipe_desc spd = {
 607                .pages = pages,
 608                .partial = partial,
 609                .nr_pages_max = PIPE_DEF_BUFFERS,
 610                .flags = flags,
 611                .ops = &default_pipe_buf_ops,
 612                .spd_release = spd_release_page,
 613        };
 614
 615        if (splice_grow_spd(pipe, &spd))
 616                return -ENOMEM;
 617
 618        res = -ENOMEM;
 619        vec = __vec;
 620        if (spd.nr_pages_max > PIPE_DEF_BUFFERS) {
 621                vec = kmalloc(spd.nr_pages_max * sizeof(struct iovec), GFP_KERNEL);
 622                if (!vec)
 623                        goto shrink_ret;
 624        }
 625
 626        offset = *ppos & ~PAGE_CACHE_MASK;
 627        nr_pages = (len + offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
 628
 629        for (i = 0; i < nr_pages && i < spd.nr_pages_max && len; i++) {
 630                struct page *page;
 631
 632                page = alloc_page(GFP_USER);
 633                error = -ENOMEM;
 634                if (!page)
 635                        goto err;
 636
 637                this_len = min_t(size_t, len, PAGE_CACHE_SIZE - offset);
 638                vec[i].iov_base = (void __user *) page_address(page);
 639                vec[i].iov_len = this_len;
 640                spd.pages[i] = page;
 641                spd.nr_pages++;
 642                len -= this_len;
 643                offset = 0;
 644        }
 645
 646        res = kernel_readv(in, vec, spd.nr_pages, *ppos);
 647        if (res < 0) {
 648                error = res;
 649                goto err;
 650        }
 651
 652        error = 0;
 653        if (!res)
 654                goto err;
 655
 656        nr_freed = 0;
 657        for (i = 0; i < spd.nr_pages; i++) {
 658                this_len = min_t(size_t, vec[i].iov_len, res);
 659                spd.partial[i].offset = 0;
 660                spd.partial[i].len = this_len;
 661                if (!this_len) {
 662                        __free_page(spd.pages[i]);
 663                        spd.pages[i] = NULL;
 664                        nr_freed++;
 665                }
 666                res -= this_len;
 667        }
 668        spd.nr_pages -= nr_freed;
 669
 670        res = splice_to_pipe(pipe, &spd);
 671        if (res > 0)
 672                *ppos += res;
 673
 674shrink_ret:
 675        if (vec != __vec)
 676                kfree(vec);
 677        splice_shrink_spd(&spd);
 678        return res;
 679
 680err:
 681        for (i = 0; i < spd.nr_pages; i++)
 682                __free_page(spd.pages[i]);
 683
 684        res = error;
 685        goto shrink_ret;
 686}
 687EXPORT_SYMBOL(default_file_splice_read);
 688
 689/*
 690 * Send 'sd->len' bytes to socket from 'sd->file' at position 'sd->pos'
 691 * using sendpage(). Return the number of bytes sent.
 692 */
 693static int pipe_to_sendpage(struct pipe_inode_info *pipe,
 694                            struct pipe_buffer *buf, struct splice_desc *sd)
 695{
 696        struct file *file = sd->u.file;
 697        loff_t pos = sd->pos;
 698        int more;
 699
 700        if (!likely(file->f_op && file->f_op->sendpage))
 701                return -EINVAL;
 702
 703        more = (sd->flags & SPLICE_F_MORE) ? MSG_MORE : 0;
 704
 705        if (sd->len < sd->total_len && pipe->nrbufs > 1)
 706                more |= MSG_SENDPAGE_NOTLAST;
 707
 708        return file->f_op->sendpage(file, buf->page, buf->offset,
 709                                    sd->len, &pos, more);
 710}
 711
 712/*
 713 * This is a little more tricky than the file -> pipe splicing. There are
 714 * basically three cases:
 715 *
 716 *      - Destination page already exists in the address space and there
 717 *        are users of it. For that case we have no other option that
 718 *        copying the data. Tough luck.
 719 *      - Destination page already exists in the address space, but there
 720 *        are no users of it. Make sure it's uptodate, then drop it. Fall
 721 *        through to last case.
 722 *      - Destination page does not exist, we can add the pipe page to
 723 *        the page cache and avoid the copy.
 724 *
 725 * If asked to move pages to the output file (SPLICE_F_MOVE is set in
 726 * sd->flags), we attempt to migrate pages from the pipe to the output
 727 * file address space page cache. This is possible if no one else has
 728 * the pipe page referenced outside of the pipe and page cache. If
 729 * SPLICE_F_MOVE isn't set, or we cannot move the page, we simply create
 730 * a new page in the output file page cache and fill/dirty that.
 731 */
 732int pipe_to_file(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
 733                 struct splice_desc *sd)
 734{
 735        struct file *file = sd->u.file;
 736        struct address_space *mapping = file->f_mapping;
 737        unsigned int offset, this_len;
 738        struct page *page;
 739        void *fsdata;
 740        int ret;
 741
 742        offset = sd->pos & ~PAGE_CACHE_MASK;
 743
 744        this_len = sd->len;
 745        if (this_len + offset > PAGE_CACHE_SIZE)
 746                this_len = PAGE_CACHE_SIZE - offset;
 747
 748        ret = pagecache_write_begin(file, mapping, sd->pos, this_len,
 749                                AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
 750        if (unlikely(ret))
 751                goto out;
 752
 753        if (buf->page != page) {
 754                char *src = buf->ops->map(pipe, buf, 1);
 755                char *dst = kmap_atomic(page);
 756
 757                memcpy(dst + offset, src + buf->offset, this_len);
 758                flush_dcache_page(page);
 759                kunmap_atomic(dst);
 760                buf->ops->unmap(pipe, buf, src);
 761        }
 762        ret = pagecache_write_end(file, mapping, sd->pos, this_len, this_len,
 763                                page, fsdata);
 764out:
 765        return ret;
 766}
 767EXPORT_SYMBOL(pipe_to_file);
 768
 769static void wakeup_pipe_writers(struct pipe_inode_info *pipe)
 770{
 771        smp_mb();
 772        if (waitqueue_active(&pipe->wait))
 773                wake_up_interruptible(&pipe->wait);
 774        kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
 775}
 776
 777/**
 778 * splice_from_pipe_feed - feed available data from a pipe to a file
 779 * @pipe:       pipe to splice from
 780 * @sd:         information to @actor
 781 * @actor:      handler that splices the data
 782 *
 783 * Description:
 784 *    This function loops over the pipe and calls @actor to do the
 785 *    actual moving of a single struct pipe_buffer to the desired
 786 *    destination.  It returns when there's no more buffers left in
 787 *    the pipe or if the requested number of bytes (@sd->total_len)
 788 *    have been copied.  It returns a positive number (one) if the
 789 *    pipe needs to be filled with more data, zero if the required
 790 *    number of bytes have been copied and -errno on error.
 791 *
 792 *    This, together with splice_from_pipe_{begin,end,next}, may be
 793 *    used to implement the functionality of __splice_from_pipe() when
 794 *    locking is required around copying the pipe buffers to the
 795 *    destination.
 796 */
 797int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd,
 798                          splice_actor *actor)
 799{
 800        int ret;
 801
 802        while (pipe->nrbufs) {
 803                struct pipe_buffer *buf = pipe->bufs + pipe->curbuf;
 804                const struct pipe_buf_operations *ops = buf->ops;
 805
 806                sd->len = buf->len;
 807                if (sd->len > sd->total_len)
 808                        sd->len = sd->total_len;
 809
 810                ret = buf->ops->confirm(pipe, buf);
 811                if (unlikely(ret)) {
 812                        if (ret == -ENODATA)
 813                                ret = 0;
 814                        return ret;
 815                }
 816
 817                ret = actor(pipe, buf, sd);
 818                if (ret <= 0)
 819                        return ret;
 820
 821                buf->offset += ret;
 822                buf->len -= ret;
 823
 824                sd->num_spliced += ret;
 825                sd->len -= ret;
 826                sd->pos += ret;
 827                sd->total_len -= ret;
 828
 829                if (!buf->len) {
 830                        buf->ops = NULL;
 831                        ops->release(pipe, buf);
 832                        pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
 833                        pipe->nrbufs--;
 834                        if (pipe->files)
 835                                sd->need_wakeup = true;
 836                }
 837
 838                if (!sd->total_len)
 839                        return 0;
 840        }
 841
 842        return 1;
 843}
 844EXPORT_SYMBOL(splice_from_pipe_feed);
 845
 846/**
 847 * splice_from_pipe_next - wait for some data to splice from
 848 * @pipe:       pipe to splice from
 849 * @sd:         information about the splice operation
 850 *
 851 * Description:
 852 *    This function will wait for some data and return a positive
 853 *    value (one) if pipe buffers are available.  It will return zero
 854 *    or -errno if no more data needs to be spliced.
 855 */
 856int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
 857{
 858        while (!pipe->nrbufs) {
 859                if (!pipe->writers)
 860                        return 0;
 861
 862                if (!pipe->waiting_writers && sd->num_spliced)
 863                        return 0;
 864
 865                if (sd->flags & SPLICE_F_NONBLOCK)
 866                        return -EAGAIN;
 867
 868                if (signal_pending(current))
 869                        return -ERESTARTSYS;
 870
 871                if (sd->need_wakeup) {
 872                        wakeup_pipe_writers(pipe);
 873                        sd->need_wakeup = false;
 874                }
 875
 876                pipe_wait(pipe);
 877        }
 878
 879        return 1;
 880}
 881EXPORT_SYMBOL(splice_from_pipe_next);
 882
 883/**
 884 * splice_from_pipe_begin - start splicing from pipe
 885 * @sd:         information about the splice operation
 886 *
 887 * Description:
 888 *    This function should be called before a loop containing
 889 *    splice_from_pipe_next() and splice_from_pipe_feed() to
 890 *    initialize the necessary fields of @sd.
 891 */
 892void splice_from_pipe_begin(struct splice_desc *sd)
 893{
 894        sd->num_spliced = 0;
 895        sd->need_wakeup = false;
 896}
 897EXPORT_SYMBOL(splice_from_pipe_begin);
 898
 899/**
 900 * splice_from_pipe_end - finish splicing from pipe
 901 * @pipe:       pipe to splice from
 902 * @sd:         information about the splice operation
 903 *
 904 * Description:
 905 *    This function will wake up pipe writers if necessary.  It should
 906 *    be called after a loop containing splice_from_pipe_next() and
 907 *    splice_from_pipe_feed().
 908 */
 909void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
 910{
 911        if (sd->need_wakeup)
 912                wakeup_pipe_writers(pipe);
 913}
 914EXPORT_SYMBOL(splice_from_pipe_end);
 915
 916/**
 917 * __splice_from_pipe - splice data from a pipe to given actor
 918 * @pipe:       pipe to splice from
 919 * @sd:         information to @actor
 920 * @actor:      handler that splices the data
 921 *
 922 * Description:
 923 *    This function does little more than loop over the pipe and call
 924 *    @actor to do the actual moving of a single struct pipe_buffer to
 925 *    the desired destination. See pipe_to_file, pipe_to_sendpage, or
 926 *    pipe_to_user.
 927 *
 928 */
 929ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd,
 930                           splice_actor *actor)
 931{
 932        int ret;
 933
 934        splice_from_pipe_begin(sd);
 935        do {
 936                ret = splice_from_pipe_next(pipe, sd);
 937                if (ret > 0)
 938                        ret = splice_from_pipe_feed(pipe, sd, actor);
 939        } while (ret > 0);
 940        splice_from_pipe_end(pipe, sd);
 941
 942        return sd->num_spliced ? sd->num_spliced : ret;
 943}
 944EXPORT_SYMBOL(__splice_from_pipe);
 945
 946/**
 947 * splice_from_pipe - splice data from a pipe to a file
 948 * @pipe:       pipe to splice from
 949 * @out:        file to splice to
 950 * @ppos:       position in @out
 951 * @len:        how many bytes to splice
 952 * @flags:      splice modifier flags
 953 * @actor:      handler that splices the data
 954 *
 955 * Description:
 956 *    See __splice_from_pipe. This function locks the pipe inode,
 957 *    otherwise it's identical to __splice_from_pipe().
 958 *
 959 */
 960ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,
 961                         loff_t *ppos, size_t len, unsigned int flags,
 962                         splice_actor *actor)
 963{
 964        ssize_t ret;
 965        struct splice_desc sd = {
 966                .total_len = len,
 967                .flags = flags,
 968                .pos = *ppos,
 969                .u.file = out,
 970        };
 971
 972        pipe_lock(pipe);
 973        ret = __splice_from_pipe(pipe, &sd, actor);
 974        pipe_unlock(pipe);
 975
 976        return ret;
 977}
 978
 979/**
 980 * splice_write_to_file - splice data from a pipe to a file
 981 * @pipe:       pipe info
 982 * @out:        file to write to
 983 * @ppos:       position in @out
 984 * @len:        number of bytes to splice
 985 * @flags:      splice modifier flags
 986 * @actor:      worker that does the splicing from the pipe to the file
 987 *
 988 * Description:
 989 *    Will either move or copy pages (determined by @flags options) from
 990 *    the given pipe inode to the given file.
 991 *
 992 */
 993ssize_t splice_write_to_file(struct pipe_inode_info *pipe, struct file *out,
 994                             loff_t *ppos, size_t len, unsigned int flags,
 995                             splice_write_actor actor)
 996{
 997        struct address_space *mapping = out->f_mapping;
 998        struct splice_desc sd = {
 999                .total_len = len,
1000                .flags = flags,
1001                .pos = *ppos,
1002                .u.file = out,
1003        };
1004        ssize_t ret;
1005
1006        pipe_lock(pipe);
1007
1008        splice_from_pipe_begin(&sd);
1009        do {
1010                ret = splice_from_pipe_next(pipe, &sd);
1011                if (ret <= 0)
1012                        break;
1013
1014                ret = actor(pipe, &sd);
1015
1016        } while (ret > 0);
1017        splice_from_pipe_end(pipe, &sd);
1018
1019        pipe_unlock(pipe);
1020
1021        if (sd.num_spliced)
1022                ret = sd.num_spliced;
1023
1024        if (ret > 0) {
1025                int err;
1026
1027                err = generic_write_sync(out, *ppos, ret);
1028                if (err)
1029                        ret = err;
1030                else
1031                        *ppos += ret;
1032                balance_dirty_pages_ratelimited(mapping);
1033        }
1034
1035        return ret;
1036}
1037EXPORT_SYMBOL(splice_write_to_file);
1038
1039static ssize_t generic_file_splice_write_actor(struct pipe_inode_info *pipe,
1040                                               struct splice_desc *sd)
1041{
1042        struct file *out = sd->u.file;
1043        struct inode *inode = out->f_mapping->host;
1044        ssize_t ret;
1045
1046        mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1047        ret = file_remove_privs(out);
1048        if (!ret) {
1049                file_update_time(out);
1050                ret = splice_from_pipe_feed(pipe, sd, pipe_to_file);
1051        }
1052        mutex_unlock(&inode->i_mutex);
1053
1054        return ret;
1055}
1056
1057static int write_pipe_buf(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1058                          struct splice_desc *sd)
1059{
1060        int ret;
1061        void *data;
1062        loff_t tmp = sd->pos;
1063
1064        data = buf->ops->map(pipe, buf, 0);
1065        ret = __kernel_write(sd->u.file, data + buf->offset, sd->len, &tmp);
1066        buf->ops->unmap(pipe, buf, data);
1067
1068        return ret;
1069}
1070
1071ssize_t default_file_splice_write(struct pipe_inode_info *pipe,
1072                                         struct file *out, loff_t *ppos,
1073                                         size_t len, unsigned int flags)
1074{
1075        ssize_t ret;
1076
1077        ret = splice_from_pipe(pipe, out, ppos, len, flags, write_pipe_buf);
1078        if (ret > 0)
1079                *ppos += ret;
1080
1081        return ret;
1082}
1083EXPORT_SYMBOL(default_file_splice_write);
1084
1085/**
1086 * generic_file_splice_write - splice data from a pipe to a file
1087 * @pipe:       pipe info
1088 * @out:        file to write to
1089 * @ppos:       position in @out
1090 * @len:        number of bytes to splice
1091 * @flags:      splice modifier flags
1092 *
1093 * Description:
1094 *    Will either move or copy pages (determined by @flags options) from
1095 *    the given pipe inode to the given file.
1096 *
1097 */
1098ssize_t
1099generic_file_splice_write(struct pipe_inode_info *pipe, struct file *out,
1100                          loff_t *ppos, size_t len, unsigned int flags)
1101{
1102        if (IS_DAX(out->f_mapping->host))
1103                return default_file_splice_write(pipe, out, ppos, len, flags);
1104
1105        return splice_write_to_file(pipe, out, ppos, len, flags,
1106                                    generic_file_splice_write_actor);
1107}
1108EXPORT_SYMBOL(generic_file_splice_write);
1109
1110/**
1111 * generic_splice_sendpage - splice data from a pipe to a socket
1112 * @pipe:       pipe to splice from
1113 * @out:        socket to write to
1114 * @ppos:       position in @out
1115 * @len:        number of bytes to splice
1116 * @flags:      splice modifier flags
1117 *
1118 * Description:
1119 *    Will send @len bytes from the pipe to a network socket. No data copying
1120 *    is involved.
1121 *
1122 */
1123ssize_t generic_splice_sendpage(struct pipe_inode_info *pipe, struct file *out,
1124                                loff_t *ppos, size_t len, unsigned int flags)
1125{
1126        return splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_sendpage);
1127}
1128
1129EXPORT_SYMBOL(generic_splice_sendpage);
1130
1131/*
1132 * Attempt to initiate a splice from pipe to file.
1133 */
1134static long do_splice_from(struct pipe_inode_info *pipe, struct file *out,
1135                           loff_t *ppos, size_t len, unsigned int flags)
1136{
1137        ssize_t (*splice_write)(struct pipe_inode_info *, struct file *,
1138                                loff_t *, size_t, unsigned int);
1139        struct inode *inode = out->f_mapping->host;
1140        int ret;
1141
1142        if (unlikely(!(out->f_mode & FMODE_WRITE)))
1143                return -EBADF;
1144
1145        if (unlikely(out->f_flags & O_APPEND))
1146                return -EINVAL;
1147
1148        ret = rw_verify_area(WRITE, out, ppos, len);
1149        if (unlikely(ret < 0))
1150                return ret;
1151
1152        ret = generic_write_checks(out, ppos, &len, S_ISBLK(inode->i_mode));
1153        if (ret)
1154                return ret;
1155
1156        if (out->f_op && out->f_op->splice_write)
1157                splice_write = out->f_op->splice_write;
1158        else
1159                splice_write = default_file_splice_write;
1160
1161        return splice_write(pipe, out, ppos, len, flags);
1162}
1163
1164/*
1165 * Attempt to initiate a splice from a file to a pipe.
1166 */
1167static long do_splice_to(struct file *in, loff_t *ppos,
1168                         struct pipe_inode_info *pipe, size_t len,
1169                         unsigned int flags)
1170{
1171        ssize_t (*splice_read)(struct file *, loff_t *,
1172                               struct pipe_inode_info *, size_t, unsigned int);
1173        int ret;
1174
1175        if (unlikely(!(in->f_mode & FMODE_READ)))
1176                return -EBADF;
1177
1178        ret = rw_verify_area(READ, in, ppos, len);
1179        if (unlikely(ret < 0))
1180                return ret;
1181
1182        if (in->f_op && in->f_op->splice_read)
1183                splice_read = in->f_op->splice_read;
1184        else
1185                splice_read = default_file_splice_read;
1186
1187        return splice_read(in, ppos, pipe, len, flags);
1188}
1189
1190/**
1191 * splice_direct_to_actor - splices data directly between two non-pipes
1192 * @in:         file to splice from
1193 * @sd:         actor information on where to splice to
1194 * @actor:      handles the data splicing
1195 *
1196 * Description:
1197 *    This is a special case helper to splice directly between two
1198 *    points, without requiring an explicit pipe. Internally an allocated
1199 *    pipe is cached in the process, and reused during the lifetime of
1200 *    that process.
1201 *
1202 */
1203ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,
1204                               splice_direct_actor *actor)
1205{
1206        struct pipe_inode_info *pipe;
1207        long ret, bytes;
1208        umode_t i_mode;
1209        size_t len;
1210        int i, flags;
1211
1212        /*
1213         * We require the input being a regular file, as we don't want to
1214         * randomly drop data for eg socket -> socket splicing. Use the
1215         * piped splicing for that!
1216         */
1217        i_mode = file_inode(in)->i_mode;
1218        if (unlikely(!S_ISREG(i_mode) && !S_ISBLK(i_mode)))
1219                return -EINVAL;
1220
1221        /*
1222         * neither in nor out is a pipe, setup an internal pipe attached to
1223         * 'out' and transfer the wanted data from 'in' to 'out' through that
1224         */
1225        pipe = current->splice_pipe;
1226        if (unlikely(!pipe)) {
1227                pipe = alloc_pipe_info();
1228                if (!pipe)
1229                        return -ENOMEM;
1230
1231                /*
1232                 * We don't have an immediate reader, but we'll read the stuff
1233                 * out of the pipe right after the splice_to_pipe(). So set
1234                 * PIPE_READERS appropriately.
1235                 */
1236                pipe->readers = 1;
1237
1238                current->splice_pipe = pipe;
1239        }
1240
1241        /*
1242         * Do the splice.
1243         */
1244        ret = 0;
1245        bytes = 0;
1246        len = sd->total_len;
1247        flags = sd->flags;
1248
1249        /*
1250         * Don't block on output, we have to drain the direct pipe.
1251         */
1252        sd->flags &= ~SPLICE_F_NONBLOCK;
1253
1254        while (len) {
1255                size_t read_len;
1256                loff_t pos = sd->pos, prev_pos = pos;
1257
1258                ret = do_splice_to(in, &pos, pipe, len, flags);
1259                if (unlikely(ret <= 0))
1260                        goto out_release;
1261
1262                read_len = ret;
1263                sd->total_len = read_len;
1264
1265                /*
1266                 * NOTE: nonblocking mode only applies to the input. We
1267                 * must not do the output in nonblocking mode as then we
1268                 * could get stuck data in the internal pipe:
1269                 */
1270                ret = actor(pipe, sd);
1271                if (unlikely(ret <= 0)) {
1272                        sd->pos = prev_pos;
1273                        goto out_release;
1274                }
1275
1276                bytes += ret;
1277                len -= ret;
1278                sd->pos = pos;
1279
1280                if (ret < read_len) {
1281                        sd->pos = prev_pos + ret;
1282                        goto out_release;
1283                }
1284        }
1285
1286done:
1287        pipe->nrbufs = pipe->curbuf = 0;
1288        file_accessed(in);
1289        return bytes;
1290
1291out_release:
1292        /*
1293         * If we did an incomplete transfer we must release
1294         * the pipe buffers in question:
1295         */
1296        for (i = 0; i < pipe->buffers; i++) {
1297                struct pipe_buffer *buf = pipe->bufs + i;
1298
1299                if (buf->ops) {
1300                        buf->ops->release(pipe, buf);
1301                        buf->ops = NULL;
1302                }
1303        }
1304
1305        if (!bytes)
1306                bytes = ret;
1307
1308        goto done;
1309}
1310EXPORT_SYMBOL(splice_direct_to_actor);
1311
1312static int direct_splice_actor(struct pipe_inode_info *pipe,
1313                               struct splice_desc *sd)
1314{
1315        struct file *file = sd->u.file;
1316
1317        return do_splice_from(pipe, file, sd->opos, sd->total_len,
1318                              sd->flags);
1319}
1320
1321/**
1322 * do_splice_direct - splices data directly between two files
1323 * @in:         file to splice from
1324 * @ppos:       input file offset
1325 * @out:        file to splice to
1326 * @opos:       output file offset
1327 * @len:        number of bytes to splice
1328 * @flags:      splice modifier flags
1329 *
1330 * Description:
1331 *    For use by do_sendfile(). splice can easily emulate sendfile, but
1332 *    doing it in the application would incur an extra system call
1333 *    (splice in + splice out, as compared to just sendfile()). So this helper
1334 *    can splice directly through a process-private pipe.
1335 *
1336 */
1337long do_splice_direct(struct file *in, loff_t *ppos, struct file *out,
1338                      loff_t *opos, size_t len, unsigned int flags)
1339{
1340        struct splice_desc sd = {
1341                .len            = len,
1342                .total_len      = len,
1343                .flags          = flags,
1344                .pos            = *ppos,
1345                .u.file         = out,
1346                .opos           = opos,
1347        };
1348        long ret;
1349
1350        ret = splice_direct_to_actor(in, &sd, direct_splice_actor);
1351        if (ret > 0)
1352                *ppos = sd.pos;
1353
1354        return ret;
1355}
1356EXPORT_SYMBOL(do_splice_direct);
1357
1358static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1359                               struct pipe_inode_info *opipe,
1360                               size_t len, unsigned int flags);
1361
1362/*
1363 * Determine where to splice to/from.
1364 */
1365static long do_splice(struct file *in, loff_t __user *off_in,
1366                      struct file *out, loff_t __user *off_out,
1367                      size_t len, unsigned int flags)
1368{
1369        struct pipe_inode_info *ipipe;
1370        struct pipe_inode_info *opipe;
1371        loff_t offset;
1372        long ret;
1373
1374        ipipe = get_pipe_info(in);
1375        opipe = get_pipe_info(out);
1376
1377        if (ipipe && opipe) {
1378                if (off_in || off_out)
1379                        return -ESPIPE;
1380
1381                if (!(in->f_mode & FMODE_READ))
1382                        return -EBADF;
1383
1384                if (!(out->f_mode & FMODE_WRITE))
1385                        return -EBADF;
1386
1387                /* Splicing to self would be fun, but... */
1388                if (ipipe == opipe)
1389                        return -EINVAL;
1390
1391                return splice_pipe_to_pipe(ipipe, opipe, len, flags);
1392        }
1393
1394        if (ipipe) {
1395                if (off_in)
1396                        return -ESPIPE;
1397                if (off_out) {
1398                        if (!(out->f_mode & FMODE_PWRITE))
1399                                return -EINVAL;
1400                        if (copy_from_user(&offset, off_out, sizeof(loff_t)))
1401                                return -EFAULT;
1402                } else {
1403                        offset = out->f_pos;
1404                }
1405
1406                file_start_write(out);
1407                ret = do_splice_from(ipipe, out, &offset, len, flags);
1408                file_end_write(out);
1409
1410                if (!off_out)
1411                        out->f_pos = offset;
1412                else if (copy_to_user(off_out, &offset, sizeof(loff_t)))
1413                        ret = -EFAULT;
1414
1415                return ret;
1416        }
1417
1418        if (opipe) {
1419                if (off_out)
1420                        return -ESPIPE;
1421                if (off_in) {
1422                        if (!(in->f_mode & FMODE_PREAD))
1423                                return -EINVAL;
1424                        if (copy_from_user(&offset, off_in, sizeof(loff_t)))
1425                                return -EFAULT;
1426                } else {
1427                        offset = in->f_pos;
1428                }
1429
1430                ret = do_splice_to(in, &offset, opipe, len, flags);
1431
1432                if (!off_in)
1433                        in->f_pos = offset;
1434                else if (copy_to_user(off_in, &offset, sizeof(loff_t)))
1435                        ret = -EFAULT;
1436
1437                return ret;
1438        }
1439
1440        return -EINVAL;
1441}
1442
1443/*
1444 * Map an iov into an array of pages and offset/length tupples. With the
1445 * partial_page structure, we can map several non-contiguous ranges into
1446 * our ones pages[] map instead of splitting that operation into pieces.
1447 * Could easily be exported as a generic helper for other users, in which
1448 * case one would probably want to add a 'max_nr_pages' parameter as well.
1449 */
1450static int get_iovec_page_array(const struct iovec __user *iov,
1451                                unsigned int nr_vecs, struct page **pages,
1452                                struct partial_page *partial, bool aligned,
1453                                unsigned int pipe_buffers)
1454{
1455        int buffers = 0, error = 0;
1456
1457        while (nr_vecs) {
1458                unsigned long off, npages;
1459                struct iovec entry;
1460                void __user *base;
1461                size_t len;
1462                int i;
1463
1464                error = -EFAULT;
1465                if (copy_from_user(&entry, iov, sizeof(entry)))
1466                        break;
1467
1468                base = entry.iov_base;
1469                len = entry.iov_len;
1470
1471                /*
1472                 * Sanity check this iovec. 0 read succeeds.
1473                 */
1474                error = 0;
1475                if (unlikely(!len))
1476                        break;
1477                error = -EFAULT;
1478                if (!access_ok(VERIFY_READ, base, len))
1479                        break;
1480
1481                /*
1482                 * Get this base offset and number of pages, then map
1483                 * in the user pages.
1484                 */
1485                off = (unsigned long) base & ~PAGE_MASK;
1486
1487                /*
1488                 * If asked for alignment, the offset must be zero and the
1489                 * length a multiple of the PAGE_SIZE.
1490                 */
1491                error = -EINVAL;
1492                if (aligned && (off || len & ~PAGE_MASK))
1493                        break;
1494
1495                npages = (off + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
1496                if (npages > pipe_buffers - buffers)
1497                        npages = pipe_buffers - buffers;
1498
1499                error = get_user_pages_fast((unsigned long)base, npages,
1500                                        0, &pages[buffers]);
1501
1502                if (unlikely(error <= 0))
1503                        break;
1504
1505                /*
1506                 * Fill this contiguous range into the partial page map.
1507                 */
1508                for (i = 0; i < error; i++) {
1509                        const int plen = min_t(size_t, len, PAGE_SIZE - off);
1510
1511                        partial[buffers].offset = off;
1512                        partial[buffers].len = plen;
1513
1514                        off = 0;
1515                        len -= plen;
1516                        buffers++;
1517                }
1518
1519                /*
1520                 * We didn't complete this iov, stop here since it probably
1521                 * means we have to move some of this into a pipe to
1522                 * be able to continue.
1523                 */
1524                if (len)
1525                        break;
1526
1527                /*
1528                 * Don't continue if we mapped fewer pages than we asked for,
1529                 * or if we mapped the max number of pages that we have
1530                 * room for.
1531                 */
1532                if (error < npages || buffers == pipe_buffers)
1533                        break;
1534
1535                nr_vecs--;
1536                iov++;
1537        }
1538
1539        if (buffers)
1540                return buffers;
1541
1542        return error;
1543}
1544
1545static int pipe_to_user(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
1546                        struct splice_desc *sd)
1547{
1548        char *src;
1549        int ret;
1550
1551        /*
1552         * See if we can use the atomic maps, by prefaulting in the
1553         * pages and doing an atomic copy
1554         */
1555        if (IS_ENABLED(CONFIG_HIGHMEM) && !fault_in_pages_writeable(sd->u.userptr, sd->len)) {
1556                src = buf->ops->map(pipe, buf, 1);
1557                ret = __copy_to_user_inatomic(sd->u.userptr, src + buf->offset,
1558                                                        sd->len);
1559                buf->ops->unmap(pipe, buf, src);
1560                if (!ret) {
1561                        ret = sd->len;
1562                        goto out;
1563                }
1564        }
1565
1566        /*
1567         * No dice, use slow non-atomic map and copy
1568         */
1569        src = buf->ops->map(pipe, buf, 0);
1570
1571        ret = sd->len;
1572        if (copy_to_user(sd->u.userptr, src + buf->offset, sd->len))
1573                ret = -EFAULT;
1574
1575        buf->ops->unmap(pipe, buf, src);
1576out:
1577        if (ret > 0)
1578                sd->u.userptr += ret;
1579        return ret;
1580}
1581
1582/*
1583 * For lack of a better implementation, implement vmsplice() to userspace
1584 * as a simple copy of the pipes pages to the user iov.
1585 */
1586static long vmsplice_to_user(struct file *file, const struct iovec __user *iov,
1587                             unsigned long nr_segs, unsigned int flags)
1588{
1589        struct pipe_inode_info *pipe;
1590        struct splice_desc sd;
1591        ssize_t size;
1592        int error;
1593        long ret;
1594
1595        pipe = get_pipe_info(file);
1596        if (!pipe)
1597                return -EBADF;
1598
1599        pipe_lock(pipe);
1600
1601        error = ret = 0;
1602        while (nr_segs) {
1603                void __user *base;
1604                size_t len;
1605
1606                /*
1607                 * Get user address base and length for this iovec.
1608                 */
1609                error = get_user(base, &iov->iov_base);
1610                if (unlikely(error))
1611                        break;
1612                error = get_user(len, &iov->iov_len);
1613                if (unlikely(error))
1614                        break;
1615
1616                /*
1617                 * Sanity check this iovec. 0 read succeeds.
1618                 */
1619                if (unlikely(!len))
1620                        break;
1621                if (unlikely(!base)) {
1622                        error = -EFAULT;
1623                        break;
1624                }
1625
1626                if (unlikely(!access_ok(VERIFY_WRITE, base, len))) {
1627                        error = -EFAULT;
1628                        break;
1629                }
1630
1631                sd.len = 0;
1632                sd.total_len = len;
1633                sd.flags = flags;
1634                sd.u.userptr = base;
1635                sd.pos = 0;
1636
1637                size = __splice_from_pipe(pipe, &sd, pipe_to_user);
1638                if (size < 0) {
1639                        if (!ret)
1640                                ret = size;
1641
1642                        break;
1643                }
1644
1645                ret += size;
1646
1647                if (size < len)
1648                        break;
1649
1650                nr_segs--;
1651                iov++;
1652        }
1653
1654        pipe_unlock(pipe);
1655
1656        if (!ret)
1657                ret = error;
1658
1659        return ret;
1660}
1661
1662/*
1663 * vmsplice splices a user address range into a pipe. It can be thought of
1664 * as splice-from-memory, where the regular splice is splice-from-file (or
1665 * to file). In both cases the output is a pipe, naturally.
1666 */
1667static long vmsplice_to_pipe(struct file *file, const struct iovec __user *iov,
1668                             unsigned long nr_segs, unsigned int flags)
1669{
1670        struct pipe_inode_info *pipe;
1671        struct page *pages[PIPE_DEF_BUFFERS];
1672        struct partial_page partial[PIPE_DEF_BUFFERS];
1673        struct splice_pipe_desc spd = {
1674                .pages = pages,
1675                .partial = partial,
1676                .nr_pages_max = PIPE_DEF_BUFFERS,
1677                .flags = flags,
1678                .ops = &user_page_pipe_buf_ops,
1679                .spd_release = spd_release_page,
1680        };
1681        long ret;
1682
1683        pipe = get_pipe_info(file);
1684        if (!pipe)
1685                return -EBADF;
1686
1687        if (splice_grow_spd(pipe, &spd))
1688                return -ENOMEM;
1689
1690        spd.nr_pages = get_iovec_page_array(iov, nr_segs, spd.pages,
1691                                            spd.partial, false,
1692                                            spd.nr_pages_max);
1693        if (spd.nr_pages <= 0)
1694                ret = spd.nr_pages;
1695        else
1696                ret = splice_to_pipe(pipe, &spd);
1697
1698        splice_shrink_spd(&spd);
1699        return ret;
1700}
1701
1702/*
1703 * Note that vmsplice only really supports true splicing _from_ user memory
1704 * to a pipe, not the other way around. Splicing from user memory is a simple
1705 * operation that can be supported without any funky alignment restrictions
1706 * or nasty vm tricks. We simply map in the user memory and fill them into
1707 * a pipe. The reverse isn't quite as easy, though. There are two possible
1708 * solutions for that:
1709 *
1710 *      - memcpy() the data internally, at which point we might as well just
1711 *        do a regular read() on the buffer anyway.
1712 *      - Lots of nasty vm tricks, that are neither fast nor flexible (it
1713 *        has restriction limitations on both ends of the pipe).
1714 *
1715 * Currently we punt and implement it as a normal copy, see pipe_to_user().
1716 *
1717 */
1718SYSCALL_DEFINE4(vmsplice, int, fd, const struct iovec __user *, iov,
1719                unsigned long, nr_segs, unsigned int, flags)
1720{
1721        struct fd f;
1722        long error;
1723
1724        if (unlikely(nr_segs > UIO_MAXIOV))
1725                return -EINVAL;
1726        else if (unlikely(!nr_segs))
1727                return 0;
1728
1729        error = -EBADF;
1730        f = fdget(fd);
1731        if (f.file) {
1732                if (f.file->f_mode & FMODE_WRITE)
1733                        error = vmsplice_to_pipe(f.file, iov, nr_segs, flags);
1734                else if (f.file->f_mode & FMODE_READ)
1735                        error = vmsplice_to_user(f.file, iov, nr_segs, flags);
1736
1737                fdput(f);
1738        }
1739
1740        return error;
1741}
1742
1743#ifdef CONFIG_COMPAT
1744COMPAT_SYSCALL_DEFINE4(vmsplice, int, fd, const struct compat_iovec __user *, iov32,
1745                    unsigned int, nr_segs, unsigned int, flags)
1746{
1747        unsigned i;
1748        struct iovec __user *iov;
1749        if (nr_segs > UIO_MAXIOV)
1750                return -EINVAL;
1751        iov = compat_alloc_user_space(nr_segs * sizeof(struct iovec));
1752        for (i = 0; i < nr_segs; i++) {
1753                struct compat_iovec v;
1754                if (get_user(v.iov_base, &iov32[i].iov_base) ||
1755                    get_user(v.iov_len, &iov32[i].iov_len) ||
1756                    put_user(compat_ptr(v.iov_base), &iov[i].iov_base) ||
1757                    put_user(v.iov_len, &iov[i].iov_len))
1758                        return -EFAULT;
1759        }
1760        return sys_vmsplice(fd, iov, nr_segs, flags);
1761}
1762#endif
1763
1764SYSCALL_DEFINE6(splice, int, fd_in, loff_t __user *, off_in,
1765                int, fd_out, loff_t __user *, off_out,
1766                size_t, len, unsigned int, flags)
1767{
1768        struct fd in, out;
1769        long error;
1770
1771        if (unlikely(!len))
1772                return 0;
1773
1774        error = -EBADF;
1775        in = fdget(fd_in);
1776        if (in.file) {
1777                if (in.file->f_mode & FMODE_READ) {
1778                        out = fdget(fd_out);
1779                        if (out.file) {
1780                                if (out.file->f_mode & FMODE_WRITE)
1781                                        error = do_splice(in.file, off_in,
1782                                                          out.file, off_out,
1783                                                          len, flags);
1784                                fdput(out);
1785                        }
1786                }
1787                fdput(in);
1788        }
1789        return error;
1790}
1791
1792/*
1793 * Make sure there's data to read. Wait for input if we can, otherwise
1794 * return an appropriate error.
1795 */
1796static int ipipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1797{
1798        int ret;
1799
1800        /*
1801         * Check ->nrbufs without the inode lock first. This function
1802         * is speculative anyways, so missing one is ok.
1803         */
1804        if (pipe->nrbufs)
1805                return 0;
1806
1807        ret = 0;
1808        pipe_lock(pipe);
1809
1810        while (!pipe->nrbufs) {
1811                if (signal_pending(current)) {
1812                        ret = -ERESTARTSYS;
1813                        break;
1814                }
1815                if (!pipe->writers)
1816                        break;
1817                if (!pipe->waiting_writers) {
1818                        if (flags & SPLICE_F_NONBLOCK) {
1819                                ret = -EAGAIN;
1820                                break;
1821                        }
1822                }
1823                pipe_wait(pipe);
1824        }
1825
1826        pipe_unlock(pipe);
1827        return ret;
1828}
1829
1830/*
1831 * Make sure there's writeable room. Wait for room if we can, otherwise
1832 * return an appropriate error.
1833 */
1834static int opipe_prep(struct pipe_inode_info *pipe, unsigned int flags)
1835{
1836        int ret;
1837
1838        /*
1839         * Check ->nrbufs without the inode lock first. This function
1840         * is speculative anyways, so missing one is ok.
1841         */
1842        if (pipe->nrbufs < pipe->buffers)
1843                return 0;
1844
1845        ret = 0;
1846        pipe_lock(pipe);
1847
1848        while (pipe->nrbufs >= pipe->buffers) {
1849                if (!pipe->readers) {
1850                        send_sig(SIGPIPE, current, 0);
1851                        ret = -EPIPE;
1852                        break;
1853                }
1854                if (flags & SPLICE_F_NONBLOCK) {
1855                        ret = -EAGAIN;
1856                        break;
1857                }
1858                if (signal_pending(current)) {
1859                        ret = -ERESTARTSYS;
1860                        break;
1861                }
1862                pipe->waiting_writers++;
1863                pipe_wait(pipe);
1864                pipe->waiting_writers--;
1865        }
1866
1867        pipe_unlock(pipe);
1868        return ret;
1869}
1870
1871/*
1872 * Splice contents of ipipe to opipe.
1873 */
1874static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
1875                               struct pipe_inode_info *opipe,
1876                               size_t len, unsigned int flags)
1877{
1878        struct pipe_buffer *ibuf, *obuf;
1879        int ret = 0, nbuf;
1880        bool input_wakeup = false;
1881
1882
1883retry:
1884        ret = ipipe_prep(ipipe, flags);
1885        if (ret)
1886                return ret;
1887
1888        ret = opipe_prep(opipe, flags);
1889        if (ret)
1890                return ret;
1891
1892        /*
1893         * Potential ABBA deadlock, work around it by ordering lock
1894         * grabbing by pipe info address. Otherwise two different processes
1895         * could deadlock (one doing tee from A -> B, the other from B -> A).
1896         */
1897        pipe_double_lock(ipipe, opipe);
1898
1899        do {
1900                if (!opipe->readers) {
1901                        send_sig(SIGPIPE, current, 0);
1902                        if (!ret)
1903                                ret = -EPIPE;
1904                        break;
1905                }
1906
1907                if (!ipipe->nrbufs && !ipipe->writers)
1908                        break;
1909
1910                /*
1911                 * Cannot make any progress, because either the input
1912                 * pipe is empty or the output pipe is full.
1913                 */
1914                if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
1915                        /* Already processed some buffers, break */
1916                        if (ret)
1917                                break;
1918
1919                        if (flags & SPLICE_F_NONBLOCK) {
1920                                ret = -EAGAIN;
1921                                break;
1922                        }
1923
1924                        /*
1925                         * We raced with another reader/writer and haven't
1926                         * managed to process any buffers.  A zero return
1927                         * value means EOF, so retry instead.
1928                         */
1929                        pipe_unlock(ipipe);
1930                        pipe_unlock(opipe);
1931                        goto retry;
1932                }
1933
1934                ibuf = ipipe->bufs + ipipe->curbuf;
1935                nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
1936                obuf = opipe->bufs + nbuf;
1937
1938                if (len >= ibuf->len) {
1939                        /*
1940                         * Simply move the whole buffer from ipipe to opipe
1941                         */
1942                        *obuf = *ibuf;
1943                        ibuf->ops = NULL;
1944                        opipe->nrbufs++;
1945                        ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
1946                        ipipe->nrbufs--;
1947                        input_wakeup = true;
1948                } else {
1949                        /*
1950                         * Get a reference to this pipe buffer,
1951                         * so we can copy the contents over.
1952                         */
1953                        ibuf->ops->get(ipipe, ibuf);
1954                        *obuf = *ibuf;
1955
1956                        /*
1957                         * Don't inherit the gift flag, we need to
1958                         * prevent multiple steals of this page.
1959                         */
1960                        obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1961
1962                        obuf->len = len;
1963                        opipe->nrbufs++;
1964                        ibuf->offset += obuf->len;
1965                        ibuf->len -= obuf->len;
1966                }
1967                ret += obuf->len;
1968                len -= obuf->len;
1969        } while (len);
1970
1971        pipe_unlock(ipipe);
1972        pipe_unlock(opipe);
1973
1974        /*
1975         * If we put data in the output pipe, wakeup any potential readers.
1976         */
1977        if (ret > 0)
1978                wakeup_pipe_readers(opipe);
1979
1980        if (input_wakeup)
1981                wakeup_pipe_writers(ipipe);
1982
1983        return ret;
1984}
1985
1986/*
1987 * Link contents of ipipe to opipe.
1988 */
1989static int link_pipe(struct pipe_inode_info *ipipe,
1990                     struct pipe_inode_info *opipe,
1991                     size_t len, unsigned int flags)
1992{
1993        struct pipe_buffer *ibuf, *obuf;
1994        int ret = 0, i = 0, nbuf;
1995
1996        /*
1997         * Potential ABBA deadlock, work around it by ordering lock
1998         * grabbing by pipe info address. Otherwise two different processes
1999         * could deadlock (one doing tee from A -> B, the other from B -> A).
2000         */
2001        pipe_double_lock(ipipe, opipe);
2002
2003        do {
2004                if (!opipe->readers) {
2005                        send_sig(SIGPIPE, current, 0);
2006                        if (!ret)
2007                                ret = -EPIPE;
2008                        break;
2009                }
2010
2011                /*
2012                 * If we have iterated all input buffers or ran out of
2013                 * output room, break.
2014                 */
2015                if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
2016                        break;
2017
2018                ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
2019                nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
2020
2021                /*
2022                 * Get a reference to this pipe buffer,
2023                 * so we can copy the contents over.
2024                 */
2025                ibuf->ops->get(ipipe, ibuf);
2026
2027                obuf = opipe->bufs + nbuf;
2028                *obuf = *ibuf;
2029
2030                /*
2031                 * Don't inherit the gift flag, we need to
2032                 * prevent multiple steals of this page.
2033                 */
2034                obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
2035
2036                if (obuf->len > len)
2037                        obuf->len = len;
2038
2039                opipe->nrbufs++;
2040                ret += obuf->len;
2041                len -= obuf->len;
2042                i++;
2043        } while (len);
2044
2045        /*
2046         * return EAGAIN if we have the potential of some data in the
2047         * future, otherwise just return 0
2048         */
2049        if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
2050                ret = -EAGAIN;
2051
2052        pipe_unlock(ipipe);
2053        pipe_unlock(opipe);
2054
2055        /*
2056         * If we put data in the output pipe, wakeup any potential readers.
2057         */
2058        if (ret > 0)
2059                wakeup_pipe_readers(opipe);
2060
2061        return ret;
2062}
2063
2064/*
2065 * This is a tee(1) implementation that works on pipes. It doesn't copy
2066 * any data, it simply references the 'in' pages on the 'out' pipe.
2067 * The 'flags' used are the SPLICE_F_* variants, currently the only
2068 * applicable one is SPLICE_F_NONBLOCK.
2069 */
2070static long do_tee(struct file *in, struct file *out, size_t len,
2071                   unsigned int flags)
2072{
2073        struct pipe_inode_info *ipipe = get_pipe_info(in);
2074        struct pipe_inode_info *opipe = get_pipe_info(out);
2075        int ret = -EINVAL;
2076
2077        /*
2078         * Duplicate the contents of ipipe to opipe without actually
2079         * copying the data.
2080         */
2081        if (ipipe && opipe && ipipe != opipe) {
2082                /*
2083                 * Keep going, unless we encounter an error. The ipipe/opipe
2084                 * ordering doesn't really matter.
2085                 */
2086                ret = ipipe_prep(ipipe, flags);
2087                if (!ret) {
2088                        ret = opipe_prep(opipe, flags);
2089                        if (!ret)
2090                                ret = link_pipe(ipipe, opipe, len, flags);
2091                }
2092        }
2093
2094        return ret;
2095}
2096
2097SYSCALL_DEFINE4(tee, int, fdin, int, fdout, size_t, len, unsigned int, flags)
2098{
2099        struct fd in;
2100        int error;
2101
2102        if (unlikely(!len))
2103                return 0;
2104
2105        error = -EBADF;
2106        in = fdget(fdin);
2107        if (in.file) {
2108                if (in.file->f_mode & FMODE_READ) {
2109                        struct fd out = fdget(fdout);
2110                        if (out.file) {
2111                                if (out.file->f_mode & FMODE_WRITE)
2112                                        error = do_tee(in.file, out.file,
2113                                                        len, flags);
2114                                fdput(out);
2115                        }
2116                }
2117                fdput(in);
2118        }
2119
2120        return error;
2121}
2122