libbpf.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. static __u64 ptr_to_u64(void *ptr)
  12. {
  13. return (__u64) (unsigned long) ptr;
  14. }
  15. int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
  16. int max_entries)
  17. {
  18. union bpf_attr attr = {
  19. .map_type = map_type,
  20. .key_size = key_size,
  21. .value_size = value_size,
  22. .max_entries = max_entries
  23. };
  24. return syscall(__NR_bpf, BPF_MAP_CREATE, &attr, sizeof(attr));
  25. }
  26. int bpf_update_elem(int fd, void *key, void *value)
  27. {
  28. union bpf_attr attr = {
  29. .map_fd = fd,
  30. .key = ptr_to_u64(key),
  31. .value = ptr_to_u64(value),
  32. };
  33. return syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
  34. }
  35. int bpf_lookup_elem(int fd, void *key, void *value)
  36. {
  37. union bpf_attr attr = {
  38. .map_fd = fd,
  39. .key = ptr_to_u64(key),
  40. .value = ptr_to_u64(value),
  41. };
  42. return syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
  43. }
  44. int bpf_delete_elem(int fd, void *key)
  45. {
  46. union bpf_attr attr = {
  47. .map_fd = fd,
  48. .key = ptr_to_u64(key),
  49. };
  50. return syscall(__NR_bpf, BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
  51. }
  52. int bpf_get_next_key(int fd, void *key, void *next_key)
  53. {
  54. union bpf_attr attr = {
  55. .map_fd = fd,
  56. .key = ptr_to_u64(key),
  57. .next_key = ptr_to_u64(next_key),
  58. };
  59. return syscall(__NR_bpf, BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
  60. }
  61. #define ROUND_UP(x, n) (((x) + (n) - 1u) & ~((n) - 1u))
  62. char bpf_log_buf[LOG_BUF_SIZE];
  63. int bpf_prog_load(enum bpf_prog_type prog_type,
  64. const struct bpf_insn *insns, int prog_len,
  65. const char *license)
  66. {
  67. union bpf_attr attr = {
  68. .prog_type = prog_type,
  69. .insns = ptr_to_u64((void *) insns),
  70. .insn_cnt = prog_len / sizeof(struct bpf_insn),
  71. .license = ptr_to_u64((void *) license),
  72. .log_buf = ptr_to_u64(bpf_log_buf),
  73. .log_size = LOG_BUF_SIZE,
  74. .log_level = 1,
  75. };
  76. bpf_log_buf[0] = 0;
  77. return syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
  78. }