2 * common eBPF ELF operations.
4 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
5 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
6 * Copyright (C) 2015 Huawei Inc.
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation;
11 * version 2.1 of the License (not later!)
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this program; if not, see <http://www.gnu.org/licenses>
25 #include <asm/unistd.h>
26 #include <linux/bpf.h>
30 * When building perf, unistd.h is overrided. __NR_bpf is
31 * required to be defined explicitly.
34 # if defined(__i386__)
36 # elif defined(__x86_64__)
38 # elif defined(__aarch64__)
41 # error __NR_bpf not defined. libbpf does not support your arch.
45 static __u64 ptr_to_u64(void *ptr)
47 return (__u64) (unsigned long) ptr;
50 static int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr,
53 return syscall(__NR_bpf, cmd, attr, size);
56 int bpf_create_map(enum bpf_map_type map_type, int key_size,
57 int value_size, int max_entries)
61 memset(&attr, '\0', sizeof(attr));
63 attr.map_type = map_type;
64 attr.key_size = key_size;
65 attr.value_size = value_size;
66 attr.max_entries = max_entries;
68 return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
71 int bpf_load_program(enum bpf_prog_type type, struct bpf_insn *insns,
72 size_t insns_cnt, char *license,
73 u32 kern_version, char *log_buf, size_t log_buf_sz)
78 bzero(&attr, sizeof(attr));
79 attr.prog_type = type;
80 attr.insn_cnt = (__u32)insns_cnt;
81 attr.insns = ptr_to_u64(insns);
82 attr.license = ptr_to_u64(license);
83 attr.log_buf = ptr_to_u64(NULL);
86 attr.kern_version = kern_version;
88 fd = sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
89 if (fd >= 0 || !log_buf || !log_buf_sz)
92 /* Try again with log */
93 attr.log_buf = ptr_to_u64(log_buf);
94 attr.log_size = log_buf_sz;
97 return sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
100 int bpf_map_update_elem(int fd, void *key, void *value,
105 bzero(&attr, sizeof(attr));
107 attr.key = ptr_to_u64(key);
108 attr.value = ptr_to_u64(value);
111 return sys_bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));