]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - samples/bpf/libbpf.c
samples/bpf: Switch over to libbpf
[mirror_ubuntu-artful-kernel.git] / samples / bpf / libbpf.c
1 /* eBPF mini library */
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <linux/unistd.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <errno.h>
8 #include <net/ethernet.h>
9 #include <net/if.h>
10 #include <linux/if_packet.h>
11 #include <arpa/inet.h>
12 #include "libbpf.h"
13
14 int bpf_prog_attach(int prog_fd, int target_fd, enum bpf_attach_type type)
15 {
16 union bpf_attr attr = {
17 .target_fd = target_fd,
18 .attach_bpf_fd = prog_fd,
19 .attach_type = type,
20 };
21
22 return syscall(__NR_bpf, BPF_PROG_ATTACH, &attr, sizeof(attr));
23 }
24
25 int bpf_prog_detach(int target_fd, enum bpf_attach_type type)
26 {
27 union bpf_attr attr = {
28 .target_fd = target_fd,
29 .attach_type = type,
30 };
31
32 return syscall(__NR_bpf, BPF_PROG_DETACH, &attr, sizeof(attr));
33 }
34
35 int open_raw_sock(const char *name)
36 {
37 struct sockaddr_ll sll;
38 int sock;
39
40 sock = socket(PF_PACKET, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, htons(ETH_P_ALL));
41 if (sock < 0) {
42 printf("cannot create raw socket\n");
43 return -1;
44 }
45
46 memset(&sll, 0, sizeof(sll));
47 sll.sll_family = AF_PACKET;
48 sll.sll_ifindex = if_nametoindex(name);
49 sll.sll_protocol = htons(ETH_P_ALL);
50 if (bind(sock, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
51 printf("bind to %s: %s\n", name, strerror(errno));
52 close(sock);
53 return -1;
54 }
55
56 return sock;
57 }
58
59 int perf_event_open(struct perf_event_attr *attr, int pid, int cpu,
60 int group_fd, unsigned long flags)
61 {
62 return syscall(__NR_perf_event_open, attr, pid, cpu,
63 group_fd, flags);
64 }