tracex3_kern.c 2.1 KB

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