github.com/metacubex/gvisor@v0.0.0-20240320004321-933faba989ec/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  	"golang.org/x/sys/unix"
    25  	"github.com/metacubex/gvisor/pkg/buffer"
    26  	"github.com/metacubex/gvisor/pkg/sync"
    27  	"github.com/metacubex/gvisor/pkg/tcpip"
    28  	"github.com/metacubex/gvisor/pkg/tcpip/header"
    29  	"github.com/metacubex/gvisor/pkg/tcpip/link/qdisc/fifo"
    30  	"github.com/metacubex/gvisor/pkg/tcpip/link/rawfile"
    31  	"github.com/metacubex/gvisor/pkg/tcpip/link/stopfd"
    32  	"github.com/metacubex/gvisor/pkg/tcpip/stack"
    33  	"github.com/metacubex/gvisor/pkg/xdp"
    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  	// Bind is true when we're responsible for binding the AF_XDP socket to
   103  	// a device. When false, another process is expected to bind for us.
   104  	Bind bool
   105  }
   106  
   107  // New creates a new endpoint from an AF_XDP socket.
   108  func New(opts *Options) (stack.LinkEndpoint, error) {
   109  	caps := stack.CapabilityResolutionRequired
   110  	if opts.RXChecksumOffload {
   111  		caps |= stack.CapabilityRXChecksumOffload
   112  	}
   113  
   114  	if opts.TXChecksumOffload {
   115  		caps |= stack.CapabilityTXChecksumOffload
   116  	}
   117  
   118  	if opts.SaveRestore {
   119  		caps |= stack.CapabilitySaveRestore
   120  	}
   121  
   122  	if opts.DisconnectOk {
   123  		caps |= stack.CapabilityDisconnectOk
   124  	}
   125  
   126  	if err := unix.SetNonblock(opts.FD, true); err != nil {
   127  		return nil, fmt.Errorf("unix.SetNonblock(%v) failed: %v", opts.FD, err)
   128  	}
   129  
   130  	ep := &endpoint{
   131  		fd:     opts.FD,
   132  		caps:   caps,
   133  		closed: opts.ClosedFunc,
   134  		addr:   opts.Address,
   135  	}
   136  
   137  	stopFD, err := stopfd.New()
   138  	if err != nil {
   139  		return nil, err
   140  	}
   141  	ep.stopFD = stopFD
   142  
   143  	// Use a 2MB UMEM to match the PACKET_MMAP dispatcher. There will be
   144  	// 1024 UMEM frames, and each queue will have 512 descriptors. Having
   145  	// fewer descriptors than frames prevents RX and TX from starving each
   146  	// other.
   147  	// TODO(b/240191988): Consider different numbers of descriptors for
   148  	// different queues.
   149  	const (
   150  		frameSize = 2048
   151  		umemSize  = 1 << 21
   152  		nFrames   = umemSize / frameSize
   153  	)
   154  	xdpOpts := xdp.Opts{
   155  		NFrames:      nFrames,
   156  		FrameSize:    frameSize,
   157  		NDescriptors: nFrames / 2,
   158  		Bind:         opts.Bind,
   159  	}
   160  	ep.control, err = xdp.NewFromSocket(opts.FD, uint32(opts.InterfaceIndex), 0 /* queueID */, xdpOpts)
   161  	if err != nil {
   162  		return nil, fmt.Errorf("failed to create AF_XDP dispatcher: %v", err)
   163  	}
   164  
   165  	ep.control.UMEM.Lock()
   166  	defer ep.control.UMEM.Unlock()
   167  
   168  	ep.control.Fill.FillAll(&ep.control.UMEM)
   169  
   170  	return ep, nil
   171  }
   172  
   173  // Attach launches the goroutine that reads packets from the file descriptor and
   174  // dispatches them via the provided dispatcher. If one is already attached,
   175  // then nothing happens.
   176  //
   177  // Attach implements stack.LinkEndpoint.Attach.
   178  func (ep *endpoint) Attach(networkDispatcher stack.NetworkDispatcher) {
   179  	ep.mu.Lock()
   180  	defer ep.mu.Unlock()
   181  	// nil means the NIC is being removed.
   182  	if networkDispatcher == nil && ep.IsAttached() {
   183  		ep.stopFD.Stop()
   184  		ep.Wait()
   185  		ep.networkDispatcher = nil
   186  		return
   187  	}
   188  	if networkDispatcher != nil && ep.networkDispatcher == nil {
   189  		ep.networkDispatcher = networkDispatcher
   190  		// Link endpoints are not savable. When transportation endpoints are
   191  		// saved, they stop sending outgoing packets and all incoming packets
   192  		// are rejected.
   193  		ep.wg.Add(1)
   194  		go func() { // S/R-SAFE: See above.
   195  			defer ep.wg.Done()
   196  			for {
   197  				cont, err := ep.dispatch()
   198  				if err != nil || !cont {
   199  					if ep.closed != nil {
   200  						ep.closed(err)
   201  					}
   202  					return
   203  				}
   204  			}
   205  		}()
   206  	}
   207  }
   208  
   209  // IsAttached implements stack.LinkEndpoint.IsAttached.
   210  func (ep *endpoint) IsAttached() bool {
   211  	ep.mu.RLock()
   212  	defer ep.mu.RUnlock()
   213  	return ep.networkDispatcher != nil
   214  }
   215  
   216  // MTU implements stack.LinkEndpoint.MTU. It returns the value initialized
   217  // during construction.
   218  func (ep *endpoint) MTU() uint32 {
   219  	return MTU
   220  }
   221  
   222  // Capabilities implements stack.LinkEndpoint.Capabilities.
   223  func (ep *endpoint) Capabilities() stack.LinkEndpointCapabilities {
   224  	return ep.caps
   225  }
   226  
   227  // MaxHeaderLength returns the maximum size of the link-layer header.
   228  func (ep *endpoint) MaxHeaderLength() uint16 {
   229  	return uint16(header.EthernetMinimumSize)
   230  }
   231  
   232  // LinkAddress returns the link address of this endpoint.
   233  func (ep *endpoint) LinkAddress() tcpip.LinkAddress {
   234  	return ep.addr
   235  }
   236  
   237  // Wait implements stack.LinkEndpoint.Wait. It waits for the endpoint to stop
   238  // reading from its FD.
   239  func (ep *endpoint) Wait() {
   240  	ep.wg.Wait()
   241  }
   242  
   243  // AddHeader implements stack.LinkEndpoint.AddHeader.
   244  func (ep *endpoint) AddHeader(pkt *stack.PacketBuffer) {
   245  	// Add ethernet header if needed.
   246  	eth := header.Ethernet(pkt.LinkHeader().Push(header.EthernetMinimumSize))
   247  	eth.Encode(&header.EthernetFields{
   248  		SrcAddr: pkt.EgressRoute.LocalLinkAddress,
   249  		DstAddr: pkt.EgressRoute.RemoteLinkAddress,
   250  		Type:    pkt.NetworkProtocolNumber,
   251  	})
   252  }
   253  
   254  // ParseHeader implements stack.LinkEndpoint.ParseHeader.
   255  func (ep *endpoint) ParseHeader(pkt *stack.PacketBuffer) bool {
   256  	_, ok := pkt.LinkHeader().Consume(header.EthernetMinimumSize)
   257  	return ok
   258  }
   259  
   260  // ARPHardwareType implements stack.LinkEndpoint.ARPHardwareType.
   261  func (ep *endpoint) ARPHardwareType() header.ARPHardwareType {
   262  	return header.ARPHardwareEther
   263  }
   264  
   265  // WritePackets writes outbound packets to the underlying file descriptors. If
   266  // one is not currently writable, the packet is dropped.
   267  //
   268  // Each packet in pkts should have the following fields populated:
   269  //   - pkt.EgressRoute
   270  //   - pkt.NetworkProtocolNumber
   271  //
   272  // The following should not be populated, as GSO is not supported with XDP.
   273  //   - pkt.GSOOptions
   274  func (ep *endpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Error) {
   275  	// We expect to be called via fifo, which imposes a limit of
   276  	// fifo.BatchSize.
   277  	var preallocatedBatch [fifo.BatchSize]unix.XDPDesc
   278  	batch := preallocatedBatch[:0]
   279  
   280  	ep.control.UMEM.Lock()
   281  
   282  	ep.control.Completion.FreeAll(&ep.control.UMEM)
   283  
   284  	// Reserve TX queue descriptors and umem buffers
   285  	nReserved, index := ep.control.TX.Reserve(&ep.control.UMEM, uint32(pkts.Len()))
   286  	if nReserved == 0 {
   287  		ep.control.UMEM.Unlock()
   288  		return 0, &tcpip.ErrNoBufferSpace{}
   289  	}
   290  
   291  	// Allocate UMEM space. In order to release the UMEM lock as soon as
   292  	// possible we allocate up-front.
   293  	for _, pkt := range pkts.AsSlice() {
   294  		batch = append(batch, unix.XDPDesc{
   295  			Addr: ep.control.UMEM.AllocFrame(),
   296  			Len:  uint32(pkt.Size()),
   297  		})
   298  	}
   299  
   300  	for i, pkt := range pkts.AsSlice() {
   301  		// Copy packets into UMEM frame.
   302  		frame := ep.control.UMEM.Get(batch[i])
   303  		offset := 0
   304  		for _, buf := range pkt.AsSlices() {
   305  			offset += copy(frame[offset:], buf)
   306  		}
   307  		ep.control.TX.Set(index+uint32(i), batch[i])
   308  	}
   309  
   310  	// Notify the kernel that there're packets to write.
   311  	ep.control.TX.Notify()
   312  
   313  	// TODO(b/240191988): Explore more fine-grained locking. We shouldn't
   314  	// need to hold the UMEM lock for the whole duration of packet copying.
   315  	ep.control.UMEM.Unlock()
   316  
   317  	return pkts.Len(), nil
   318  }
   319  
   320  func (ep *endpoint) dispatch() (bool, tcpip.Error) {
   321  	var views []*buffer.View
   322  
   323  	for {
   324  		stopped, errno := rawfile.BlockingPollUntilStopped(ep.stopFD.EFD, ep.fd, unix.POLLIN|unix.POLLERR)
   325  		if errno != 0 {
   326  			if errno == unix.EINTR {
   327  				continue
   328  			}
   329  			return !stopped, rawfile.TranslateErrno(errno)
   330  		}
   331  		if stopped {
   332  			return true, nil
   333  		}
   334  
   335  		// Avoid the cost of the poll syscall if possible by peeking
   336  		// until there are no packets left.
   337  		for {
   338  			// We can receive multiple packets at once.
   339  			nReceived, rxIndex := ep.control.RX.Peek()
   340  
   341  			if nReceived == 0 {
   342  				break
   343  			}
   344  
   345  			// Reuse views to avoid allocating.
   346  			views = views[:0]
   347  
   348  			// Populate views quickly so that we can release frames
   349  			// back to the kernel.
   350  			ep.control.UMEM.Lock()
   351  			for i := uint32(0); i < nReceived; i++ {
   352  				// Copy packet bytes into a view and free up the
   353  				// buffer.
   354  				descriptor := ep.control.RX.Get(rxIndex + i)
   355  				data := ep.control.UMEM.Get(descriptor)
   356  				view := buffer.NewViewWithData(data)
   357  				views = append(views, view)
   358  				ep.control.UMEM.FreeFrame(descriptor.Addr)
   359  			}
   360  			ep.control.Fill.FillAll(&ep.control.UMEM)
   361  			ep.control.UMEM.Unlock()
   362  
   363  			// Process each packet.
   364  			ep.mu.RLock()
   365  			d := ep.networkDispatcher
   366  			ep.mu.RUnlock()
   367  			for i := uint32(0); i < nReceived; i++ {
   368  				view := views[i]
   369  				data := view.AsSlice()
   370  
   371  				netProto := header.Ethernet(data).Type()
   372  
   373  				// Wrap the packet in a PacketBuffer and send it up the stack.
   374  				pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
   375  					Payload: buffer.MakeWithView(view),
   376  				})
   377  				// AF_XDP packets always have a link header.
   378  				if !ep.ParseHeader(pkt) {
   379  					panic("ParseHeader(_) must succeed")
   380  				}
   381  				d.DeliverNetworkPacket(netProto, pkt)
   382  				pkt.DecRef()
   383  			}
   384  			// Tell the kernel that we're done with these
   385  			// descriptors in the RX queue.
   386  			ep.control.RX.Release(nReceived)
   387  		}
   388  
   389  		return true, nil
   390  	}
   391  }