Walk the control buffer by hand instead of allocating a message list per frame

This commit is contained in:
flamingcow
2026-08-04 20:48:17 -07:00
parent 1d54a1a1f6
commit ce44fe9866
2 changed files with 121 additions and 12 deletions
+22 -12
View File
@@ -80,21 +80,31 @@ func enableRxTimestamps(fd int) error {
// means the mac did not produce a stamp.
const scmTimestampingLen = 3 * int(unsafe.Sizeof(unix.Timespec{}))
// A control message's payload starts at its header rounded up to a pointer, and
// the next starts at its length rounded up the same way.
const (
cmsgAlignMask = unix.SizeofPtr - 1
cmsgDataOff = (unix.SizeofCmsghdr + cmsgAlignMask) &^ cmsgAlignMask
)
// Walked by hand rather than through ParseSocketControlMessage, which allocates
// per call on a path that runs for every frame received.
func hwTimestamp(oob []byte) (int64, bool) {
msgs, err := unix.ParseSocketControlMessage(oob)
if err != nil {
return 0, false
}
for _, m := range msgs {
if m.Header.Level != unix.SOL_SOCKET || m.Header.Type != unix.SCM_TIMESTAMPING {
continue
}
if len(m.Data) < scmTimestampingLen {
for off := 0; off+unix.SizeofCmsghdr <= len(oob); {
h := (*unix.Cmsghdr)(unsafe.Pointer(&oob[off]))
n := int(h.Len)
if n < unix.SizeofCmsghdr || off+n > len(oob) {
return 0, false
}
ts := (*[3]unix.Timespec)(unsafe.Pointer(&m.Data[0]))
ns := ts[2].Nano()
return ns, ns != 0
if h.Level == unix.SOL_SOCKET && h.Type == unix.SCM_TIMESTAMPING {
if cmsgDataOff+scmTimestampingLen > n {
return 0, false
}
ts := (*[3]unix.Timespec)(unsafe.Pointer(&oob[off+cmsgDataOff]))
ns := ts[2].Nano()
return ns, ns != 0
}
off += (n + cmsgAlignMask) &^ cmsgAlignMask
}
return 0, false
}