spans.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. //! Diagnostics: how long the card itself works on our submissions, by its own
  2. //! timestamps (`VICTORY_CARD_SPANS=1`). The clock of the frame line
  3. //! (`card_clock_line`) counts from the call that sends a submission to the
  4. //! moment a thread of ours wakes behind its last signal: the time the system
  5. //! takes to hand a submission to the card and to report it done is in it, 40
  6. //! times a frame. Here two lists made once, of nothing but a timestamp, stand
  7. //! around each submission.
  8. use std::sync::Mutex;
  9. use windows::Win32::Graphics::Direct3D12::*;
  10. use windows::core::Interface;
  11. use super::Host;
  12. /// Submissions stamped before the first stamps are read and used again.
  13. const SPANS: usize = 512;
  14. /// The stamps of one queue's submissions.
  15. pub(super) struct Spans {
  16. _allocator: ID3D12CommandAllocator,
  17. _heap: ID3D12QueryHeap,
  18. _back: ID3D12Resource,
  19. /// The mapped results, two a submission.
  20. data: usize,
  21. lists: Vec<ID3D12CommandList>,
  22. ticks_per_ms: f64,
  23. next: usize,
  24. sums: Sums,
  25. }
  26. // SAFETY: free-threaded objects and a mapping only read behind a lock.
  27. unsafe impl Send for Spans {}
  28. /// What the stamps read so far add up to.
  29. #[derive(Debug, Default, Clone, Copy, PartialEq)]
  30. struct Sums {
  31. /// Submissions, ticks the card worked on them, ticks between them.
  32. count: u64,
  33. busy: u64,
  34. between: u64,
  35. /// Ticks of the longest one, and the last one's end.
  36. longest: u64,
  37. last: u64,
  38. }
  39. impl Sums {
  40. /// A submission that ran from `start` to `end` (card ticks), after those
  41. /// before it. The start's stamp may be of before the last one's end: the
  42. /// part before that end is the last one's.
  43. fn add(&mut self, start: u64, end: u64) {
  44. if start == 0 || end < start {
  45. return;
  46. }
  47. let start = start.max(self.last);
  48. let took = end.saturating_sub(start);
  49. if self.last != 0 {
  50. self.between += start - self.last;
  51. }
  52. self.count += 1;
  53. self.busy += took;
  54. self.longest = self.longest.max(took);
  55. self.last = end.max(self.last);
  56. }
  57. }
  58. fn on() -> bool {
  59. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  60. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_SPANS").is_some_and(|v| v == "1"))
  61. }
  62. static SPANS_MADE: Mutex<Option<Option<Spans>>> = Mutex::new(None);
  63. impl Host {
  64. /// The lists that go in front of and behind a submission about to be
  65. /// sent to the drawing queue, if stamps are asked for.
  66. pub(super) fn span_lists(&self) -> Option<[ID3D12CommandList; 2]> {
  67. if !on() {
  68. return None;
  69. }
  70. let mut made = SPANS_MADE.lock().unwrap_or_else(|e| e.into_inner());
  71. let spans = made
  72. .get_or_insert_with(|| {
  73. self.make_spans()
  74. .inspect_err(|e| tracing::warn!(error = %e, "no stamps around submissions"))
  75. .ok()
  76. })
  77. .as_mut()?;
  78. let i = spans.next;
  79. spans.next = (i + 1) % SPANS;
  80. // The stamps of the submission that had these lists, that many
  81. // submissions ago: long done.
  82. // SAFETY: inside the mapping; written by the card at whole words.
  83. let (start, end) = unsafe {
  84. let at = (spans.data as *mut u64).add(2 * i);
  85. let read = (at.read_volatile(), at.add(1).read_volatile());
  86. at.write_volatile(0);
  87. at.add(1).write_volatile(0);
  88. read
  89. };
  90. spans.sums.add(start, end);
  91. Some([spans.lists[2 * i].clone(), spans.lists[2 * i + 1].clone()])
  92. }
  93. fn make_spans(&self) -> windows::core::Result<Spans> {
  94. let device = &self.device;
  95. // SAFETY: plain object creation; lists of one allocator recorded one
  96. // after the other.
  97. unsafe {
  98. let mut heap: Option<ID3D12QueryHeap> = None;
  99. device.CreateQueryHeap(
  100. &D3D12_QUERY_HEAP_DESC {
  101. Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
  102. Count: 2 * SPANS as u32,
  103. NodeMask: 0,
  104. },
  105. &mut heap,
  106. )?;
  107. let heap = heap.ok_or_else(windows::core::Error::empty)?;
  108. let back = self.read_back_buffer(16 * SPANS as u64).ok_or_else(windows::core::Error::empty)?;
  109. let mut data = std::ptr::null_mut();
  110. back.Map(0, None, Some(&mut data))?;
  111. std::ptr::write_bytes(data.cast::<u8>(), 0, 16 * SPANS);
  112. let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  113. let mut lists = Vec::with_capacity(2 * SPANS);
  114. for i in 0..2 * SPANS as u32 {
  115. let list: ID3D12GraphicsCommandList =
  116. device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  117. list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, i);
  118. list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, &back, u64::from(i) * 8);
  119. list.Close()?;
  120. lists.push(list.cast()?);
  121. }
  122. Ok(Spans {
  123. _allocator: allocator,
  124. _heap: heap,
  125. _back: back,
  126. data: data as usize,
  127. lists,
  128. ticks_per_ms: self.queue.GetTimestampFrequency()? as f64 / 1000.0,
  129. next: 0,
  130. sums: Sums::default(),
  131. })
  132. }
  133. }
  134. }
  135. /// The GPU timestamps the title was given since the last frame-rate line:
  136. /// how many, how often a later one was 1 ms or more after the one before
  137. /// (written with another submission), and where the first few lie.
  138. static STAMPED: Mutex<(u64, u64, u64, Vec<usize>)> = Mutex::new((0, 0, 0, Vec::new()));
  139. /// The title's GPU timestamp at `at` was given the value `now` (ticks of 10
  140. /// ns).
  141. pub(crate) fn stamped(at: usize, now: u64) {
  142. if !on() {
  143. return;
  144. }
  145. let mut s = STAMPED.lock().unwrap_or_else(|e| e.into_inner());
  146. s.0 += 1;
  147. s.1 += u64::from(now.saturating_sub(s.2) > 100_000);
  148. s.2 = now;
  149. if s.3.len() < 64 && !s.3.contains(&at) {
  150. s.3.push(at);
  151. tracing::info!(address = format_args!("{at:#x}"), now, "a GPU timestamp of the title");
  152. }
  153. }
  154. /// The viewports' sizes seen (each said once): whether the title draws its
  155. /// scene at sizes of its choice.
  156. pub(crate) fn viewport(width: u32, height: u32) {
  157. if !on() || width < 1024 || height < 576 {
  158. return;
  159. }
  160. static SEEN: Mutex<Vec<(u32, u32)>> = Mutex::new(Vec::new());
  161. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  162. if seen.len() < 200 && !seen.contains(&(width, height)) {
  163. seen.push((width, height));
  164. tracing::info!(width, height, "a viewport of the title");
  165. }
  166. }
  167. /// For the frame-rate line: what the stamps read since the last one say, per
  168. /// frame (they are of some [`SPANS`] submissions ago).
  169. pub(super) fn line(frames: f64) {
  170. {
  171. let mut s = STAMPED.lock().unwrap_or_else(|e| e.into_inner());
  172. if s.0 > 0 {
  173. tracing::info!(
  174. "GPU timestamps the title asked for per frame: {:.1}, in {:.1} groups written at one time",
  175. s.0 as f64 / frames,
  176. s.1 as f64 / frames
  177. );
  178. }
  179. (s.0, s.1) = (0, 0);
  180. }
  181. let mut made = SPANS_MADE.lock().unwrap_or_else(|e| e.into_inner());
  182. let Some(Some(spans)) = made.as_mut() else {
  183. return;
  184. };
  185. let last = spans.sums.last;
  186. let s = std::mem::replace(&mut spans.sums, Sums { last, ..Sums::default() });
  187. let ms = |ticks: u64| ticks as f64 / spans.ticks_per_ms / frames;
  188. tracing::info!(
  189. "the card's own stamps per frame: {:.1} submissions, working {:.1} ms, idle between them {:.1} ms, the longest {:.1} ms",
  190. s.count as f64 / frames,
  191. ms(s.busy),
  192. ms(s.between),
  193. s.longest as f64 / spans.ticks_per_ms
  194. );
  195. }
  196. #[cfg(test)]
  197. mod tests {
  198. use super::Sums;
  199. #[test]
  200. fn submissions_add_up_without_counting_anything_twice() {
  201. let mut s = Sums::default();
  202. s.add(100, 150);
  203. s.add(140, 200); // began before the last one ended
  204. s.add(260, 270);
  205. assert_eq!((s.count, s.busy, s.between, s.longest, s.last), (3, 110, 60, 50, 270));
  206. // Never written, or nonsense: nothing.
  207. s.add(0, 0);
  208. s.add(300, 290);
  209. assert_eq!(s.count, 3);
  210. // Whole inside the last one.
  211. s.add(265, 268);
  212. assert_eq!((s.count, s.busy, s.between), (4, 110, 60));
  213. }
  214. }