bpf: add a testsuite for eBPF maps
[linux-2.6/btrfs-unstable.git] / samples / bpf / libbpf.c
blob17bb520eb57fc9b6df3aca889242a5b5a12e698b
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"
12 static __u64 ptr_to_u64(void *ptr)
14 return (__u64) (unsigned long) ptr;
17 int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
18 int max_entries)
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
27 return syscall(__NR_bpf, BPF_MAP_CREATE, &attr, sizeof(attr));
30 int bpf_update_elem(int fd, void *key, void *value, unsigned long long flags)
32 union bpf_attr attr = {
33 .map_fd = fd,
34 .key = ptr_to_u64(key),
35 .value = ptr_to_u64(value),
36 .flags = flags,
39 return syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
42 int bpf_lookup_elem(int fd, void *key, void *value)
44 union bpf_attr attr = {
45 .map_fd = fd,
46 .key = ptr_to_u64(key),
47 .value = ptr_to_u64(value),
50 return syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
53 int bpf_delete_elem(int fd, void *key)
55 union bpf_attr attr = {
56 .map_fd = fd,
57 .key = ptr_to_u64(key),
60 return syscall(__NR_bpf, BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
63 int bpf_get_next_key(int fd, void *key, void *next_key)
65 union bpf_attr attr = {
66 .map_fd = fd,
67 .key = ptr_to_u64(key),
68 .next_key = ptr_to_u64(next_key),
71 return syscall(__NR_bpf, BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
74 #define ROUND_UP(x, n) (((x) + (n) - 1u) & ~((n) - 1u))
76 char bpf_log_buf[LOG_BUF_SIZE];
78 int bpf_prog_load(enum bpf_prog_type prog_type,
79 const struct bpf_insn *insns, int prog_len,
80 const char *license)
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,
92 bpf_log_buf[0] = 0;
94 return syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));