xdp.go 1.3 KB

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