tracex3_kern.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* Copyright (c) 2013-2015 PLUMgrid, http://plumgrid.com
  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/skbuff.h>
  8. #include <linux/netdevice.h>
  9. #include <linux/version.h>
  10. #include <uapi/linux/bpf.h>
  11. #include "bpf_helpers.h"
  12. struct bpf_map_def SEC("maps") my_map = {
  13. .type = BPF_MAP_TYPE_HASH,
  14. .key_size = sizeof(long),
  15. .value_size = sizeof(u64),
  16. .max_entries = 4096,
  17. };
  18. /* kprobe is NOT a stable ABI. If kernel internals change this bpf+kprobe
  19. * example will no longer be meaningful
  20. */
  21. SEC("kprobe/blk_mq_start_request")
  22. int bpf_prog1(struct pt_regs *ctx)
  23. {
  24. long rq = PT_REGS_PARM1(ctx);
  25. u64 val = bpf_ktime_get_ns();
  26. bpf_map_update_elem(&my_map, &rq, &val, BPF_ANY);
  27. return 0;
  28. }
  29. static unsigned int log2l(unsigned long long n)
  30. {
  31. #define S(k) if (n >= (1ull << k)) { i += k; n >>= k; }
  32. int i = -(n == 0);
  33. S(32); S(16); S(8); S(4); S(2); S(1);
  34. return i;
  35. #undef S
  36. }
  37. #define SLOTS 100
  38. struct bpf_map_def SEC("maps") lat_map = {
  39. .type = BPF_MAP_TYPE_ARRAY,
  40. .key_size = sizeof(u32),
  41. .value_size = sizeof(u64),
  42. .max_entries = SLOTS,
  43. };
  44. SEC("kprobe/blk_update_request")
  45. int bpf_prog2(struct pt_regs *ctx)
  46. {
  47. long rq = PT_REGS_PARM1(ctx);
  48. u64 *value, l, base;
  49. u32 index;
  50. value = bpf_map_lookup_elem(&my_map, &rq);
  51. if (!value)
  52. return 0;
  53. u64 cur_time = bpf_ktime_get_ns();
  54. u64 delta = cur_time - *value;
  55. bpf_map_delete_elem(&my_map, &rq);
  56. /* the lines below are computing index = log10(delta)*10
  57. * using integer arithmetic
  58. * index = 29 ~ 1 usec
  59. * index = 59 ~ 1 msec
  60. * index = 89 ~ 1 sec
  61. * index = 99 ~ 10sec or more
  62. * log10(x)*10 = log2(x)*10/log2(10) = log2(x)*3
  63. */
  64. l = log2l(delta);
  65. base = 1ll << l;
  66. index = (l * 64 + (delta - base) * 64 / base) * 3 / 64;
  67. if (index >= SLOTS)
  68. index = SLOTS - 1;
  69. value = bpf_map_lookup_elem(&lat_map, &index);
  70. if (value)
  71. __sync_fetch_and_add((long *)value, 1);
  72. return 0;
  73. }
  74. char _license[] SEC("license") = "GPL";
  75. u32 _version SEC("version") = LINUX_VERSION_CODE;