github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/internal/poll/sendfile_linux.go (about)

     1  // Copyright 2011 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  package poll
     6  
     7  import "syscall"
     8  
     9  // maxSendfileSize is the largest chunk size we ask the kernel to copy
    10  // at a time.
    11  const maxSendfileSize int = 4 << 20
    12  
    13  // SendFile wraps the sendfile system call.
    14  func SendFile(dstFD *FD, src int, remain int64) (written int64, err error, handled bool) {
    15  	if err := dstFD.writeLock(); err != nil {
    16  		return 0, err, false
    17  	}
    18  	defer dstFD.writeUnlock()
    19  
    20  	if err := dstFD.pd.prepareWrite(dstFD.isFile); err != nil {
    21  		return 0, err, false
    22  	}
    23  
    24  	dst := dstFD.Sysfd
    25  	for remain > 0 {
    26  		n := maxSendfileSize
    27  		if int64(n) > remain {
    28  			n = int(remain)
    29  		}
    30  		n, err = syscall.Sendfile(dst, src, nil, n)
    31  		if n > 0 {
    32  			written += int64(n)
    33  			remain -= int64(n)
    34  			continue
    35  		} else if err != syscall.EAGAIN && err != syscall.EINTR {
    36  			// This includes syscall.ENOSYS (no kernel
    37  			// support) and syscall.EINVAL (fd types which
    38  			// don't implement sendfile), and other errors.
    39  			// We should end the loop when there is no error
    40  			// returned from sendfile(2) or it is not a retryable error.
    41  			break
    42  		}
    43  		if err == syscall.EINTR {
    44  			continue
    45  		}
    46  		if err = dstFD.pd.waitWrite(dstFD.isFile); err != nil {
    47  			break
    48  		}
    49  	}
    50  	handled = written != 0 || (err != syscall.ENOSYS && err != syscall.EINVAL)
    51  	return
    52  }