github.com/ttpreport/gvisor-ligolo@v0.0.0-20240123134145-a858404967ba/pkg/tcpip/link/xdp/endpoint.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //go:build linux 16 // +build linux 17 18 // Package xdp provides link layer endpoints backed by AF_XDP sockets. 19 package xdp 20 21 import ( 22 "fmt" 23 24 "github.com/ttpreport/gvisor-ligolo/pkg/buffer" 25 "github.com/ttpreport/gvisor-ligolo/pkg/sync" 26 "github.com/ttpreport/gvisor-ligolo/pkg/tcpip" 27 "github.com/ttpreport/gvisor-ligolo/pkg/tcpip/header" 28 "github.com/ttpreport/gvisor-ligolo/pkg/tcpip/link/qdisc/fifo" 29 "github.com/ttpreport/gvisor-ligolo/pkg/tcpip/link/rawfile" 30 "github.com/ttpreport/gvisor-ligolo/pkg/tcpip/link/stopfd" 31 "github.com/ttpreport/gvisor-ligolo/pkg/tcpip/stack" 32 "github.com/ttpreport/gvisor-ligolo/pkg/xdp" 33 "golang.org/x/sys/unix" 34 ) 35 36 // TODO(b/240191988): Turn off GSO, GRO, and LRO. Limit veth MTU to 1500. 37 38 // MTU is sized to ensure packets fit inside a 2048 byte XDP frame. 39 const MTU = 1500 40 41 var _ stack.LinkEndpoint = (*endpoint)(nil) 42 43 type endpoint struct { 44 // fd is the underlying AF_XDP socket. 45 fd int 46 47 // addr is the address of the endpoint. 48 addr tcpip.LinkAddress 49 50 // caps holds the endpoint capabilities. 51 caps stack.LinkEndpointCapabilities 52 53 // closed is a function to be called when the FD's peer (if any) closes 54 // its end of the communication pipe. 55 closed func(tcpip.Error) 56 57 mu sync.RWMutex 58 // +checkloks:mu 59 networkDispatcher stack.NetworkDispatcher 60 61 // wg keeps track of running goroutines. 62 wg sync.WaitGroup 63 64 // control is used to control the AF_XDP socket. 65 control *xdp.ControlBlock 66 67 // stopFD is used to stop the dispatch loop. 68 stopFD stopfd.StopFD 69 } 70 71 // Options specify the details about the fd-based endpoint to be created. 72 type Options struct { 73 // FD is used to read/write packets. 74 FD int 75 76 // ClosedFunc is a function to be called when an endpoint's peer (if 77 // any) closes its end of the communication pipe. 78 ClosedFunc func(tcpip.Error) 79 80 // Address is the link address for this endpoint. 81 Address tcpip.LinkAddress 82 83 // SaveRestore if true, indicates that this NIC capability set should 84 // include CapabilitySaveRestore 85 SaveRestore bool 86 87 // DisconnectOk if true, indicates that this NIC capability set should 88 // include CapabilityDisconnectOk. 89 DisconnectOk bool 90 91 // TXChecksumOffload if true, indicates that this endpoints capability 92 // set should include CapabilityTXChecksumOffload. 93 TXChecksumOffload bool 94 95 // RXChecksumOffload if true, indicates that this endpoints capability 96 // set should include CapabilityRXChecksumOffload. 97 RXChecksumOffload bool 98 99 // InterfaceIndex is the interface index of the underlying device. 100 InterfaceIndex int 101 } 102 103 // New creates a new endpoint from an AF_XDP socket. 104 func New(opts *Options) (stack.LinkEndpoint, error) { 105 caps := stack.CapabilityResolutionRequired 106 if opts.RXChecksumOffload { 107 caps |= stack.CapabilityRXChecksumOffload 108 } 109 110 if opts.TXChecksumOffload { 111 caps |= stack.CapabilityTXChecksumOffload 112 } 113 114 if opts.SaveRestore { 115 caps |= stack.CapabilitySaveRestore 116 } 117 118 if opts.DisconnectOk { 119 caps |= stack.CapabilityDisconnectOk 120 } 121 122 if err := unix.SetNonblock(opts.FD, true); err != nil { 123 return nil, fmt.Errorf("unix.SetNonblock(%v) failed: %v", opts.FD, err) 124 } 125 126 ep := &endpoint{ 127 fd: opts.FD, 128 caps: caps, 129 closed: opts.ClosedFunc, 130 addr: opts.Address, 131 } 132 133 stopFD, err := stopfd.New() 134 if err != nil { 135 return nil, err 136 } 137 ep.stopFD = stopFD 138 139 // Use a 2MB UMEM to match the PACKET_MMAP dispatcher. There will be 140 // 1024 UMEM frames, and each queue will have 512 descriptors. Having 141 // fewer descriptors than frames prevents RX and TX from starving each 142 // other. 143 // TODO(b/240191988): Consider different numbers of descriptors for 144 // different queues. 145 const ( 146 frameSize = 2048 147 umemSize = 1 << 21 148 nFrames = umemSize / frameSize 149 ) 150 xdpOpts := xdp.ReadOnlySocketOpts{ 151 NFrames: nFrames, 152 FrameSize: frameSize, 153 NDescriptors: nFrames / 2, 154 } 155 ep.control, err = xdp.ReadOnlyFromSocket(opts.FD, uint32(opts.InterfaceIndex), 0 /* queueID */, xdpOpts) 156 if err != nil { 157 return nil, fmt.Errorf("failed to create AF_XDP dispatcher: %v", err) 158 } 159 160 ep.control.UMEM.Lock() 161 defer ep.control.UMEM.Unlock() 162 163 ep.control.Fill.FillAll(&ep.control.UMEM) 164 165 return ep, nil 166 } 167 168 // Attach launches the goroutine that reads packets from the file descriptor and 169 // dispatches them via the provided dispatcher. If one is already attached, 170 // then nothing happens. 171 // 172 // Attach implements stack.LinkEndpoint.Attach. 173 func (ep *endpoint) Attach(networkDispatcher stack.NetworkDispatcher) { 174 ep.mu.Lock() 175 defer ep.mu.Unlock() 176 // nil means the NIC is being removed. 177 if networkDispatcher == nil && ep.IsAttached() { 178 ep.stopFD.Stop() 179 ep.Wait() 180 ep.networkDispatcher = nil 181 return 182 } 183 if networkDispatcher != nil && ep.networkDispatcher == nil { 184 ep.networkDispatcher = networkDispatcher 185 // Link endpoints are not savable. When transportation endpoints are 186 // saved, they stop sending outgoing packets and all incoming packets 187 // are rejected. 188 ep.wg.Add(1) 189 go func() { // S/R-SAFE: See above. 190 defer ep.wg.Done() 191 for { 192 cont, err := ep.dispatch() 193 if err != nil || !cont { 194 if ep.closed != nil { 195 ep.closed(err) 196 } 197 return 198 } 199 } 200 }() 201 } 202 } 203 204 // IsAttached implements stack.LinkEndpoint.IsAttached. 205 func (ep *endpoint) IsAttached() bool { 206 ep.mu.RLock() 207 defer ep.mu.RUnlock() 208 return ep.networkDispatcher != nil 209 } 210 211 // MTU implements stack.LinkEndpoint.MTU. It returns the value initialized 212 // during construction. 213 func (ep *endpoint) MTU() uint32 { 214 return MTU 215 } 216 217 // Capabilities implements stack.LinkEndpoint.Capabilities. 218 func (ep *endpoint) Capabilities() stack.LinkEndpointCapabilities { 219 return ep.caps 220 } 221 222 // MaxHeaderLength returns the maximum size of the link-layer header. 223 func (ep *endpoint) MaxHeaderLength() uint16 { 224 return uint16(header.EthernetMinimumSize) 225 } 226 227 // LinkAddress returns the link address of this endpoint. 228 func (ep *endpoint) LinkAddress() tcpip.LinkAddress { 229 return ep.addr 230 } 231 232 // Wait implements stack.LinkEndpoint.Wait. It waits for the endpoint to stop 233 // reading from its FD. 234 func (ep *endpoint) Wait() { 235 ep.wg.Wait() 236 } 237 238 // AddHeader implements stack.LinkEndpoint.AddHeader. 239 func (ep *endpoint) AddHeader(pkt stack.PacketBufferPtr) { 240 // Add ethernet header if needed. 241 eth := header.Ethernet(pkt.LinkHeader().Push(header.EthernetMinimumSize)) 242 eth.Encode(&header.EthernetFields{ 243 SrcAddr: pkt.EgressRoute.LocalLinkAddress, 244 DstAddr: pkt.EgressRoute.RemoteLinkAddress, 245 Type: pkt.NetworkProtocolNumber, 246 }) 247 } 248 249 // ParseHeader implements stack.LinkEndpoint.ParseHeader. 250 func (ep *endpoint) ParseHeader(pkt stack.PacketBufferPtr) bool { 251 _, ok := pkt.LinkHeader().Consume(header.EthernetMinimumSize) 252 return ok 253 } 254 255 // ARPHardwareType implements stack.LinkEndpoint.ARPHardwareType. 256 func (ep *endpoint) ARPHardwareType() header.ARPHardwareType { 257 return header.ARPHardwareEther 258 } 259 260 // WritePackets writes outbound packets to the underlying file descriptors. If 261 // one is not currently writable, the packet is dropped. 262 // 263 // Each packet in pkts should have the following fields populated: 264 // - pkt.EgressRoute 265 // - pkt.NetworkProtocolNumber 266 // 267 // The following should not be populated, as GSO is not supported with XDP. 268 // - pkt.GSOOptions 269 func (ep *endpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Error) { 270 // We expect to be called via fifo, which imposes a limit of 271 // fifo.BatchSize. 272 var preallocatedBatch [fifo.BatchSize]unix.XDPDesc 273 batch := preallocatedBatch[:0] 274 275 ep.control.UMEM.Lock() 276 277 ep.control.Completion.FreeAll(&ep.control.UMEM) 278 279 // Reserve TX queue descriptors and umem buffers 280 nReserved, index := ep.control.TX.Reserve(&ep.control.UMEM, uint32(pkts.Len())) 281 if nReserved == 0 { 282 ep.control.UMEM.Unlock() 283 return 0, &tcpip.ErrNoBufferSpace{} 284 } 285 286 // Allocate UMEM space. In order to release the UMEM lock as soon as 287 // possible, we allocate up-front and copy data in after releasing. 288 for _, pkt := range pkts.AsSlice() { 289 batch = append(batch, unix.XDPDesc{ 290 Addr: ep.control.UMEM.AllocFrame(), 291 Len: uint32(pkt.Size()), 292 }) 293 } 294 ep.control.UMEM.Unlock() 295 296 for i, pkt := range pkts.AsSlice() { 297 // Copy packets into UMEM frame. 298 frame := ep.control.UMEM.Get(batch[i]) 299 offset := 0 300 for _, buf := range pkt.AsSlices() { 301 offset += copy(frame[offset:], buf) 302 } 303 ep.control.TX.Set(index+uint32(i), batch[i]) 304 } 305 306 // Notify the kernel that there're packets to write. 307 ep.control.TX.Notify() 308 309 return pkts.Len(), nil 310 } 311 312 func (ep *endpoint) dispatch() (bool, tcpip.Error) { 313 var views []*buffer.View 314 315 for { 316 stopped, errno := rawfile.BlockingPollUntilStopped(ep.stopFD.EFD, ep.fd, unix.POLLIN|unix.POLLERR) 317 if errno != 0 { 318 if errno == unix.EINTR { 319 continue 320 } 321 return !stopped, rawfile.TranslateErrno(errno) 322 } 323 if stopped { 324 return true, nil 325 } 326 327 // Avoid the cost of the poll syscall if possible by peeking 328 // until there are no packets left. 329 for { 330 // We can receive multiple packets at once. 331 nReceived, rxIndex := ep.control.RX.Peek() 332 333 if nReceived == 0 { 334 break 335 } 336 337 // Reuse views to avoid allocating. 338 views = views[:0] 339 340 // Populate views quickly so that we can release frames 341 // back to the kernel. 342 ep.control.UMEM.Lock() 343 for i := uint32(0); i < nReceived; i++ { 344 // Copy packet bytes into a view and free up the 345 // buffer. 346 descriptor := ep.control.RX.Get(rxIndex + i) 347 data := ep.control.UMEM.Get(descriptor) 348 view := buffer.NewViewWithData(data) 349 views = append(views, view) 350 ep.control.UMEM.FreeFrame(descriptor.Addr) 351 } 352 ep.control.Fill.FillAll(&ep.control.UMEM) 353 ep.control.UMEM.Unlock() 354 355 // Process each packet. 356 ep.mu.RLock() 357 d := ep.networkDispatcher 358 ep.mu.RUnlock() 359 for i := uint32(0); i < nReceived; i++ { 360 view := views[i] 361 data := view.AsSlice() 362 363 netProto := header.Ethernet(data).Type() 364 365 // Wrap the packet in a PacketBuffer and send it up the stack. 366 pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{ 367 Payload: buffer.MakeWithView(view), 368 }) 369 // AF_XDP packets always have a link header. 370 if !ep.ParseHeader(pkt) { 371 panic("ParseHeader(_) must succeed") 372 } 373 d.DeliverNetworkPacket(netProto, pkt) 374 pkt.DecRef() 375 } 376 // Tell the kernel that we're done with these 377 // descriptors in the RX queue. 378 ep.control.RX.Release(nReceived) 379 } 380 381 return true, nil 382 } 383 }