github.com/JimmyHuang454/JLS-go@v0.0.0-20230831150107-90d536585ba0/internal/poll/sendfile_solaris.go (about)

     1  // Copyright 2015 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  // Not strictly needed, but very helpful for debugging, see issue #10221.
    10  //
    11  //go:cgo_import_dynamic _ _ "libsendfile.so"
    12  //go:cgo_import_dynamic _ _ "libsocket.so"
    13  
    14  // maxSendfileSize is the largest chunk size we ask the kernel to copy
    15  // at a time.
    16  const maxSendfileSize int = 4 << 20
    17  
    18  // SendFile wraps the sendfile system call.
    19  func SendFile(dstFD *FD, src int, pos, remain int64) (int64, error) {
    20  	if err := dstFD.writeLock(); err != nil {
    21  		return 0, err
    22  	}
    23  	defer dstFD.writeUnlock()
    24  	if err := dstFD.pd.prepareWrite(dstFD.isFile); err != nil {
    25  		return 0, err
    26  	}
    27  
    28  	dst := dstFD.Sysfd
    29  	var written int64
    30  	var err error
    31  	for remain > 0 {
    32  		n := maxSendfileSize
    33  		if int64(n) > remain {
    34  			n = int(remain)
    35  		}
    36  		pos1 := pos
    37  		n, err1 := syscall.Sendfile(dst, src, &pos1, n)
    38  		if err1 == syscall.EAGAIN || err1 == syscall.EINTR {
    39  			// partial write may have occurred
    40  			n = int(pos1 - pos)
    41  		}
    42  		if n > 0 {
    43  			pos += int64(n)
    44  			written += int64(n)
    45  			remain -= int64(n)
    46  		} else if n == 0 && err1 == nil {
    47  			break
    48  		}
    49  		if err1 == syscall.EAGAIN {
    50  			if err1 = dstFD.pd.waitWrite(dstFD.isFile); err1 == nil {
    51  				continue
    52  			}
    53  		}
    54  		if err1 == syscall.EINTR {
    55  			continue
    56  		}
    57  		if err1 != nil {
    58  			// This includes syscall.ENOSYS (no kernel
    59  			// support) and syscall.EINVAL (fd types which
    60  			// don't implement sendfile)
    61  			err = err1
    62  			break
    63  		}
    64  	}
    65  	return written, err
    66  }