thermal: fix Mediatek thermal controller build
[linux/fpc-iii.git] / tools / lib / bpf / bpf.c
blob1f91cc941b7c2b14243f6ffe4118a21a2ac39c83
1 /*
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.
7 */
9 #include <stdlib.h>
10 #include <memory.h>
11 #include <unistd.h>
12 #include <asm/unistd.h>
13 #include <linux/bpf.h>
14 #include "bpf.h"
17 * When building perf, unistd.h is overrided. __NR_bpf is
18 * required to be defined explicitly.
20 #ifndef __NR_bpf
21 # if defined(__i386__)
22 # define __NR_bpf 357
23 # elif defined(__x86_64__)
24 # define __NR_bpf 321
25 # elif defined(__aarch64__)
26 # define __NR_bpf 280
27 # else
28 # error __NR_bpf not defined. libbpf does not support your arch.
29 # endif
30 #endif
32 static __u64 ptr_to_u64(void *ptr)
34 return (__u64) (unsigned long) ptr;
37 static int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr,
38 unsigned int size)
40 return syscall(__NR_bpf, cmd, attr, size);
43 int bpf_create_map(enum bpf_map_type map_type, int key_size,
44 int value_size, int max_entries)
46 union bpf_attr attr;
48 memset(&attr, '\0', sizeof(attr));
50 attr.map_type = map_type;
51 attr.key_size = key_size;
52 attr.value_size = value_size;
53 attr.max_entries = max_entries;
55 return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
58 int bpf_load_program(enum bpf_prog_type type, struct bpf_insn *insns,
59 size_t insns_cnt, char *license,
60 u32 kern_version, char *log_buf, size_t log_buf_sz)
62 int fd;
63 union bpf_attr attr;
65 bzero(&attr, sizeof(attr));
66 attr.prog_type = type;
67 attr.insn_cnt = (__u32)insns_cnt;
68 attr.insns = ptr_to_u64(insns);
69 attr.license = ptr_to_u64(license);
70 attr.log_buf = ptr_to_u64(NULL);
71 attr.log_size = 0;
72 attr.log_level = 0;
73 attr.kern_version = kern_version;
75 fd = sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
76 if (fd >= 0 || !log_buf || !log_buf_sz)
77 return fd;
79 /* Try again with log */
80 attr.log_buf = ptr_to_u64(log_buf);
81 attr.log_size = log_buf_sz;
82 attr.log_level = 1;
83 log_buf[0] = 0;
84 return sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
87 int bpf_map_update_elem(int fd, void *key, void *value,
88 u64 flags)
90 union bpf_attr attr;
92 bzero(&attr, sizeof(attr));
93 attr.map_fd = fd;
94 attr.key = ptr_to_u64(key);
95 attr.value = ptr_to_u64(value);
96 attr.flags = flags;
98 return sys_bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));