raw_sendmmsg_linux.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package udp
  4. import (
  5. "net"
  6. "syscall"
  7. "unsafe"
  8. "golang.org/x/sys/unix"
  9. )
  10. // rawSendmmsg performs sendmmsg(2) over a syscall.RawConn without
  11. // allocating a closure per call. The struct holds preallocated in/out
  12. // scratch (chunk/sent/errno) and a method-value bound at construction so
  13. // rawConn.Write receives a stable function pointer instead of a fresh
  14. // closure on every send.
  15. type rawSendmmsg struct {
  16. msgs []rawMessage
  17. chunk int
  18. sent int
  19. errno syscall.Errno
  20. callback func(fd uintptr) bool
  21. }
  22. // bind wires r.callback to r.run. Must be called once after r.msgs is set;
  23. // subsequent send calls invoke r.callback without rebinding.
  24. func (r *rawSendmmsg) bind() { r.callback = r.run }
  25. // run is the preallocated callback rawConn.Write invokes. It reads its
  26. // input (r.chunk) and writes its outputs (r.sent, r.errno) through the
  27. // rawSendmmsg fields so the method value does not capture per-call locals
  28. // and therefore does not heap-allocate.
  29. func (r *rawSendmmsg) run(fd uintptr) bool {
  30. r1, _, errno := unix.Syscall6(unix.SYS_SENDMMSG, fd,
  31. uintptr(unsafe.Pointer(&r.msgs[0])), uintptr(r.chunk),
  32. 0, 0, 0,
  33. )
  34. if errno == syscall.EAGAIN || errno == syscall.EWOULDBLOCK {
  35. return false
  36. }
  37. r.sent = int(r1)
  38. r.errno = errno
  39. return true
  40. }
  41. // send issues sendmmsg over rc against the first n entries of r.msgs.
  42. // Returns the number of entries the kernel processed and any error;
  43. // matches the original sendmmsg helper's contract.
  44. func (r *rawSendmmsg) send(rc syscall.RawConn, n int) (int, error) {
  45. r.chunk = n
  46. r.sent = 0
  47. r.errno = 0
  48. if err := rc.Write(r.callback); err != nil {
  49. return r.sent, err
  50. }
  51. if r.errno != 0 {
  52. return r.sent, &net.OpError{Op: "sendmmsg", Err: r.errno}
  53. }
  54. return r.sent, nil
  55. }