xdp.go (1347B)
1 package link 2 3 import ( 4 "fmt" 5 6 "github.com/cilium/ebpf" 7 ) 8 9 // XDPAttachFlags represents how XDP program will be attached to interface. 10 type XDPAttachFlags uint32 11 12 const ( 13 // XDPGenericMode (SKB) links XDP BPF program for drivers which do 14 // not yet support native XDP. 15 XDPGenericMode XDPAttachFlags = 1 << (iota + 1) 16 // XDPDriverMode links XDP BPF program into the driver’s receive path. 17 XDPDriverMode 18 // XDPOffloadMode offloads the entire XDP BPF program into hardware. 19 XDPOffloadMode 20 ) 21 22 type XDPOptions struct { 23 // Program must be an XDP BPF program. 24 Program *ebpf.Program 25 26 // Interface is the interface index to attach program to. 27 Interface int 28 29 // Flags is one of XDPAttachFlags (optional). 30 // 31 // Only one XDP mode should be set, without flag defaults 32 // to driver/generic mode (best effort). 33 Flags XDPAttachFlags 34 } 35 36 // AttachXDP links an XDP BPF program to an XDP hook. 37 func AttachXDP(opts XDPOptions) (Link, error) { 38 if t := opts.Program.Type(); t != ebpf.XDP { 39 return nil, fmt.Errorf("invalid program type %s, expected XDP", t) 40 } 41 42 if opts.Interface < 1 { 43 return nil, fmt.Errorf("invalid interface index: %d", opts.Interface) 44 } 45 46 rawLink, err := AttachRawLink(RawLinkOptions{ 47 Program: opts.Program, 48 Attach: ebpf.AttachXDP, 49 Target: opts.Interface, 50 Flags: uint32(opts.Flags), 51 }) 52 53 return rawLink, err 54 }