| 1 |
|
| 2 |
|
| 3 |
package link |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
|
| 8 |
"github.com/cilium/ebpf" |
| 9 |
"github.com/cilium/ebpf/internal/sys" |
| 10 |
) |
| 11 |
|
| 12 |
|
| 13 |
type XDPAttachFlags uint32 |
| 14 |
|
| 15 |
const ( |
| 16 |
|
| 17 |
|
| 18 |
XDPGenericMode XDPAttachFlags = 1 << (iota + 1) |
| 19 |
h. |
| 20 |
XDPDriverMode |
| 21 |
|
| 22 |
XDPOffloadMode |
| 23 |
) |
| 24 |
|
| 25 |
type XDPOptions struct { |
| 26 |
|
| 27 |
Program *ebpf.Program |
| 28 |
|
| 29 |
|
| 30 |
Interface int |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
Flags XDPAttachFlags |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
func AttachXDP(opts XDPOptions) (Link, error) { |
| 41 |
if t := opts.Program.Type(); t != ebpf.XDP { |
| 42 |
return nil, fmt.Errorf("invalid program type %s, expected XDP", t) |
| 43 |
} |
| 44 |
|
| 45 |
if opts.Interface < 1 { |
| 46 |
return nil, fmt.Errorf("invalid interface index: %d", opts.Interface) |
| 47 |
} |
| 48 |
|
| 49 |
rawLink, err := AttachRawLink(RawLinkOptions{ |
| 50 |
Program: opts.Program, |
| 51 |
Attach: ebpf.AttachXDP, |
| 52 |
Target: opts.Interface, |
| 53 |
Flags: uint32(opts.Flags), |
| 54 |
}) |
| 55 |
|
| 56 |
if err != nil { |
| 57 |
return nil, fmt.Errorf("failed to attach link: %w", err) |
| 58 |
} |
| 59 |
|
| 60 |
return &xdpLink{*rawLink}, nil |
| 61 |
} |
| 62 |
|
| 63 |
type xdpLink struct { |
| 64 |
RawLink |
| 65 |
} |
| 66 |
|
| 67 |
func (xdp *xdpLink) Info() (*Info, error) { |
| 68 |
var info sys.XDPLinkInfo |
| 69 |
if err := sys.ObjInfo(xdp.fd, &info); err != nil { |
| 70 |
return nil, fmt.Errorf("xdp link info: %s", err) |
| 71 |
} |
| 72 |
extra := &XDPInfo{ |
| 73 |
Ifindex: info.Ifindex, |
| 74 |
} |
| 75 |
|
| 76 |
return &Info{ |
| 77 |
info.Type, |
| 78 |
info.Id, |
| 79 |
ebpf.ProgramID(info.ProgId), |
| 80 |
extra, |
| 81 |
}, nil |
| 82 |
} |