bpf_map.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. #include "util/bpf_map.h"
  3. #include <bpf/bpf.h>
  4. #include <bpf/libbpf.h>
  5. #include <linux/err.h>
  6. #include <linux/kernel.h>
  7. #include <stdbool.h>
  8. #include <stdlib.h>
  9. #include <unistd.h>
  10. static bool bpf_map_def__is_per_cpu(const struct bpf_map_def *def)
  11. {
  12. return def->type == BPF_MAP_TYPE_PERCPU_HASH ||
  13. def->type == BPF_MAP_TYPE_PERCPU_ARRAY ||
  14. def->type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
  15. def->type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE;
  16. }
  17. static void *bpf_map_def__alloc_value(const struct bpf_map_def *def)
  18. {
  19. if (bpf_map_def__is_per_cpu(def))
  20. return malloc(round_up(def->value_size, 8) * sysconf(_SC_NPROCESSORS_CONF));
  21. return malloc(def->value_size);
  22. }
  23. int bpf_map__fprintf(struct bpf_map *map, FILE *fp)
  24. {
  25. const struct bpf_map_def *def = bpf_map__def(map);
  26. void *prev_key = NULL, *key, *value;
  27. int fd = bpf_map__fd(map), err;
  28. int printed = 0;
  29. if (fd < 0)
  30. return fd;
  31. if (IS_ERR(def))
  32. return PTR_ERR(def);
  33. err = -ENOMEM;
  34. key = malloc(def->key_size);
  35. if (key == NULL)
  36. goto out;
  37. value = bpf_map_def__alloc_value(def);
  38. if (value == NULL)
  39. goto out_free_key;
  40. while ((err = bpf_map_get_next_key(fd, prev_key, key) == 0)) {
  41. int intkey = *(int *)key;
  42. if (!bpf_map_lookup_elem(fd, key, value)) {
  43. bool boolval = *(bool *)value;
  44. if (boolval)
  45. printed += fprintf(fp, "[%d] = %d,\n", intkey, boolval);
  46. } else {
  47. printed += fprintf(fp, "[%d] = ERROR,\n", intkey);
  48. }
  49. prev_key = key;
  50. }
  51. if (err == ENOENT)
  52. err = printed;
  53. free(value);
  54. out_free_key:
  55. free(key);
  56. out:
  57. return err;
  58. }