Source file src/internal/poll/copy_file_range_unix.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build freebsd || linux
     6  
     7  package poll
     8  
     9  import (
    10  	"internal/syscall/unix"
    11  	"syscall"
    12  )
    13  
    14  // CopyFileRange copies at most remain bytes of data from src to dst, using
    15  // the copy_file_range system call. dst and src must refer to regular files.
    16  func CopyFileRange(dst, src *FD, remain int64) (written int64, handled bool, err error) {
    17  	if !supportCopyFileRange() {
    18  		return 0, false, nil
    19  	}
    20  
    21  	for remain > 0 {
    22  		max := remain
    23  		if max > maxCopyFileRangeRound {
    24  			max = maxCopyFileRangeRound
    25  		}
    26  		n, e := copyFileRange(dst, src, int(max))
    27  		if n > 0 {
    28  			remain -= n
    29  			written += n
    30  		}
    31  		handled, err = handleCopyFileRangeErr(e, n, written)
    32  		if n == 0 || !handled || err != nil {
    33  			return
    34  		}
    35  	}
    36  
    37  	return written, true, nil
    38  }
    39  
    40  // copyFileRange performs one round of copy_file_range(2).
    41  func copyFileRange(dst, src *FD, max int) (written int64, err error) {
    42  	// For Linux, the signature of copy_file_range(2) is:
    43  	//
    44  	// ssize_t copy_file_range(int fd_in, loff_t *off_in,
    45  	//                         int fd_out, loff_t *off_out,
    46  	//                         size_t len, unsigned int flags);
    47  	//
    48  	// For FreeBSD, the signature of copy_file_range(2) is:
    49  	//
    50  	// ssize_t
    51  	// copy_file_range(int infd, off_t *inoffp, int outfd, off_t *outoffp,
    52  	//                 size_t len, unsigned int flags);
    53  	//
    54  	// Note that in the call to unix.CopyFileRange below, we use nil
    55  	// values for off_in/off_out and inoffp/outoffp, which means "the file
    56  	// offset for infd(fd_in) or outfd(fd_out) respectively will be used and
    57  	// updated by the number of bytes copied".
    58  	//
    59  	// That is why we must acquire locks for both file descriptors (and why
    60  	// this whole machinery is in the internal/poll package to begin with).
    61  	if err := dst.writeLock(); err != nil {
    62  		return 0, err
    63  	}
    64  	defer dst.writeUnlock()
    65  	if err := src.readLock(); err != nil {
    66  		return 0, err
    67  	}
    68  	defer src.readUnlock()
    69  	var n int
    70  	for {
    71  		n, err = unix.CopyFileRange(src.Sysfd, nil, dst.Sysfd, nil, max, 0)
    72  		if err != syscall.EINTR {
    73  			break
    74  		}
    75  	}
    76  	return int64(n), err
    77  }
    78  

View as plain text