udp_linux_writebatch.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. //go:build linux && !android && !e2e_testing
  2. package udp
  3. import (
  4. "context"
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "net"
  10. "net/netip"
  11. "strconv"
  12. "strings"
  13. "unsafe"
  14. "golang.org/x/sys/unix"
  15. )
  16. // batchWriter owns the sendmmsg(2)/UDP-GSO transmit path for a StdConn: the
  17. // scratch WriteBatch packs mmsghdr entries into, plus the GSO capability
  18. // state probed at socket creation. Each queue has its own StdConn and
  19. // batchWriter, so no locking is needed.
  20. //
  21. // Terminology, smallest to largest:
  22. //
  23. // packet one element of bufs: a single UDP datagram. The unit of the
  24. // returned written count.
  25. // run consecutive packets planRun groups into one entry: same
  26. // destination, equal sizes (a shorter packet only last), within
  27. // maxGSOBytes and maxGSOSegments. Without GSO a run is always one
  28. // packet. Runs are atomic: packed whole into one entry, or
  29. // skipped whole if the socket cannot address their destination,
  30. // leaving a hole (bufs indices covered by no entry).
  31. // entry one mmsghdr slot of the sendmmsg array; the kernel's unit of
  32. // success and failure. A multi-packet entry carries a UDP_SEGMENT
  33. // cmsg and is sent as one superpacket the kernel segments into
  34. // gso_size-byte datagrams. Entries never split.
  35. // chunk the entries packed for one sendmmsg call, at most MaxWriteBatch.
  36. // batch the caller's whole bufs/addrs pair, processed as one or more chunks.
  37. type batchWriter struct {
  38. fd int
  39. isV4 bool
  40. // UDP GSO (sendmsg with UDP_SEGMENT cmsg) support, probed once at
  41. // socket creation and cleared by WriteBatch if the kernel later rejects
  42. // a GSO send (the setsockopt probe cannot see per-route limitations).
  43. // When true, WriteBatch coalesces runs into UDP_SEGMENT entries;
  44. // otherwise each packet is its own entry.
  45. gsoSupported bool
  46. maxGSOSegments int
  47. // sendmmsg scratch, sized to MaxWriteBatch at construction; WriteBatch
  48. // chunks larger inputs.
  49. msgs []rawMessage
  50. iovs []iovec
  51. names [][]byte
  52. l *slog.Logger
  53. // sendFn sends n prepared entries beginning at w.msgs[start]
  54. // This is a function pointer to facilitate testing.
  55. sendFn func(start, n int) (int, error)
  56. // Per-entry cmsg scratch: one contiguous slab of
  57. // MaxWriteBatch * cmsgSpace bytes holding one UDP_SEGMENT cmsg per entry.
  58. cmsg []byte
  59. cmsgSpace int
  60. // entryEnd[e] is the bufs index after the last packet packed into entry e.
  61. // entryEnd[e]-entryPkts[e] recovers the bufs index the entry's run started at,
  62. // used to rewind i for the GSO-disable replay.
  63. entryEnd []int
  64. // entryPkts[e] is the number of packets packed into entry e.
  65. entryPkts []int
  66. }
  67. func newBatchWriter(fd int, isV4 bool, l *slog.Logger, offloadsEnabled bool) *batchWriter {
  68. w := &batchWriter{fd: fd, isV4: isV4, l: l}
  69. w.sendFn = w.sendmmsg
  70. if offloadsEnabled {
  71. w.prepareGSO()
  72. }
  73. w.prepareWriteMessages(MaxWriteBatch, offloadsEnabled)
  74. return w
  75. }
  76. // prepareWriteMessages allocates the per-entry mmsghdr/iovec/sockaddr/cmsg
  77. // scratch. Hdr.Iov/Iovlen/Control/Controllen are wired per call, since an
  78. // entry spans a variable number of iovecs and may or may not carry a cmsg.
  79. //
  80. // Each entry's cmsg slot holds one UDP_SEGMENT (gso_size, uint16) header,
  81. // pre-filled here; only its payload is rewritten per call.
  82. // Hdr.Control/Controllen select whether it applies (none / segment).
  83. func (w *batchWriter) prepareWriteMessages(n int, offloadsEnabled bool) {
  84. w.msgs = make([]rawMessage, n)
  85. w.iovs = make([]iovec, n)
  86. w.names = make([][]byte, n)
  87. w.entryEnd = make([]int, n)
  88. w.entryPkts = make([]int, n)
  89. w.cmsgSpace = unix.CmsgSpace(2)
  90. for i := range w.msgs {
  91. w.names[i] = make([]byte, unix.SizeofSockaddrInet6)
  92. w.msgs[i].Hdr.Name = &w.names[i][0]
  93. }
  94. if !offloadsEnabled || !w.gsoSupported {
  95. return //avoid allocating cmsg space if we will never use it
  96. }
  97. w.cmsg = make([]byte, n*w.cmsgSpace)
  98. for k := 0; k < n; k++ {
  99. base := k * w.cmsgSpace
  100. seg := (*unix.Cmsghdr)(unsafe.Pointer(&w.cmsg[base]))
  101. seg.Level = unix.SOL_UDP
  102. seg.Type = unix.UDP_SEGMENT
  103. setCmsgLen(seg, unix.CmsgLen(2))
  104. }
  105. }
  106. // maxGSOBytes bounds the total payload of one UDP_SEGMENT send. The kernel
  107. // builds a single skb, which must fit the 16-bit UDP length field and
  108. // sk_gso_max_size (65536 on most devices); 65000 leaves headroom for headers.
  109. const maxGSOBytes = 65000
  110. // prepareGSO probes UDP_SEGMENT support and sets w.gsoSupported on success.
  111. // Best-effort; failure leaves it false.
  112. func (w *batchWriter) prepareGSO() {
  113. w.maxGSOSegments = 63 // pre-6.9 cap; see gsoMaxSegments
  114. if err := unix.SetsockoptInt(w.fd, unix.IPPROTO_UDP, unix.UDP_SEGMENT, 0); err != nil {
  115. w.l.Info("udp: GSO disabled", "reason", "rawconn control failed", "error", err)
  116. recordCapability("udp.gso.enabled", false)
  117. return
  118. }
  119. var un unix.Utsname
  120. if err := unix.Uname(&un); err != nil {
  121. w.l.Warn("udp: kernel version probe failed, capping GSO at 63 segments", "error", err)
  122. } else {
  123. w.maxGSOSegments = gsoMaxSegments(string(un.Release[:]))
  124. }
  125. w.gsoSupported = true
  126. w.l.Info("udp: GSO enabled", "maxGSOSegments", w.maxGSOSegments)
  127. recordCapability("udp.gso.enabled", true)
  128. }
  129. // gsoMaxSegments returns the most segments one UDP_SEGMENT send may carry:
  130. // the kernel cap (UDP_MAX_SEGMENTS: 64 before 6.9, 128 after) minus one,
  131. // because the kernel counts the 8-byte UDP header against the gso_size * UDP_MAX_SEGMENTS budget.
  132. func gsoMaxSegments(release string) int {
  133. major, minor := parseRelease(release)
  134. if major > 6 || (major == 6 && minor >= 9) {
  135. return 127
  136. }
  137. return 63
  138. }
  139. func parseRelease(r string) (major, minor int) {
  140. // strip anything after the second dot or any non-digit
  141. parts := strings.SplitN(r, ".", 3)
  142. if len(parts) < 2 {
  143. return 0, 0
  144. }
  145. major, _ = strconv.Atoi(parts[0])
  146. // minor may have trailing junk like "15-generic"
  147. mp := parts[1]
  148. for i, c := range mp {
  149. if c < '0' || c > '9' {
  150. mp = mp[:i]
  151. break
  152. }
  153. }
  154. minor, _ = strconv.Atoi(mp)
  155. return
  156. }
  157. // WriteBatch sends bufs via sendmmsg(2), coalescing runs into UDP_SEGMENT
  158. // entries, so one syscall can mix GSO superpackets and plain datagrams.
  159. // Without GSO support every packet is its own entry.
  160. // Callers shall deliver same-destination packets contiguously and in counter order
  161. //
  162. // Batches larger than the scratch take one sendmmsg per chunk.
  163. // A partial success resumes the same prepared entries at the first unsent entry.
  164. // A zero-sent error means the kernel rejected the first remaining entry:
  165. // its packets are dropped and the rest of the chunk resumes in place.
  166. //
  167. // Returns the number of packets sent. An error means the call itself failed.
  168. // A short count means some destinations were undeliverable.
  169. func (w *batchWriter) WriteBatch(bufs [][]byte, addrs []netip.AddrPort) (int, error) {
  170. if len(bufs) != len(addrs) {
  171. return 0, fmt.Errorf("WriteBatch: len(bufs)=%d != len(addrs)=%d", len(bufs), len(addrs))
  172. }
  173. // A destination the kernel rejects results in us dropping that entry (one packet, or one same-destination GSO run).
  174. // We count what actually made it out rather than returning an error.
  175. written := 0
  176. i := 0
  177. for i < len(bufs) {
  178. entry := 0
  179. iovIdx := 0
  180. for entry < len(w.msgs) && i < len(bufs) {
  181. iovBudget := len(w.iovs) - iovIdx
  182. if iovBudget < 1 {
  183. break
  184. }
  185. runLen, segSize := w.planRun(bufs, addrs, i, iovBudget)
  186. if runLen == 0 {
  187. break
  188. }
  189. for k := 0; k < runLen; k++ {
  190. b := bufs[i+k]
  191. if len(b) == 0 {
  192. w.iovs[iovIdx+k].Base = nil
  193. setIovLen(&w.iovs[iovIdx+k], 0)
  194. } else {
  195. w.iovs[iovIdx+k].Base = &b[0]
  196. setIovLen(&w.iovs[iovIdx+k], len(b))
  197. }
  198. }
  199. nlen, err := writeSockaddr(w.names[entry], addrs[i], w.isV4)
  200. if err != nil {
  201. // The destination's address family does not match the socket
  202. // (e.g. an IPv6 remote on a v4-bound socket). The packets are
  203. // undeliverable and no entry is committed yet: skip the run.
  204. if w.l.Enabled(context.Background(), slog.LevelDebug) {
  205. w.l.Debug("skipping unroutable batch destination", "udpAddr", addrs[i], "packets", runLen, "error", err)
  206. }
  207. i += runLen
  208. continue
  209. }
  210. hdr := &w.msgs[entry].Hdr
  211. hdr.Iov = &w.iovs[iovIdx]
  212. setMsgIovlen(hdr, runLen)
  213. hdr.Namelen = uint32(nlen)
  214. w.writeEntryCmsg(entry, runLen, segSize)
  215. i += runLen
  216. iovIdx += runLen
  217. w.entryEnd[entry] = i
  218. w.entryPkts[entry] = runLen
  219. entry++
  220. }
  221. if entry == 0 {
  222. // Every remaining packet was skipped; i reached len(bufs).
  223. break
  224. }
  225. // Drain the packed entries without repacking: everything the packing
  226. // loop wired (iovecs, names, cmsgs) stays intact until the next chunk
  227. // overwrites it, so a partial success resumes the same sendmmsg array
  228. // at the first unsent entry, and a rejected entry is skipped in place.
  229. // Only the GSO-disable path replans, since its entries change shape.
  230. done := 0
  231. for done < entry {
  232. sent, serr := w.sendFn(done, entry-done)
  233. if sent > 0 {
  234. // Count packets per entry; the bufs index span would
  235. // overcount across holes left by skipped runs.
  236. for e := done; e < done+sent; e++ {
  237. written += w.entryPkts[e]
  238. }
  239. done += sent
  240. continue
  241. }
  242. if serr == nil {
  243. return written, fmt.Errorf("sendmmsg made no progress")
  244. }
  245. // sent<=0 means the first remaining entry itself failed.
  246. // EIO on a superpacket means the route cannot carry a GSO send even though the setsockopt probe passed:
  247. // udp_send_skb() returns EIO when:
  248. // * the egress device lacks TX checksum offload (kernels through 6.10)
  249. // * or when an xfrm policy covers the route.
  250. // Persistent, so disable GSO and replay from the failed run as one-packet entries.
  251. if w.gsoSupported && w.entryPkts[done] >= 2 && errors.Is(serr, unix.EIO) {
  252. w.gsoSupported = false
  253. w.l.Warn("udp: kernel rejected GSO send, disabling GSO", "error", serr)
  254. recordCapability("udp.gso.enabled", false)
  255. i = w.entryEnd[done] - w.entryPkts[done]
  256. break
  257. }
  258. // Any other zero-sent error is a per-entry failure.
  259. // Transient errnos (EINTR, ENOBUFS) were already retried inside sendFn.
  260. // These packets are doomed. Log them and move on.
  261. if w.l.Enabled(context.Background(), slog.LevelDebug) {
  262. w.l.Debug("sendmmsg rejected entry",
  263. "error", serr,
  264. "udpAddr", addrs[w.entryEnd[done]-w.entryPkts[done]],
  265. "packets", w.entryPkts[done],
  266. "gso", w.gsoSupported,
  267. )
  268. }
  269. done++
  270. }
  271. }
  272. return written, nil
  273. }
  274. // planRun returns the length of the run starting at start and its segment
  275. // size (len(bufs[start])). A run of length 1 carries no UDP_SEGMENT cmsg
  276. // and is sent as a plain datagram; without GSO support planRun always returns 1.
  277. func (w *batchWriter) planRun(bufs [][]byte, addrs []netip.AddrPort, start, iovBudget int) (int, int) {
  278. if start >= len(bufs) || iovBudget < 1 {
  279. return 0, 0
  280. }
  281. segSize := len(bufs[start])
  282. if !w.gsoSupported || segSize == 0 || segSize > maxGSOBytes {
  283. return 1, segSize
  284. }
  285. dst := addrs[start]
  286. maxLen := w.maxGSOSegments
  287. if iovBudget < maxLen {
  288. maxLen = iovBudget
  289. }
  290. runLen := 1
  291. total := segSize
  292. for runLen < maxLen && start+runLen < len(bufs) {
  293. nextLen := len(bufs[start+runLen])
  294. if nextLen == 0 || nextLen > segSize {
  295. break
  296. }
  297. if addrs[start+runLen] != dst {
  298. break
  299. }
  300. if total+nextLen > maxGSOBytes {
  301. break
  302. }
  303. total += nextLen
  304. runLen++
  305. if nextLen < segSize {
  306. // A short packet must be the last in the run.
  307. break
  308. }
  309. }
  310. return runLen, segSize
  311. }
  312. // writeEntryCmsg writes one entry's UDP_SEGMENT payload when runLen >= 2 and
  313. // points Hdr.Control at it; a single-packet entry carries no cmsg.
  314. func (w *batchWriter) writeEntryCmsg(entry, runLen, segSize int) {
  315. hdr := &w.msgs[entry].Hdr
  316. base := entry * w.cmsgSpace
  317. if runLen >= 2 {
  318. dataOff := base + unix.CmsgLen(0)
  319. binary.NativeEndian.PutUint16(w.cmsg[dataOff:dataOff+2], uint16(segSize))
  320. hdr.Control = &w.cmsg[base]
  321. setMsgControllen(hdr, w.cmsgSpace)
  322. } else {
  323. hdr.Control = nil
  324. setMsgControllen(hdr, 0)
  325. }
  326. }
  327. // sendmmsg issues sendmmsg(2) against n entries of w.msgs starting at start.
  328. //
  329. // EINTR is automatically retried and will never be returned.
  330. // ENOBUFS is retried enobufsRetries times, and should be treated like any other error
  331. func (w *batchWriter) sendmmsg(start, n int) (int, error) {
  332. const enobufsRetries = 3
  333. for enobufs := 0; ; {
  334. r1, _, errno := unix.Syscall6(unix.SYS_SENDMMSG, uintptr(w.fd),
  335. uintptr(unsafe.Pointer(&w.msgs[start])), uintptr(n),
  336. 0, 0, 0,
  337. )
  338. switch {
  339. case errno == unix.EINTR: //similar to stdlib's ignoringEINTRIO
  340. continue
  341. case errno == unix.ENOBUFS && enobufs < enobufsRetries:
  342. enobufs++ //worth a retry or three
  343. continue
  344. case errno != 0:
  345. return int(r1), &net.OpError{Op: "sendmmsg", Err: errno}
  346. }
  347. return int(r1), nil
  348. }
  349. }