github.com/cilium/ebpf@v0.16.0/link/xdp.go (about)

     1  package link
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/cilium/ebpf"
     7  	"github.com/cilium/ebpf/internal/sys"
     8  )
     9  
    10  // XDPAttachFlags represents how XDP program will be attached to interface.
    11  type XDPAttachFlags uint32
    12  
    13  const (
    14  	// XDPGenericMode (SKB) links XDP BPF program for drivers which do
    15  	// not yet support native XDP.
    16  	XDPGenericMode XDPAttachFlags = 1 << (iota + 1)
    17  	// XDPDriverMode links XDP BPF program into the driver’s receive path.
    18  	XDPDriverMode
    19  	// XDPOffloadMode offloads the entire XDP BPF program into hardware.
    20  	XDPOffloadMode
    21  )
    22  
    23  type XDPOptions struct {
    24  	// Program must be an XDP BPF program.
    25  	Program *ebpf.Program
    26  
    27  	// Interface is the interface index to attach program to.
    28  	Interface int
    29  
    30  	// Flags is one of XDPAttachFlags (optional).
    31  	//
    32  	// Only one XDP mode should be set, without flag defaults
    33  	// to driver/generic mode (best effort).
    34  	Flags XDPAttachFlags
    35  }
    36  
    37  // AttachXDP links an XDP BPF program to an XDP hook.
    38  func AttachXDP(opts XDPOptions) (Link, error) {
    39  	if t := opts.Program.Type(); t != ebpf.XDP {
    40  		return nil, fmt.Errorf("invalid program type %s, expected XDP", t)
    41  	}
    42  
    43  	if opts.Interface < 1 {
    44  		return nil, fmt.Errorf("invalid interface index: %d", opts.Interface)
    45  	}
    46  
    47  	rawLink, err := AttachRawLink(RawLinkOptions{
    48  		Program: opts.Program,
    49  		Attach:  ebpf.AttachXDP,
    50  		Target:  opts.Interface,
    51  		Flags:   uint32(opts.Flags),
    52  	})
    53  
    54  	if err != nil {
    55  		return nil, fmt.Errorf("failed to attach link: %w", err)
    56  	}
    57  
    58  	return &xdpLink{*rawLink}, nil
    59  }
    60  
    61  type xdpLink struct {
    62  	RawLink
    63  }
    64  
    65  func (xdp *xdpLink) Info() (*Info, error) {
    66  	var info sys.XDPLinkInfo
    67  	if err := sys.ObjInfo(xdp.fd, &info); err != nil {
    68  		return nil, fmt.Errorf("xdp link info: %s", err)
    69  	}
    70  	extra := &XDPInfo{
    71  		Ifindex: info.Ifindex,
    72  	}
    73  
    74  	return &Info{
    75  		info.Type,
    76  		info.Id,
    77  		ebpf.ProgramID(info.ProgId),
    78  		extra,
    79  	}, nil
    80  }