bpf.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * common eBPF ELF operations.
  3. *
  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. */
  8. #include <stdlib.h>
  9. #include <memory.h>
  10. #include <unistd.h>
  11. #include <asm/unistd.h>
  12. #include <linux/bpf.h>
  13. #include "bpf.h"
  14. /*
  15. * When building perf, unistd.h is override. Define __NR_bpf is
  16. * required to be defined.
  17. */
  18. #ifndef __NR_bpf
  19. # if defined(__i386__)
  20. # define __NR_bpf 357
  21. # elif defined(__x86_64__)
  22. # define __NR_bpf 321
  23. # elif defined(__aarch64__)
  24. # define __NR_bpf 280
  25. # else
  26. # error __NR_bpf not defined. libbpf does not support your arch.
  27. # endif
  28. #endif
  29. static __u64 ptr_to_u64(void *ptr)
  30. {
  31. return (__u64) (unsigned long) ptr;
  32. }
  33. static int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr,
  34. unsigned int size)
  35. {
  36. return syscall(__NR_bpf, cmd, attr, size);
  37. }
  38. int bpf_create_map(enum bpf_map_type map_type, int key_size,
  39. int value_size, int max_entries)
  40. {
  41. union bpf_attr attr;
  42. memset(&attr, '\0', sizeof(attr));
  43. attr.map_type = map_type;
  44. attr.key_size = key_size;
  45. attr.value_size = value_size;
  46. attr.max_entries = max_entries;
  47. return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
  48. }
  49. int bpf_load_program(enum bpf_prog_type type, struct bpf_insn *insns,
  50. size_t insns_cnt, char *license,
  51. u32 kern_version, char *log_buf, size_t log_buf_sz)
  52. {
  53. int fd;
  54. union bpf_attr attr;
  55. bzero(&attr, sizeof(attr));
  56. attr.prog_type = type;
  57. attr.insn_cnt = (__u32)insns_cnt;
  58. attr.insns = ptr_to_u64(insns);
  59. attr.license = ptr_to_u64(license);
  60. attr.log_buf = ptr_to_u64(NULL);
  61. attr.log_size = 0;
  62. attr.log_level = 0;
  63. attr.kern_version = kern_version;
  64. fd = sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
  65. if (fd >= 0 || !log_buf || !log_buf_sz)
  66. return fd;
  67. /* Try again with log */
  68. attr.log_buf = ptr_to_u64(log_buf);
  69. attr.log_size = log_buf_sz;
  70. attr.log_level = 1;
  71. log_buf[0] = 0;
  72. return sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
  73. }