udp_linux_writebatch.go 13 KB

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