// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build freebsd || linux

package poll

import 

// CopyFileRange copies at most remain bytes of data from src to dst, using
// the copy_file_range system call. dst and src must refer to regular files.
func (,  *FD,  int64) ( int64,  bool,  error) {
	if !supportCopyFileRange() {
		return 0, false, nil
	}

	for  > 0 {
		 := 
		if  > maxCopyFileRangeRound {
			 = maxCopyFileRangeRound
		}
		,  := copyFileRange(, , int())
		if  > 0 {
			 -= 
			 += 
		}
		,  = handleCopyFileRangeErr(, , )
		if  == 0 || ! ||  != nil {
			return
		}
	}

	return , true, nil
}

// copyFileRange performs one round of copy_file_range(2).
func copyFileRange(,  *FD,  int) ( int64,  error) {
	// For Linux, the signature of copy_file_range(2) is:
	//
	// ssize_t copy_file_range(int fd_in, loff_t *off_in,
	//                         int fd_out, loff_t *off_out,
	//                         size_t len, unsigned int flags);
	//
	// For FreeBSD, the signature of copy_file_range(2) is:
	//
	// ssize_t
	// copy_file_range(int infd, off_t *inoffp, int outfd, off_t *outoffp,
	//                 size_t len, unsigned int flags);
	//
	// Note that in the call to unix.CopyFileRange below, we use nil
	// values for off_in/off_out and inoffp/outoffp, which means "the file
	// offset for infd(fd_in) or outfd(fd_out) respectively will be used and
	// updated by the number of bytes copied".
	//
	// That is why we must acquire locks for both file descriptors (and why
	// this whole machinery is in the internal/poll package to begin with).
	if  := .writeLock();  != nil {
		return 0, 
	}
	defer .writeUnlock()
	if  := .readLock();  != nil {
		return 0, 
	}
	defer .readUnlock()
	return ignoringEINTR2(func() (int64, error) {
		,  := unix.CopyFileRange(.Sysfd, nil, .Sysfd, nil, , 0)
		return int64(), 
	})
}