tio.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package tio
  2. import (
  3. "io"
  4. )
  5. // QueueSet holds one or many Queue objects and helps close them in an orderly way.
  6. type QueueSet interface {
  7. io.Closer
  8. // Shutdown wakes every reader without releasing any fds, Close only once they have exited
  9. Shutdown() error
  10. Queues() []Queue
  11. // Add takes a tun fd, adds it to the set, and prepares it for use as a Queue.
  12. Add(fd int) error
  13. }
  14. // Capabilities advertises which kernel offload features a Queue successfully negotiated.
  15. // Callers consult this to decide which coalescers to wire onto the write path.
  16. type Capabilities struct {
  17. // TSO means the FD was opened with IFF_VNET_HDR and the kernel agreed to TUN_F_TSO4|TSO6,
  18. // and WriteGSO with GSOProtoTCP is safe.
  19. TSO bool
  20. // USO means the kernel additionally agreed to TUN_F_USO4|USO6,
  21. // so WriteGSO with GSOProtoUDP is safe. Linux ≥ 6.2.
  22. USO bool
  23. }
  24. // Queue is a readable/writable Poll queue.
  25. // Concurrency contract: a single read goroutine drives Read; plain Write is safe for concurrent callers;
  26. // WriteGSO (on Queues that implement GSOWriter) is single-writer per queue.
  27. //
  28. // Close on an individual Queue does NOT unblock a Read parked in poll — closing an fd
  29. // never wakes its pollers. Orderly teardown goes through the owning QueueSet's Close,
  30. // which first signals a shared shutdown eventfd every reader polls alongside its own fd.
  31. // That eventfd is a set-wide kill switch: once signaled, every Queue in the set returns
  32. // os.ErrClosed from Read, so it cannot be used to stop a single Queue.
  33. type Queue interface {
  34. io.Closer
  35. // Read returns one or more packets.
  36. // The returned Packet.Bytes slices are borrowed from the Queue's internal buffer and are only valid
  37. // until the next Read or Close on this Queue.
  38. // A Packet may carry a GSO/USO superpacket (see GSOInfo)
  39. // Single-reader only: not safe for concurrent Reads (it reuses per-queue rx scratch each call).
  40. Read() ([]Packet, error)
  41. // Write emits a single packet on the plaintext (outside→inside) delivery path.
  42. // Safe for concurrent use.
  43. Write(p []byte) (int, error)
  44. }
  45. // Packet is the unit Queue.Read returns.
  46. // Bytes points into the queue's internal buffer and is only valid until the next Read or Close on the queue that produced it.
  47. // GSO is the zero value for an already-segmented IP datagram;
  48. // when non-zero it describes a kernel-supplied TSO/USO superpacket the caller must segment before consuming.
  49. type Packet struct {
  50. Bytes []byte
  51. GSO GSOInfo
  52. }
  53. // GSOInfo describes a kernel-supplied superpacket sitting in Packet.Bytes.
  54. // The zero value means Bytes is one regular IP datagram and no segmentation is required.
  55. type GSOInfo struct {
  56. // Size is the GSO segment size: max payload bytes per segment
  57. // (== TCP MSS for TSO, == UDP payload chunk for USO). Zero means not a superpacket.
  58. Size uint16
  59. // HdrLen is the total L3+L4 header length within Bytes (already corrected via correctHdrLen, so safe to slice on).
  60. HdrLen uint16
  61. // CsumStart is the L4 header offset inside Bytes (== L3 header length).
  62. CsumStart uint16
  63. // Proto picks the L4 protocol (TCP or UDP) so the segmenter knows which checksum/header layout to apply.
  64. Proto GSOProto
  65. }
  66. // IsSuperpacket reports whether g describes a multi-segment GSO/USO
  67. // superpacket that needs segmentation before its bytes can be encrypted and sent on the wire.
  68. func (g GSOInfo) IsSuperpacket() bool { return g.Size > 0 }
  69. // Clone returns a Packet whose Bytes is a freshly allocated copy of p.Bytes,
  70. // safe to retain past the next Read or Close on the originating Queue.
  71. // GSO metadata is copied verbatim.
  72. // Use this only when a caller needs the data to outlive the borrowed-slice contract.
  73. func (p Packet) Clone() Packet {
  74. if p.Bytes == nil {
  75. return p
  76. }
  77. cp := make([]byte, len(p.Bytes))
  78. copy(cp, p.Bytes)
  79. return Packet{Bytes: cp, GSO: p.GSO}
  80. }
  81. // CapsProvider is an optional interface implemented by Queues that negotiate kernel offload features at open time.
  82. // Callers pick a write-path coalescer based on the result.
  83. // Queues that don't implement it are treated as having no offload capability.
  84. type CapsProvider interface {
  85. Capabilities() Capabilities
  86. }
  87. // GSOProto selects the L4 protocol for a GSO superpacket.
  88. // Determines which VIRTIO_NET_HDR_GSO_* type the writer stamps and which checksum offset
  89. // inside the transport header virtio NEEDS_CSUM expects.
  90. type GSOProto uint8
  91. const (
  92. GSOProtoUnknown GSOProto = iota
  93. GSOProtoTCP
  94. GSOProtoUDP
  95. )
  96. // GSOWriter is implemented by Queues that can emit a TCP or UDP superpacket
  97. // assembled from a header prefix plus one or more borrowed payload fragments,
  98. // in a single vectored write (writev with a leading virtio_net_hdr).
  99. // This lets the coalescer avoid copying payload bytes between the caller's decrypt buffer and the TUN.
  100. // Backends without GSO support do not implement this interface and coalescing is skipped.
  101. //
  102. // hdr contains the IPv4/IPv6 header prefix (mutable: callers will have filled in total length and IP csum).
  103. // transportHdr is the TCP or UDP header
  104. // (mutable: the L4 checksum field must hold the pseudo-header partial, single-fold not inverted, per virtio NEEDS_CSUM semantics).
  105. // pays are non-overlapping payload fragments whose concatenation is the full superpacket payload.
  106. // They are read-only from the writer's perspective and must remain valid until the call returns.
  107. // Every segment in pays except possibly the last must be exactly the same size.
  108. // proto picks the L4 protocol so the writer knows which gsoType / CsumOffset to set.
  109. //
  110. // Callers should also consult CapsProvider (via SupportsGSO) for the per-protocol negotiated capability:
  111. // USO may not have been negotiated even when TSO was.
  112. type GSOWriter interface {
  113. io.Writer
  114. CapsProvider
  115. WriteGSO(hdr []byte, transportHdr []byte, pays [][]byte, proto GSOProto) error
  116. }
  117. // SupportsGSO reports whether w implements GSOWriter and the underlying
  118. // queue advertises the negotiated capability for `want`.
  119. func SupportsGSO(w io.Writer, want GSOProto) (GSOWriter, bool) {
  120. gw, ok := w.(GSOWriter)
  121. if !ok {
  122. return nil, false
  123. }
  124. caps := gw.Capabilities()
  125. switch want {
  126. case GSOProtoTCP:
  127. return gw, caps.TSO
  128. case GSOProtoUDP:
  129. return gw, caps.USO
  130. default:
  131. return gw, false
  132. }
  133. }