bpf_util.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef __BPF_UTIL__
  3. #define __BPF_UTIL__
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <errno.h>
  8. static inline unsigned int bpf_num_possible_cpus(void)
  9. {
  10. static const char *fcpu = "/sys/devices/system/cpu/possible";
  11. unsigned int start, end, possible_cpus = 0;
  12. char buff[128];
  13. FILE *fp;
  14. int len, n, i, j = 0;
  15. fp = fopen(fcpu, "r");
  16. if (!fp) {
  17. printf("Failed to open %s: '%s'!\n", fcpu, strerror(errno));
  18. exit(1);
  19. }
  20. if (!fgets(buff, sizeof(buff), fp)) {
  21. printf("Failed to read %s!\n", fcpu);
  22. exit(1);
  23. }
  24. len = strlen(buff);
  25. for (i = 0; i <= len; i++) {
  26. if (buff[i] == ',' || buff[i] == '\0') {
  27. buff[i] = '\0';
  28. n = sscanf(&buff[j], "%u-%u", &start, &end);
  29. if (n <= 0) {
  30. printf("Failed to retrieve # possible CPUs!\n");
  31. exit(1);
  32. } else if (n == 1) {
  33. end = start;
  34. }
  35. possible_cpus += end - start + 1;
  36. j = i + 1;
  37. }
  38. }
  39. fclose(fp);
  40. return possible_cpus;
  41. }
  42. #define __bpf_percpu_val_align __attribute__((__aligned__(8)))
  43. #define BPF_DECLARE_PERCPU(type, name) \
  44. struct { type v; /* padding */ } __bpf_percpu_val_align \
  45. name[bpf_num_possible_cpus()]
  46. #define bpf_percpu(name, cpu) name[(cpu)].v
  47. #ifndef ARRAY_SIZE
  48. # define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
  49. #endif
  50. #endif /* __BPF_UTIL__ */