...

Source file src/internal/poll/sendfile_bsd.go

Documentation: internal/poll

     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  //go:build darwin || dragonfly || freebsd
     6  
     7  package poll
     8  
     9  import "syscall"
    10  
    11  // maxSendfileSize is the largest chunk size we ask the kernel to copy
    12  // at a time.
    13  const maxSendfileSize int = 4 << 20
    14  
    15  // SendFile wraps the sendfile system call.
    16  func SendFile(dstFD *FD, src int, pos, remain int64) (written int64, err error, handled bool) {
    17  	defer func() {
    18  		TestHookDidSendFile(dstFD, src, written, err, handled)
    19  	}()
    20  	if err := dstFD.writeLock(); err != nil {
    21  		return 0, err, false
    22  	}
    23  	defer dstFD.writeUnlock()
    24  
    25  	if err := dstFD.pd.prepareWrite(dstFD.isFile); err != nil {
    26  		return 0, err, false
    27  	}
    28  
    29  	dst := dstFD.Sysfd
    30  	for remain > 0 {
    31  		n := maxSendfileSize
    32  		if int64(n) > remain {
    33  			n = int(remain)
    34  		}
    35  		m := n
    36  		pos1 := pos
    37  		n, err = syscall.Sendfile(dst, src, &pos1, n)
    38  		if n > 0 {
    39  			pos += int64(n)
    40  			written += int64(n)
    41  			remain -= int64(n)
    42  			// (n, nil) indicates that sendfile(2) has transferred
    43  			// the exact number of bytes we requested, or some unretryable
    44  			// error have occurred with partial bytes sent. Either way, we
    45  			// don't need to go through the following logic to check EINTR
    46  			// or fell into dstFD.pd.waitWrite, just continue to send the
    47  			// next chunk or break the loop.
    48  			if n == m {
    49  				continue
    50  			} else if err != syscall.EAGAIN &&
    51  				err != syscall.EINTR &&
    52  				err != syscall.EBUSY {
    53  				// Particularly, EPIPE. Errors like that would normally lead
    54  				// the subsequent sendfile(2) call to (-1, EBADF).
    55  				break
    56  			}
    57  		} else if err != syscall.EAGAIN && err != syscall.EINTR {
    58  			// This includes syscall.ENOSYS (no kernel
    59  			// support) and syscall.EINVAL (fd types which
    60  			// don't implement sendfile), and other errors.
    61  			// We should end the loop when there is no error
    62  			// returned from sendfile(2) or it is not a retryable error.
    63  			break
    64  		}
    65  		if err == syscall.EINTR {
    66  			continue
    67  		}
    68  		if err = dstFD.pd.waitWrite(dstFD.isFile); err != nil {
    69  			break
    70  		}
    71  	}
    72  	if err == syscall.EAGAIN {
    73  		err = nil
    74  	}
    75  	handled = written != 0 || (err != syscall.ENOSYS && err != syscall.EINVAL)
    76  	return
    77  }
    78  

View as plain text