ring_buffer.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #ifndef _TOOLS_LINUX_RING_BUFFER_H_
  2. #define _TOOLS_LINUX_RING_BUFFER_H_
  3. #include <asm/barrier.h>
  4. #include <linux/perf_event.h>
  5. /*
  6. * Contract with kernel for walking the perf ring buffer from
  7. * user space requires the following barrier pairing (quote
  8. * from kernel/events/ring_buffer.c):
  9. *
  10. * Since the mmap() consumer (userspace) can run on a
  11. * different CPU:
  12. *
  13. * kernel user
  14. *
  15. * if (LOAD ->data_tail) { LOAD ->data_head
  16. * (A) smp_rmb() (C)
  17. * STORE $data LOAD $data
  18. * smp_wmb() (B) smp_mb() (D)
  19. * STORE ->data_head STORE ->data_tail
  20. * }
  21. *
  22. * Where A pairs with D, and B pairs with C.
  23. *
  24. * In our case A is a control dependency that separates the
  25. * load of the ->data_tail and the stores of $data. In case
  26. * ->data_tail indicates there is no room in the buffer to
  27. * store $data we do not.
  28. *
  29. * D needs to be a full barrier since it separates the data
  30. * READ from the tail WRITE.
  31. *
  32. * For B a WMB is sufficient since it separates two WRITEs,
  33. * and for C an RMB is sufficient since it separates two READs.
  34. *
  35. * Note, instead of B, C, D we could also use smp_store_release()
  36. * in B and D as well as smp_load_acquire() in C.
  37. *
  38. * However, this optimization does not make sense for all kernel
  39. * supported architectures since for a fair number it would
  40. * resolve into READ_ONCE() + smp_mb() pair for smp_load_acquire(),
  41. * and smp_mb() + WRITE_ONCE() pair for smp_store_release().
  42. *
  43. * Thus for those smp_wmb() in B and smp_rmb() in C would still
  44. * be less expensive. For the case of D this has either the same
  45. * cost or is less expensive, for example, due to TSO x86 can
  46. * avoid the CPU barrier entirely.
  47. */
  48. static inline u64 ring_buffer_read_head(struct perf_event_mmap_page *base)
  49. {
  50. /*
  51. * Architectures where smp_load_acquire() does not fallback to
  52. * READ_ONCE() + smp_mb() pair.
  53. */
  54. #if defined(__x86_64__) || defined(__aarch64__) || defined(__powerpc64__) || \
  55. defined(__ia64__) || defined(__sparc__) && defined(__arch64__)
  56. return smp_load_acquire(&base->data_head);
  57. #else
  58. u64 head = READ_ONCE(base->data_head);
  59. smp_rmb();
  60. return head;
  61. #endif
  62. }
  63. static inline void ring_buffer_write_tail(struct perf_event_mmap_page *base,
  64. u64 tail)
  65. {
  66. smp_store_release(&base->data_tail, tail);
  67. }
  68. #endif /* _TOOLS_LINUX_RING_BUFFER_H_ */