lwt_len_hist_kern.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* Copyright (c) 2016 Thomas Graf <tgraf@tgraf.ch>
  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. * This program is distributed in the hope that it will be useful, but
  8. * WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. * General Public License for more details.
  11. */
  12. #include <uapi/linux/bpf.h>
  13. #include <uapi/linux/if_ether.h>
  14. #include <uapi/linux/ip.h>
  15. #include <uapi/linux/in.h>
  16. #include <bpf/bpf_helpers.h>
  17. # define printk(fmt, ...) \
  18. ({ \
  19. char ____fmt[] = fmt; \
  20. bpf_trace_printk(____fmt, sizeof(____fmt), \
  21. ##__VA_ARGS__); \
  22. })
  23. struct bpf_elf_map {
  24. __u32 type;
  25. __u32 size_key;
  26. __u32 size_value;
  27. __u32 max_elem;
  28. __u32 flags;
  29. __u32 id;
  30. __u32 pinning;
  31. };
  32. struct bpf_elf_map SEC("maps") lwt_len_hist_map = {
  33. .type = BPF_MAP_TYPE_PERCPU_HASH,
  34. .size_key = sizeof(__u64),
  35. .size_value = sizeof(__u64),
  36. .pinning = 2,
  37. .max_elem = 1024,
  38. };
  39. static unsigned int log2(unsigned int v)
  40. {
  41. unsigned int r;
  42. unsigned int shift;
  43. r = (v > 0xFFFF) << 4; v >>= r;
  44. shift = (v > 0xFF) << 3; v >>= shift; r |= shift;
  45. shift = (v > 0xF) << 2; v >>= shift; r |= shift;
  46. shift = (v > 0x3) << 1; v >>= shift; r |= shift;
  47. r |= (v >> 1);
  48. return r;
  49. }
  50. static unsigned int log2l(unsigned long v)
  51. {
  52. unsigned int hi = v >> 32;
  53. if (hi)
  54. return log2(hi) + 32;
  55. else
  56. return log2(v);
  57. }
  58. SEC("len_hist")
  59. int do_len_hist(struct __sk_buff *skb)
  60. {
  61. __u64 *value, key, init_val = 1;
  62. key = log2l(skb->len);
  63. value = bpf_map_lookup_elem(&lwt_len_hist_map, &key);
  64. if (value)
  65. __sync_fetch_and_add(value, 1);
  66. else
  67. bpf_map_update_elem(&lwt_len_hist_map, &key, &init_val, BPF_ANY);
  68. return BPF_OK;
  69. }
  70. char _license[] SEC("license") = "GPL";