bpf: add a testsuite for eBPF maps
[cascardo/linux.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 <linux/netlink.h>
8 #include <linux/bpf.h>
9 #include <errno.h>
10 #include "libbpf.h"
11
12 static __u64 ptr_to_u64(void *ptr)
13 {
14         return (__u64) (unsigned long) ptr;
15 }
16
17 int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
18                    int max_entries)
19 {
20         union bpf_attr attr = {
21                 .map_type = map_type,
22                 .key_size = key_size,
23                 .value_size = value_size,
24                 .max_entries = max_entries
25         };
26
27         return syscall(__NR_bpf, BPF_MAP_CREATE, &attr, sizeof(attr));
28 }
29
30 int bpf_update_elem(int fd, void *key, void *value, unsigned long long flags)
31 {
32         union bpf_attr attr = {
33                 .map_fd = fd,
34                 .key = ptr_to_u64(key),
35                 .value = ptr_to_u64(value),
36                 .flags = flags,
37         };
38
39         return syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
40 }
41
42 int bpf_lookup_elem(int fd, void *key, void *value)
43 {
44         union bpf_attr attr = {
45                 .map_fd = fd,
46                 .key = ptr_to_u64(key),
47                 .value = ptr_to_u64(value),
48         };
49
50         return syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
51 }
52
53 int bpf_delete_elem(int fd, void *key)
54 {
55         union bpf_attr attr = {
56                 .map_fd = fd,
57                 .key = ptr_to_u64(key),
58         };
59
60         return syscall(__NR_bpf, BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
61 }
62
63 int bpf_get_next_key(int fd, void *key, void *next_key)
64 {
65         union bpf_attr attr = {
66                 .map_fd = fd,
67                 .key = ptr_to_u64(key),
68                 .next_key = ptr_to_u64(next_key),
69         };
70
71         return syscall(__NR_bpf, BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
72 }
73
74 #define ROUND_UP(x, n) (((x) + (n) - 1u) & ~((n) - 1u))
75
76 char bpf_log_buf[LOG_BUF_SIZE];
77
78 int bpf_prog_load(enum bpf_prog_type prog_type,
79                   const struct bpf_insn *insns, int prog_len,
80                   const char *license)
81 {
82         union bpf_attr attr = {
83                 .prog_type = prog_type,
84                 .insns = ptr_to_u64((void *) insns),
85                 .insn_cnt = prog_len / sizeof(struct bpf_insn),
86                 .license = ptr_to_u64((void *) license),
87                 .log_buf = ptr_to_u64(bpf_log_buf),
88                 .log_size = LOG_BUF_SIZE,
89                 .log_level = 1,
90         };
91
92         bpf_log_buf[0] = 0;
93
94         return syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
95 }