faultbook.rs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. //! A book of the title's write faults on guarded view memory
  2. //! (`VICTORY_FAULT_BOOK=<file>`; builds with diagnostics): which block, when
  3. //! in the frame, what it waited for, and what else happened to the block
  4. //! (taken by a refresh, asked about), for 40 frames from each of the times
  5. //! `VICTORY_FAULT_BOOK_AT` gives (seconds after the start; 150,210,270 unless
  6. //! given). Written as `<file>.<n>.bin`, records of 40 bytes: ticks of the
  7. //! performance counter, two words, thread, what.
  8. #![cfg(feature = "diagnostics")]
  9. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
  10. use std::sync::{Mutex, OnceLock};
  11. /// What a record is of.
  12. #[derive(Clone, Copy)]
  13. #[repr(u32)]
  14. pub(crate) enum What {
  15. /// A frame ended (a: its number).
  16. Frame = 0,
  17. /// A write fault opened block `a`; b: blocks opened with it (the upper
  18. /// 32 bits), nanoseconds of waiting for the guards' lock; c: nanoseconds
  19. /// with it.
  20. Fault = 1,
  21. /// Blocks `[a, b)` were found written, or never taken, and made read-only.
  22. Taken = 2,
  23. /// `[a, b)` was asked about and known unwritten by its bits.
  24. Known = 3,
  25. /// `[a, b)` was asked about block by block; c: how many were written.
  26. Asked = 4,
  27. /// We opened block `a` ourselves.
  28. Ours = 5,
  29. /// Another view of a page taken, block `a`, was made read-only.
  30. Alias = 6,
  31. /// A fault on block `a` that someone else had opened; b: nanoseconds.
  32. Open = 7,
  33. /// The instruction at `a` made the fault before (block `b`).
  34. Site = 9,
  35. /// A store (the instruction at `a`) was done beside the guard of block
  36. /// `b`.
  37. Stored = 10,
  38. }
  39. #[repr(C)]
  40. #[derive(Clone, Copy)]
  41. struct Record {
  42. at: i64,
  43. a: u64,
  44. b: u64,
  45. c: u64,
  46. thread: u32,
  47. what: u32,
  48. }
  49. static ON: AtomicBool = AtomicBool::new(false);
  50. static BOOK: Mutex<Vec<Record>> = Mutex::new(Vec::new());
  51. fn ticks() -> i64 {
  52. let mut t = 0;
  53. // SAFETY: an out pointer of the right size.
  54. unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut t) };
  55. t
  56. }
  57. /// Whether records are kept now.
  58. pub(crate) fn on() -> bool {
  59. ON.load(Relaxed)
  60. }
  61. pub(crate) fn note(what: What, a: usize, b: usize, c: u64) {
  62. if !on() {
  63. return;
  64. }
  65. // SAFETY: a question about this thread.
  66. let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
  67. let record = Record { at: ticks(), a: a as u64, b: b as u64, c, thread, what: what as u32 };
  68. BOOK.lock().unwrap_or_else(|e| e.into_inner()).push(record);
  69. }
  70. /// A frame ended.
  71. pub(crate) fn frame() {
  72. const FRAMES: u64 = 40;
  73. static SETTINGS: OnceLock<Option<(String, Vec<u64>)>> = OnceLock::new();
  74. static BEGAN: OnceLock<std::time::Instant> = OnceLock::new();
  75. static LEFT: AtomicU64 = AtomicU64::new(0);
  76. static MADE: AtomicU64 = AtomicU64::new(0);
  77. let began = *BEGAN.get_or_init(std::time::Instant::now);
  78. let Some((file, times)) = SETTINGS.get_or_init(|| {
  79. let file = std::env::var("VICTORY_FAULT_BOOK").ok().filter(|f| !f.is_empty())?;
  80. let times = std::env::var("VICTORY_FAULT_BOOK_AT").unwrap_or_else(|_| "150,210,270".into());
  81. Some((file, times.split(',').filter_map(|t| t.trim().parse().ok()).collect()))
  82. }) else {
  83. return;
  84. };
  85. note(What::Frame, crate::frame::current() as usize, 0, 0);
  86. if on() {
  87. if LEFT.fetch_sub(1, Relaxed) > 1 {
  88. return;
  89. }
  90. ON.store(false, Relaxed);
  91. let records = std::mem::take(&mut *BOOK.lock().unwrap_or_else(|e| e.into_inner()));
  92. let file = format!("{file}.{}.bin", MADE.fetch_add(1, Relaxed));
  93. std::thread::spawn(move || {
  94. // SAFETY: plain data, every byte of it written.
  95. let bytes = unsafe { std::slice::from_raw_parts(records.as_ptr().cast::<u8>(), size_of_val(&records[..])) };
  96. match std::fs::write(&file, bytes) {
  97. Ok(()) => tracing::info!(file, records = records.len(), "book of faults written"),
  98. Err(e) => tracing::warn!(file, %e, "book of faults not written"),
  99. }
  100. });
  101. } else if times.get(MADE.load(Relaxed) as usize).is_some_and(|&t| began.elapsed().as_secs() >= t) {
  102. LEFT.store(FRAMES, Relaxed);
  103. ON.store(true, Relaxed);
  104. }
  105. }