tracex2_user.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <signal.h>
  5. #include <linux/bpf.h>
  6. #include "libbpf.h"
  7. #include "bpf_load.h"
  8. #define MAX_INDEX 64
  9. #define MAX_STARS 38
  10. static void stars(char *str, long val, long max, int width)
  11. {
  12. int i;
  13. for (i = 0; i < (width * val / max) - 1 && i < width - 1; i++)
  14. str[i] = '*';
  15. if (val > max)
  16. str[i - 1] = '+';
  17. str[i] = '\0';
  18. }
  19. static void print_hist(int fd)
  20. {
  21. int key;
  22. long value;
  23. long data[MAX_INDEX] = {};
  24. char starstr[MAX_STARS];
  25. int i;
  26. int max_ind = -1;
  27. long max_value = 0;
  28. for (key = 0; key < MAX_INDEX; key++) {
  29. bpf_lookup_elem(fd, &key, &value);
  30. data[key] = value;
  31. if (value && key > max_ind)
  32. max_ind = key;
  33. if (value > max_value)
  34. max_value = value;
  35. }
  36. printf(" syscall write() stats\n");
  37. printf(" byte_size : count distribution\n");
  38. for (i = 1; i <= max_ind + 1; i++) {
  39. stars(starstr, data[i - 1], max_value, MAX_STARS);
  40. printf("%8ld -> %-8ld : %-8ld |%-*s|\n",
  41. (1l << i) >> 1, (1l << i) - 1, data[i - 1],
  42. MAX_STARS, starstr);
  43. }
  44. }
  45. static void int_exit(int sig)
  46. {
  47. print_hist(map_fd[1]);
  48. exit(0);
  49. }
  50. int main(int ac, char **argv)
  51. {
  52. char filename[256];
  53. long key, next_key, value;
  54. FILE *f;
  55. int i;
  56. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  57. signal(SIGINT, int_exit);
  58. /* start 'ping' in the background to have some kfree_skb events */
  59. f = popen("ping -c5 localhost", "r");
  60. (void) f;
  61. /* start 'dd' in the background to have plenty of 'write' syscalls */
  62. f = popen("dd if=/dev/zero of=/dev/null count=5000000", "r");
  63. (void) f;
  64. if (load_bpf_file(filename)) {
  65. printf("%s", bpf_log_buf);
  66. return 1;
  67. }
  68. for (i = 0; i < 5; i++) {
  69. key = 0;
  70. while (bpf_get_next_key(map_fd[0], &key, &next_key) == 0) {
  71. bpf_lookup_elem(map_fd[0], &next_key, &value);
  72. printf("location 0x%lx count %ld\n", next_key, value);
  73. key = next_key;
  74. }
  75. if (key)
  76. printf("\n");
  77. sleep(1);
  78. }
  79. print_hist(map_fd[1]);
  80. return 0;
  81. }