bpf-script-example.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #ifndef LINUX_VERSION_CODE
  2. # error Need LINUX_VERSION_CODE
  3. # error Example: for 4.2 kernel, put 'clang-opt="-DLINUX_VERSION_CODE=0x40200" into llvm section of ~/.perfconfig'
  4. #endif
  5. #define BPF_ANY 0
  6. #define BPF_MAP_TYPE_ARRAY 2
  7. #define BPF_FUNC_map_lookup_elem 1
  8. #define BPF_FUNC_map_update_elem 2
  9. static void *(*bpf_map_lookup_elem)(void *map, void *key) =
  10. (void *) BPF_FUNC_map_lookup_elem;
  11. static void *(*bpf_map_update_elem)(void *map, void *key, void *value, int flags) =
  12. (void *) BPF_FUNC_map_update_elem;
  13. struct bpf_map_def {
  14. unsigned int type;
  15. unsigned int key_size;
  16. unsigned int value_size;
  17. unsigned int max_entries;
  18. };
  19. #define SEC(NAME) __attribute__((section(NAME), used))
  20. struct bpf_map_def SEC("maps") flip_table = {
  21. .type = BPF_MAP_TYPE_ARRAY,
  22. .key_size = sizeof(int),
  23. .value_size = sizeof(int),
  24. .max_entries = 1,
  25. };
  26. SEC("func=sys_epoll_pwait")
  27. int bpf_func__sys_epoll_pwait(void *ctx)
  28. {
  29. int ind =0;
  30. int *flag = bpf_map_lookup_elem(&flip_table, &ind);
  31. int new_flag;
  32. if (!flag)
  33. return 0;
  34. /* flip flag and store back */
  35. new_flag = !*flag;
  36. bpf_map_update_elem(&flip_table, &ind, &new_flag, BPF_ANY);
  37. return new_flag;
  38. }
  39. char _license[] SEC("license") = "GPL";
  40. int _version SEC("version") = LINUX_VERSION_CODE;