tracex3.bpf.c 2.2 KB

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