perf_callchain.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SPDX-License-Identifier: GPL-2.0
  2. /* Copyright (C) 2019 Hangzhou C-SKY Microsystems co.,ltd. */
  3. #include <linux/perf_event.h>
  4. #include <linux/uaccess.h>
  5. #include <asm/stacktrace.h>
  6. /*
  7. * Get the return address for a single stackframe and return a pointer to the
  8. * next frame tail.
  9. */
  10. static unsigned long user_backtrace(struct perf_callchain_entry_ctx *entry,
  11. unsigned long fp, unsigned long reg_ra)
  12. {
  13. struct stackframe buftail;
  14. unsigned long ra = 0;
  15. unsigned long __user *user_frame_tail =
  16. (unsigned long __user *)(fp - sizeof(struct stackframe));
  17. /* Check accessibility of one struct frame_tail beyond */
  18. if (!access_ok(user_frame_tail, sizeof(buftail)))
  19. return 0;
  20. if (__copy_from_user_inatomic(&buftail, user_frame_tail,
  21. sizeof(buftail)))
  22. return 0;
  23. if (reg_ra != 0)
  24. ra = reg_ra;
  25. else
  26. ra = buftail.ra;
  27. fp = buftail.fp;
  28. if (ra != 0)
  29. perf_callchain_store(entry, ra);
  30. else
  31. return 0;
  32. return fp;
  33. }
  34. /*
  35. * This will be called when the target is in user mode
  36. * This function will only be called when we use
  37. * "PERF_SAMPLE_CALLCHAIN" in
  38. * kernel/events/core.c:perf_prepare_sample()
  39. *
  40. * How to trigger perf_callchain_[user/kernel] :
  41. * $ perf record -e cpu-clock --call-graph fp ./program
  42. * $ perf report --call-graph
  43. *
  44. * On RISC-V platform, the program being sampled and the C library
  45. * need to be compiled with -fno-omit-frame-pointer, otherwise
  46. * the user stack will not contain function frame.
  47. */
  48. void perf_callchain_user(struct perf_callchain_entry_ctx *entry,
  49. struct pt_regs *regs)
  50. {
  51. unsigned long fp = 0;
  52. fp = regs->s0;
  53. perf_callchain_store(entry, regs->epc);
  54. fp = user_backtrace(entry, fp, regs->ra);
  55. while (fp && !(fp & 0x3) && entry->nr < entry->max_stack)
  56. fp = user_backtrace(entry, fp, 0);
  57. }
  58. static bool fill_callchain(void *entry, unsigned long pc)
  59. {
  60. return perf_callchain_store(entry, pc) == 0;
  61. }
  62. void perf_callchain_kernel(struct perf_callchain_entry_ctx *entry,
  63. struct pt_regs *regs)
  64. {
  65. walk_stackframe(NULL, regs, fill_callchain, entry);
  66. }