trace_event_kern.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* Copyright (c) 2016 Facebook
  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/ptrace.h>
  8. #include <linux/version.h>
  9. #include <uapi/linux/bpf.h>
  10. #include <uapi/linux/bpf_perf_event.h>
  11. #include <uapi/linux/perf_event.h>
  12. #include "bpf_helpers.h"
  13. struct key_t {
  14. char comm[TASK_COMM_LEN];
  15. u32 kernstack;
  16. u32 userstack;
  17. };
  18. struct bpf_map_def SEC("maps") counts = {
  19. .type = BPF_MAP_TYPE_HASH,
  20. .key_size = sizeof(struct key_t),
  21. .value_size = sizeof(u64),
  22. .max_entries = 10000,
  23. };
  24. struct bpf_map_def SEC("maps") stackmap = {
  25. .type = BPF_MAP_TYPE_STACK_TRACE,
  26. .key_size = sizeof(u32),
  27. .value_size = PERF_MAX_STACK_DEPTH * sizeof(u64),
  28. .max_entries = 10000,
  29. };
  30. #define KERN_STACKID_FLAGS (0 | BPF_F_FAST_STACK_CMP)
  31. #define USER_STACKID_FLAGS (0 | BPF_F_FAST_STACK_CMP | BPF_F_USER_STACK)
  32. SEC("perf_event")
  33. int bpf_prog1(struct bpf_perf_event_data *ctx)
  34. {
  35. char fmt[] = "CPU-%d period %lld ip %llx";
  36. u32 cpu = bpf_get_smp_processor_id();
  37. struct key_t key;
  38. u64 *val, one = 1;
  39. if (ctx->sample_period < 10000)
  40. /* ignore warmup */
  41. return 0;
  42. bpf_get_current_comm(&key.comm, sizeof(key.comm));
  43. key.kernstack = bpf_get_stackid(ctx, &stackmap, KERN_STACKID_FLAGS);
  44. key.userstack = bpf_get_stackid(ctx, &stackmap, USER_STACKID_FLAGS);
  45. if ((int)key.kernstack < 0 && (int)key.userstack < 0) {
  46. bpf_trace_printk(fmt, sizeof(fmt), cpu, ctx->sample_period,
  47. PT_REGS_IP(&ctx->regs));
  48. return 0;
  49. }
  50. val = bpf_map_lookup_elem(&counts, &key);
  51. if (val)
  52. (*val)++;
  53. else
  54. bpf_map_update_elem(&counts, &key, &one, BPF_NOEXIST);
  55. return 0;
  56. }
  57. char _license[] SEC("license") = "GPL";