xdp1_user.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Copyright (c) 2016 PLUMgrid
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of version 2 of the GNU General Public
  5. * License as published by the Free Software Foundation.
  6. */
  7. #include <linux/bpf.h>
  8. #include <assert.h>
  9. #include <errno.h>
  10. #include <signal.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <unistd.h>
  15. #include "bpf_load.h"
  16. #include "bpf_util.h"
  17. #include "libbpf.h"
  18. static int ifindex;
  19. static void int_exit(int sig)
  20. {
  21. set_link_xdp_fd(ifindex, -1);
  22. exit(0);
  23. }
  24. /* simple per-protocol drop counter
  25. */
  26. static void poll_stats(int interval)
  27. {
  28. unsigned int nr_cpus = bpf_num_possible_cpus();
  29. const unsigned int nr_keys = 256;
  30. __u64 values[nr_cpus], prev[nr_keys][nr_cpus];
  31. __u32 key;
  32. int i;
  33. memset(prev, 0, sizeof(prev));
  34. while (1) {
  35. sleep(interval);
  36. for (key = 0; key < nr_keys; key++) {
  37. __u64 sum = 0;
  38. assert(bpf_map_lookup_elem(map_fd[0], &key, values) == 0);
  39. for (i = 0; i < nr_cpus; i++)
  40. sum += (values[i] - prev[key][i]);
  41. if (sum)
  42. printf("proto %u: %10llu pkt/s\n",
  43. key, sum / interval);
  44. memcpy(prev[key], values, sizeof(values));
  45. }
  46. }
  47. }
  48. int main(int ac, char **argv)
  49. {
  50. char filename[256];
  51. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  52. if (ac != 2) {
  53. printf("usage: %s IFINDEX\n", argv[0]);
  54. return 1;
  55. }
  56. ifindex = strtoul(argv[1], NULL, 0);
  57. if (load_bpf_file(filename)) {
  58. printf("%s", bpf_log_buf);
  59. return 1;
  60. }
  61. if (!prog_fd[0]) {
  62. printf("load_bpf_file: %s\n", strerror(errno));
  63. return 1;
  64. }
  65. signal(SIGINT, int_exit);
  66. if (set_link_xdp_fd(ifindex, prog_fd[0]) < 0) {
  67. printf("link set xdp fd failed\n");
  68. return 1;
  69. }
  70. poll_stats(2);
  71. return 0;
  72. }