tio.go 6.0 KB

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