tracex3_kern.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 start_key {
  14. dev_t dev;
  15. u32 _pad;
  16. sector_t sector;
  17. };
  18. struct {
  19. __uint(type, BPF_MAP_TYPE_HASH);
  20. __type(key, long);
  21. __type(value, u64);
  22. __uint(max_entries, 4096);
  23. } my_map SEC(".maps");
  24. /* from /sys/kernel/tracing/events/block/block_io_start/format */
  25. SEC("tracepoint/block/block_io_start")
  26. int bpf_prog1(struct trace_event_raw_block_rq *ctx)
  27. {
  28. u64 val = bpf_ktime_get_ns();
  29. struct start_key key = {
  30. .dev = ctx->dev,
  31. .sector = ctx->sector
  32. };
  33. bpf_map_update_elem(&my_map, &key, &val, BPF_ANY);
  34. return 0;
  35. }
  36. static unsigned int log2l(unsigned long long n)
  37. {
  38. #define S(k) if (n >= (1ull << k)) { i += k; n >>= k; }
  39. int i = -(n == 0);
  40. S(32); S(16); S(8); S(4); S(2); S(1);
  41. return i;
  42. #undef S
  43. }
  44. #define SLOTS 100
  45. struct {
  46. __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
  47. __uint(key_size, sizeof(u32));
  48. __uint(value_size, sizeof(u64));
  49. __uint(max_entries, SLOTS);
  50. } lat_map SEC(".maps");
  51. /* from /sys/kernel/tracing/events/block/block_io_done/format */
  52. SEC("tracepoint/block/block_io_done")
  53. int bpf_prog2(struct trace_event_raw_block_rq *ctx)
  54. {
  55. struct start_key key = {
  56. .dev = ctx->dev,
  57. .sector = ctx->sector
  58. };
  59. u64 *value, l, base;
  60. u32 index;
  61. value = bpf_map_lookup_elem(&my_map, &key);
  62. if (!value)
  63. return 0;
  64. u64 cur_time = bpf_ktime_get_ns();
  65. u64 delta = cur_time - *value;
  66. bpf_map_delete_elem(&my_map, &key);
  67. /* the lines below are computing index = log10(delta)*10
  68. * using integer arithmetic
  69. * index = 29 ~ 1 usec
  70. * index = 59 ~ 1 msec
  71. * index = 89 ~ 1 sec
  72. * index = 99 ~ 10sec or more
  73. * log10(x)*10 = log2(x)*10/log2(10) = log2(x)*3
  74. */
  75. l = log2l(delta);
  76. base = 1ll << l;
  77. index = (l * 64 + (delta - base) * 64 / base) * 3 / 64;
  78. if (index >= SLOTS)
  79. index = SLOTS - 1;
  80. value = bpf_map_lookup_elem(&lat_map, &index);
  81. if (value)
  82. *value += 1;
  83. return 0;
  84. }
  85. char _license[] SEC("license") = "GPL";
  86. u32 _version SEC("version") = LINUX_VERSION_CODE;