copystat.rs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. //! Diagnostics: where the submission copies of title memory go (which
  2. //! ranges, how often, of what memory) and what limits their rate, logged
  3. //! with the frame-rate line. `VICTORY_COPY_MODE=plain` copies without the
  4. //! mapped-page guard, `none` skips the copies (both for timing only).
  5. use std::collections::HashMap;
  6. use std::sync::Mutex;
  7. use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
  8. /// Counters since the last line.
  9. pub(crate) enum C {
  10. Submissions,
  11. Copies,
  12. CopyBytes,
  13. Refreshes,
  14. RefreshBytes,
  15. Skipped,
  16. SkippedBytes,
  17. Runs,
  18. RunUs,
  19. Queries,
  20. QueryUs,
  21. MoveUs,
  22. Unmapped,
  23. /// Write-watch askings and their time.
  24. Watches,
  25. WatchUs,
  26. /// Bytes of watched ranges checked, and of those found unchanged.
  27. Checked,
  28. Unchanged,
  29. /// Copies that met an unmapped page.
  30. Fallbacks,
  31. /// Writes taken by the guard on view memory.
  32. GuardFaults,
  33. /// Texture bytes detiled after a watched write; hashed; detiled after a
  34. /// hash change.
  35. TexWatched,
  36. TexHashed,
  37. TexChanged,
  38. /// Changes of guarded textures the hash found and the guard did not see.
  39. TexHot,
  40. /// Frames presented since the last line (what the line divides by).
  41. Frames,
  42. /// Calls of list methods that record into a host list, and the
  43. /// nanoseconds they took, summed over the title's recording threads.
  44. RecordCalls,
  45. RecordNs,
  46. /// Waiting for host pipelines being made (`pipeline::make`).
  47. PipelineWaitUs,
  48. /// Dynamic descriptor slots: tables asked for, refused (no free run),
  49. /// and the nanoseconds of the searches.
  50. DynamicAsked,
  51. DynamicRefused,
  52. DynamicNs,
  53. /// Marker texts for device-removed data (`HostList::note`).
  54. NoteNs,
  55. /// Ranges given to shaders (steps), their snapshots, and the bytes
  56. /// compared after the submission.
  57. GpuWrites,
  58. SnapshotUs,
  59. BackCompared,
  60. /// Reading around unmapped pages after a failed bulk read.
  61. SparseUs,
  62. /// Guarding view memory (part of the write-watch askings' time).
  63. GuardUs,
  64. /// Bytes copied whole because their memory is neither write-watched
  65. /// nor a view (`Shadow::update_free`).
  66. WholeBytes,
  67. /// Submissions with ranges shaders write (they need the GPU's results
  68. /// before they return).
  69. BackSubmissions,
  70. /// The title's frame waits (`frame::wait`) and the time slept in them,
  71. /// over all its threads.
  72. PaceWaits,
  73. PaceUs,
  74. /// After a present: until the title's first list call and until its
  75. /// first submission; and from its last submission to its next present.
  76. UntilRecordUs,
  77. UntilSubmitUs,
  78. TailUs,
  79. /// Resetting host lists (`HostList::reset`).
  80. ResetNs,
  81. /// What shaders wrote: finding the 64 KiB pieces that differ, how many
  82. /// do, and putting them into title memory.
  83. BackScanUs,
  84. BackDiffer,
  85. BackSyncUs,
  86. /// Texture uploads recorded, and left out as unchanged.
  87. TexUploads,
  88. TexSkipped,
  89. /// Held submissions a present ran although their waits were not met.
  90. Forced,
  91. /// Ranges named through unordered access views by shaders that cannot
  92. /// store to buffers, not given to shaders as written, and their bytes.
  93. GpuWritesLeftOut,
  94. GpuWritesLeftOutBytes,
  95. /// Waits for memory values looked at (`list::ValueWait::met`) and the
  96. /// nanoseconds the looks took, on every thread.
  97. WaitChecks,
  98. WaitCheckNs,
  99. /// Host lists made (`Host::new_list`: for the lists a queue holds and
  100. /// for the parts of lists cut at waits) and the nanoseconds that took.
  101. HostLists,
  102. HostListNs,
  103. /// Parts of held submissions that ran while the part behind them could
  104. /// have run with them (its waits were met already).
  105. PartsTogether,
  106. /// Microseconds of the copies counted in `WholeBytes`.
  107. WholeUs,
  108. /// Submissions by how long the card was waited for (under 2 ms, 2-8,
  109. /// 8-32, longer), and the microseconds waited in each class.
  110. CardUnder2,
  111. Card2To8,
  112. Card8To32,
  113. CardOver32,
  114. CardUnder2Us,
  115. Card2To8Us,
  116. Card8To32Us,
  117. CardOver32Us,
  118. /// Submissions that hand nothing back to the title (no range shaders
  119. /// write, no value written when done), and the microseconds the card
  120. /// was waited for them.
  121. NothingBack,
  122. NothingBackUs,
  123. /// Waits for every earlier shader write recorded into host lists: for
  124. /// the title's barrier groups, for its barriers on buffers, and the
  125. /// indirect commands bounded (each a dispatch of ours between two such
  126. /// waits).
  127. WaitsForGroups,
  128. WaitsForBuffers,
  129. IndirectBounded,
  130. }
  131. const COUNTERS: usize = 80;
  132. static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS];
  133. pub(crate) fn add(c: C, n: u64) {
  134. COUNT[c as usize].fetch_add(n, Relaxed);
  135. }
  136. /// How copies run: 0 guarded (as always), 1 plain, 2 not at all.
  137. pub(crate) fn mode() -> u8 {
  138. static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  139. *MODE.get_or_init(|| match std::env::var("VICTORY_COPY_MODE").as_deref() {
  140. Ok("plain") => 1,
  141. Ok("none") => 2,
  142. _ => 0,
  143. })
  144. }
  145. /// Per source range (start, length): copies, bytes, microseconds, memory type.
  146. type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>;
  147. static RANGES: Mutex<Option<Ranges>> = Mutex::new(None);
  148. /// Per range copied whole because its memory is not watched (start,
  149. /// length): copies and microseconds.
  150. static WHOLE: Mutex<Option<HashMap<(usize, usize), (u64, u64)>>> = Mutex::new(None);
  151. /// `len` bytes at `src`, memory that is not watched, were copied whole in
  152. /// `us`.
  153. pub(crate) fn whole(src: usize, len: usize, us: u64) {
  154. add(C::WholeUs, us);
  155. let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner());
  156. let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0));
  157. e.0 += 1;
  158. e.1 += us;
  159. }
  160. /// The longest wait for the card since the last line: microseconds, and
  161. /// what ran (lists and pipelines).
  162. static LONGEST: Mutex<(u64, String)> = Mutex::new((0, String::new()));
  163. /// The waits for the card since the last line by what ran (lists and
  164. /// pipelines): how many, and their microseconds.
  165. static WAITS_BY_WORK: Mutex<Option<HashMap<String, (u64, u64)>>> = Mutex::new(None);
  166. /// With `VICTORY_GPU_TIMING`: the commands' time on the card since the last
  167. /// line by what they ran (a pipeline, or the kind of command): how many,
  168. /// their microseconds, and the longest one's.
  169. static COMMANDS_BY_WORK: Mutex<Option<HashMap<String, (u64, u64, u64)>>> = Mutex::new(None);
  170. /// A command took `ms` on the card (timing run). `op` is its note: the
  171. /// kind and size first, then the pipeline in brackets, then what it binds.
  172. pub(crate) fn command_took(op: &str, ms: f64) {
  173. let us = (ms * 1e3) as u64;
  174. let mut by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner());
  175. let e = by.get_or_insert_with(HashMap::new).entry(command_key(op)).or_insert((0, 0, 0));
  176. e.0 += 1;
  177. e.1 += us;
  178. e.2 = e.2.max(us);
  179. }
  180. /// What a command's note is summed under: its pipeline (`[compute ...]`,
  181. /// `[mesh ..., pixel ...]`) with the command's first word, or without a
  182. /// pipeline its first two words.
  183. fn command_key(op: &str) -> String {
  184. let head = op.split(" | ").next().unwrap_or(op);
  185. let word = head.split(' ').next().unwrap_or("");
  186. match (head.find('['), head.find(']')) {
  187. (Some(a), Some(b)) if a < b => format!("{word} {}", &head[a..=b]),
  188. _ => head.split(' ').take(2).collect::<Vec<_>>().join(" "),
  189. }
  190. }
  191. /// The card was waited for `us` for a submission; `what` names it if it is
  192. /// the longest since the last line.
  193. pub(crate) fn card_waited(us: u64, what: impl FnOnce() -> String) {
  194. let (n, t) = match us {
  195. 0..2_000 => (C::CardUnder2, C::CardUnder2Us),
  196. 2_000..8_000 => (C::Card2To8, C::Card2To8Us),
  197. 8_000..32_000 => (C::Card8To32, C::Card8To32Us),
  198. _ => (C::CardOver32, C::CardOver32Us),
  199. };
  200. add(n, 1);
  201. add(t, us);
  202. // Every submission is named (some forty a frame): the same lists run
  203. // every frame, and the eight longest waits of a line were one list
  204. // eight times.
  205. let text = what();
  206. {
  207. let mut by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner());
  208. let e = by.get_or_insert_with(HashMap::new).entry(text.clone()).or_insert((0, 0));
  209. e.0 += 1;
  210. e.1 += us;
  211. }
  212. let mut longest = LONGEST.lock().unwrap_or_else(|e| e.into_inner());
  213. if us > longest.0 {
  214. *longest = (us, text);
  215. }
  216. }
  217. /// Whether an experiment on barriers is on (`VICTORY_BARRIER_TEST`): bit 0
  218. /// for `groups` (the title's barrier groups record no wait for earlier
  219. /// shader writes), bit 1 for `indirect` (the pass that bounds an indirect
  220. /// command runs without its two such waits; its state changes stay), both
  221. /// bits for `both`. For timing only: without the waits a shader may read
  222. /// what another has not finished writing.
  223. pub(crate) fn barrier_test() -> u8 {
  224. static TEST: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  225. *TEST.get_or_init(|| match std::env::var("VICTORY_BARRIER_TEST").as_deref() {
  226. Ok("groups") => 1,
  227. Ok("indirect") => 2,
  228. Ok("both") => 3,
  229. _ => 0,
  230. })
  231. }
  232. /// Per range compared after a submission (start, length): times, and the
  233. /// bytes of it written back to the title.
  234. static COMPARED: Mutex<Option<HashMap<(usize, usize), (u64, u64)>>> = Mutex::new(None);
  235. /// `len` bytes at `src` were compared after a submission and `written` of
  236. /// them put back into title memory.
  237. pub(crate) fn compared(src: usize, len: usize, written: usize) {
  238. let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner());
  239. let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0));
  240. e.0 += 1;
  241. e.1 += written as u64;
  242. }
  243. /// A copy of `len` bytes from `src` (memory type `kind`) took `us`.
  244. pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) {
  245. let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner());
  246. let e = map
  247. .get_or_insert_with(HashMap::new)
  248. .entry((src, len))
  249. .or_insert((0, 0, 0, kind));
  250. e.0 += 1;
  251. e.1 += len as u64;
  252. e.2 += us;
  253. }
  254. /// Our own allocations alive now, by size of block (under 4 KiB, to 64 KiB,
  255. /// to 1 MiB, larger): bytes, then blocks. "Our own" is the Rust code of
  256. /// every crate in the process: in diagnostics builds [`Counting`] stands in
  257. /// front of the system's heap. The memory map's "process heap segments"
  258. /// hold the blocks under about half a megabyte of ours, of the graphics
  259. /// runtime and of the driver alike (3.5 GB in run 60's gameplay, growing by
  260. /// some 2 MB a frame, and nothing said whose): this says which part is
  261. /// ours. Bigger blocks are allocations of their own in the map.
  262. static OWN: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8];
  263. /// The class of [`OWN`] a block of `size` bytes counts in.
  264. fn block_class(size: usize) -> usize {
  265. match size {
  266. 0..0x1000 => 0,
  267. 0x1000..0x1_0000 => 1,
  268. 0x1_0000..0x10_0000 => 2,
  269. _ => 3,
  270. }
  271. }
  272. fn own(size: usize, made: bool) {
  273. let class = block_class(size);
  274. if made {
  275. OWN[class].fetch_add(size as u64, Relaxed);
  276. OWN[4 + class].fetch_add(1, Relaxed);
  277. } else {
  278. OWN[class].fetch_sub(size as u64, Relaxed);
  279. OWN[4 + class].fetch_sub(1, Relaxed);
  280. }
  281. }
  282. /// Our own blocks of [`BIG`] bytes and more alive now: where each is (0:
  283. /// none) and its bytes. The memory map lists the process's big allocations
  284. /// by size without saying whose they are (run 65: one of 544 MB, one of
  285. /// 401 MB, two of 174 MB, two of 115 MB); the sizes here say which of them
  286. /// are ours.
  287. static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = [const { std::sync::atomic::AtomicUsize::new(0) }; 64];
  288. static BIG_BYTES: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64];
  289. const BIG: usize = 32 << 20;
  290. /// A block of [`BIG`] bytes or more was made at `at`, or released there.
  291. fn big(at: *mut u8, size: usize, made: bool) {
  292. if size < BIG {
  293. return;
  294. }
  295. for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) {
  296. if made {
  297. if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() {
  298. bytes.store(size as u64, Relaxed);
  299. return;
  300. }
  301. } else if place.load(Relaxed) == at as usize {
  302. bytes.store(0, Relaxed);
  303. place.store(0, Relaxed);
  304. return;
  305. }
  306. }
  307. }
  308. /// The sizes of our own big blocks alive, largest first, in MB.
  309. fn big_blocks() -> String {
  310. let mut sizes: Vec<u64> = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect();
  311. sizes.sort_unstable_by(|a, b| b.cmp(a));
  312. let text: Vec<String> = sizes.iter().map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)).collect();
  313. if text.is_empty() { "none".into() } else { text.join(", ") }
  314. }
  315. /// The system's allocator with every block counted in [`OWN`] (two atomic
  316. /// additions per allocation and per release: diagnostics builds only).
  317. struct Counting;
  318. // SAFETY: every call goes to the system's allocator unchanged; only
  319. // counters are kept beside it.
  320. unsafe impl std::alloc::GlobalAlloc for Counting {
  321. unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 {
  322. // SAFETY: the caller's contract, passed on.
  323. let at = unsafe { std::alloc::System.alloc(layout) };
  324. if !at.is_null() {
  325. own(layout.size(), true);
  326. big(at, layout.size(), true);
  327. }
  328. at
  329. }
  330. unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 {
  331. // SAFETY: the caller's contract, passed on.
  332. let at = unsafe { std::alloc::System.alloc_zeroed(layout) };
  333. if !at.is_null() {
  334. own(layout.size(), true);
  335. big(at, layout.size(), true);
  336. }
  337. at
  338. }
  339. unsafe fn dealloc(&self, at: *mut u8, layout: std::alloc::Layout) {
  340. own(layout.size(), false);
  341. big(at, layout.size(), false);
  342. // SAFETY: the caller's contract, passed on.
  343. unsafe { std::alloc::System.dealloc(at, layout) };
  344. }
  345. unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 {
  346. // SAFETY: the caller's contract, passed on.
  347. let moved = unsafe { std::alloc::System.realloc(at, layout, size) };
  348. if !moved.is_null() {
  349. own(layout.size(), false);
  350. own(size, true);
  351. big(at, layout.size(), false);
  352. big(moved, size, true);
  353. }
  354. moved
  355. }
  356. }
  357. #[global_allocator]
  358. static HEAP: Counting = Counting;
  359. #[cfg(test)]
  360. mod command_tests {
  361. /// Commands are summed by pipeline and first word; those without a
  362. /// pipeline by their first two words.
  363. #[test]
  364. fn commands_are_named_by_their_pipeline() {
  365. use super::command_key;
  366. assert_eq!(
  367. command_key("dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]"),
  368. "dispatch [compute 24f989b98dcb03f0]"
  369. );
  370. assert_eq!(
  371. command_key("indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t"),
  372. "indirect [mesh 0750cb2d975c7563, pixel 085d374c5a795549]"
  373. );
  374. assert_eq!(command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), "texture upload");
  375. assert_eq!(command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), "alias copy");
  376. }
  377. }
  378. #[cfg(test)]
  379. mod own_tests {
  380. use super::{OWN, block_class};
  381. use std::sync::atomic::Ordering::Relaxed;
  382. #[test]
  383. fn blocks_count_in_their_size_class() {
  384. assert_eq!(block_class(0), 0);
  385. assert_eq!(block_class(4095), 0);
  386. assert_eq!(block_class(4096), 1);
  387. assert_eq!(block_class(65535), 1);
  388. assert_eq!(block_class(65536), 2);
  389. assert_eq!(block_class((1 << 20) - 1), 2);
  390. assert_eq!(block_class(1 << 20), 3);
  391. }
  392. /// A block of 32 MiB or more is listed by its size while it lives.
  393. #[test]
  394. fn big_blocks_are_listed_while_they_live() {
  395. let size = (48usize << 20) + 4096;
  396. let listed = |at: usize| {
  397. super::BIG_AT
  398. .iter()
  399. .zip(&super::BIG_BYTES)
  400. .any(|(place, bytes)| place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64)
  401. };
  402. let block = vec![0u8; size];
  403. let at = block.as_ptr() as usize;
  404. assert!(listed(at));
  405. assert!(super::big_blocks().contains("48.00"));
  406. drop(block);
  407. assert!(!listed(at));
  408. }
  409. /// A big block shows in the counters while it lives (other tests
  410. /// allocate small blocks meanwhile: only the big class is looked at,
  411. /// and only for at least this block).
  412. #[test]
  413. fn a_block_is_counted_while_it_lives() {
  414. let block = vec![1u8; 8 << 20];
  415. assert!(OWN[3].load(Relaxed) >= 8 << 20);
  416. assert!(OWN[7].load(Relaxed) >= 1);
  417. drop(block);
  418. assert!(OWN[7].load(Relaxed) < u64::MAX / 2, "no count below zero");
  419. }
  420. }
  421. /// The process's memory in bytes: in physical memory, and committed
  422. /// (private bytes).
  423. fn process_memory() -> (u64, u64) {
  424. use windows_sys::Win32::System::ProcessStatus::{
  425. K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
  426. };
  427. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  428. let mut c = PROCESS_MEMORY_COUNTERS {
  429. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  430. ..Default::default()
  431. };
  432. // SAFETY: our own process and a sized structure.
  433. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  434. (c.WorkingSetSize as u64, c.PagefileUsage as u64)
  435. }
  436. /// The PC's memory in bytes: physical memory free, and what is left to
  437. /// commit.
  438. fn system_memory() -> (u64, u64) {
  439. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  440. // SAFETY: plain data the call fills in.
  441. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  442. m.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
  443. // SAFETY: a sized structure.
  444. unsafe { GlobalMemoryStatusEx(&mut m) };
  445. (m.ullAvailPhys, m.ullAvailPageFile)
  446. }
  447. /// Whether the address space is walked for the memory map line
  448. /// ([`log_memory_map`]). On by default (this module is in diagnostics
  449. /// builds only); `VICTORY_MEMORY_MAP=0` leaves the walk out.
  450. fn memory_map() -> bool {
  451. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  452. *ON.get_or_init(|| std::env::var_os("VICTORY_MEMORY_MAP").is_none_or(|v| v != "0"))
  453. }
  454. /// Asks which of the pages in `asked` (address, answer) are in physical
  455. /// memory and adds the bytes each stands for (kind, bytes) to its kind.
  456. fn in_memory(asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, u64)>, present: &mut [u64; 10]) {
  457. use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx;
  458. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  459. // SAFETY: our own process; `asked` holds that many entries of two
  460. // words each, as the call fills them in.
  461. let ok = unsafe {
  462. K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32)
  463. } != 0;
  464. if ok {
  465. for (a, &(kind, bytes)) in asked.iter().zip(stands.iter()) {
  466. // Bit 0 of the answer: the page is in the process's memory.
  467. if a[1] & 1 != 0 {
  468. present[kind] += bytes;
  469. }
  470. }
  471. }
  472. asked.clear();
  473. stands.clear();
  474. }
  475. /// Logs what the process has committed by kind, from a walk of its address
  476. /// space, and how much of each kind is in physical memory (one page in
  477. /// sixteen is asked about). The kinds tell the title's own memory from
  478. /// ours: the title's heaps and page views lie at console addresses (below
  479. /// 1 TiB), everything the host allocates lies far above. Run 30, seen
  480. /// from outside at 18.0 GB private: 4.6 GB the title's heaps, 2.6 GB in
  481. /// 162 segments of the process heap, 2.7 GB in 707 allocations of 4 MiB
  482. /// (windows of title memory), 0.46 GB the pipeline library's file; mapped
  483. /// and so not private: 6.2 GB the title's page pool, 2.0 GB the driver's
  484. /// shader cache file.
  485. /// shortcut: the walk takes about 0.6 s on a thread of its own, and a
  486. /// query of a region of gigabytes holds up other threads' memory calls
  487. /// for its length (89 ms for the 6.2 GB pool), so it runs with every
  488. /// sixth memory line only.
  489. fn log_memory_map() {
  490. use windows_sys::Win32::System::Memory::{
  491. MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE,
  492. VirtualQuery,
  493. };
  494. const KINDS: [&str; 10] = [
  495. "the title's heaps (private, console addresses)",
  496. "views of the title's pages (mapped, console addresses)",
  497. "the title's page pool (mapped, 1 GB and more)",
  498. "process heap segments (private, 15.8 MB each)",
  499. "windows of title memory and other 4 MiB allocations",
  500. "write-combined (buffers shared with the card)",
  501. "other private allocations of 1 MB and more",
  502. "other private allocations under 1 MB",
  503. "files and other mappings at host addresses",
  504. "programs and libraries",
  505. ];
  506. /// Console addresses lie below this.
  507. const HOST: usize = 1 << 40;
  508. /// One page asked about stands for this much.
  509. const STEP: usize = 64 << 10;
  510. let started = std::time::Instant::now();
  511. // Allocation, start, bytes, committed, type, protection.
  512. type Region = (usize, usize, usize, bool, u32, u32);
  513. let mut regions: Vec<Region> = Vec::new();
  514. let mut at = 0usize;
  515. loop {
  516. // SAFETY: plain data filled in by the query.
  517. let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  518. // SAFETY: a valid out pointer of the right size.
  519. if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 {
  520. break;
  521. }
  522. if m.State != MEM_FREE {
  523. regions.push((
  524. m.AllocationBase as usize,
  525. m.BaseAddress as usize,
  526. m.RegionSize,
  527. m.State == MEM_COMMIT,
  528. m.Type,
  529. m.Protect,
  530. ));
  531. }
  532. let next = (m.BaseAddress as usize).saturating_add(m.RegionSize);
  533. if next <= at {
  534. break;
  535. }
  536. at = next;
  537. }
  538. // Each allocation's whole size, reserved parts included.
  539. let mut whole: HashMap<usize, usize> = HashMap::new();
  540. for r in &regions {
  541. *whole.entry(r.0).or_default() += r.2;
  542. }
  543. let kind = |r: &Region| -> usize {
  544. let size = whole.get(&r.0).copied().unwrap_or(0);
  545. let console = r.0 < HOST;
  546. if r.4 == MEM_IMAGE {
  547. 9
  548. } else if r.4 == MEM_MAPPED {
  549. match (console, size >= 1 << 30) {
  550. (false, _) => 8,
  551. (true, true) => 2,
  552. (true, false) => 1,
  553. }
  554. } else if console {
  555. 0
  556. } else if size == 0xfd_0000 {
  557. 3
  558. } else if size == 4 << 20 {
  559. 4
  560. } else if r.5 & PAGE_WRITECOMBINE != 0 {
  561. 5
  562. } else if size >= 1 << 20 {
  563. 6
  564. } else {
  565. 7
  566. }
  567. };
  568. let mut committed = [0u64; 10];
  569. let mut present = [0u64; 10];
  570. let mut asked: Vec<[usize; 2]> = Vec::with_capacity(4096);
  571. let mut stands: Vec<(usize, u64)> = Vec::with_capacity(4096);
  572. for r in regions.iter().filter(|r| r.3) {
  573. let k = kind(r);
  574. committed[k] += r.2 as u64;
  575. let mut offset = 0;
  576. while offset < r.2 {
  577. asked.push([r.1 + offset, 0]);
  578. stands.push((k, STEP.min(r.2 - offset) as u64));
  579. if asked.len() == 4096 {
  580. in_memory(&mut asked, &mut stands, &mut present);
  581. }
  582. offset += STEP;
  583. }
  584. }
  585. if !asked.is_empty() {
  586. in_memory(&mut asked, &mut stands, &mut present);
  587. }
  588. let text: Vec<String> = (0..KINDS.len())
  589. .filter(|&k| committed[k] > 0)
  590. .map(|k| format!("{} {} MB ({} MB in memory)", KINDS[k], committed[k] >> 20, present[k] >> 20))
  591. .collect();
  592. tracing::info!(
  593. "memory map ({} regions, {} ms): {}",
  594. regions.len(),
  595. started.elapsed().as_millis(),
  596. text.join("; ")
  597. );
  598. // The private allocations the kinds above leave as "other" (and the
  599. // write-combined ones), grouped by their size: the sizes name their
  600. // owners (the pipeline library's file to the byte, a snapshot buffer
  601. // of a title heap's size, the driver's blocks). Committed bytes by
  602. // allocation first, then allocations by (kind, whole size).
  603. let mut by_allocation: HashMap<usize, (usize, u64)> = HashMap::new();
  604. for r in regions.iter().filter(|r| r.3) {
  605. let k = kind(r);
  606. if k == 5 || k == 6 {
  607. by_allocation.entry(r.0).or_insert((k, 0)).1 += r.2 as u64;
  608. }
  609. }
  610. let mut groups: HashMap<(usize, usize), (u64, u64)> = HashMap::new();
  611. for (base, &(k, bytes)) in &by_allocation {
  612. let group = groups.entry((k, whole.get(base).copied().unwrap_or(0))).or_default();
  613. group.0 += 1;
  614. group.1 += bytes;
  615. }
  616. let mut groups: Vec<((usize, usize), (u64, u64))> = groups.into_iter().collect();
  617. groups.sort_by_key(|g| std::cmp::Reverse(g.1.1));
  618. let biggest: Vec<String> = groups
  619. .iter()
  620. .take(20)
  621. .map(|&((k, size), (n, bytes))| {
  622. format!(
  623. "{n} of {:.2} MB{}: {} MB",
  624. size as f64 / (1 << 20) as f64,
  625. if k == 5 { " write-combined" } else { "" },
  626. bytes >> 20
  627. )
  628. })
  629. .collect();
  630. tracing::info!(
  631. "memory map, other private allocations by size, the {} biggest groups of {} (committed): {}",
  632. biggest.len(),
  633. groups.len(),
  634. biggest.join("; ")
  635. );
  636. }
  637. /// Logs where the memory is: the process and the PC, then what this crate
  638. /// holds by kind (alive now), then the host buffers made since the start.
  639. fn log_memory() {
  640. use std::sync::atomic::Ordering::Relaxed;
  641. let mb = |v: u64| v as f64 / (1 << 20) as f64;
  642. let (working, private) = process_memory();
  643. let (free, left) = system_memory();
  644. let copies = crate::shadow::memory();
  645. let staged = crate::texture::memory();
  646. let textures = [0, 1].map(|i| crate::resource::HOST_TEXTURES[i].load(Relaxed));
  647. let made: Vec<u64> = crate::host::MADE.iter().map(|m| m.load(Relaxed)).collect();
  648. let windows = crate::shadow::windows();
  649. let stagings = crate::texture::let_go();
  650. let census = crate::resource::census();
  651. let kinds: Vec<u64> = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect();
  652. let card = crate::host::host()
  653. .and_then(|h| h.video_memory())
  654. .unwrap_or_default();
  655. // Everything the system says of the two memory groups, beside the
  656. // budget and use the lines below print.
  657. if let Some(h) = crate::host::host() {
  658. h.log_video_memory("with the memory line");
  659. }
  660. // What else holds memory: the map, on a thread of its own, with every
  661. // sixth line; and what the shader table and the pipeline library keep.
  662. static LINES: AtomicU64 = AtomicU64::new(0);
  663. static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  664. if memory_map() && LINES.fetch_add(1, Relaxed) % 6 == 5 && !WALKING.swap(true, Relaxed) {
  665. let walk = std::thread::Builder::new().name("victory-memory-map".into()).spawn(|| {
  666. log_memory_map();
  667. WALKING.store(false, Relaxed);
  668. });
  669. if walk.is_err() {
  670. WALKING.store(false, Relaxed);
  671. }
  672. }
  673. let kept = crate::pipeline::kept();
  674. tracing::info!(
  675. "memory kept beside the lines below: {} shader containers {:.0} MB, {} translations \
  676. {:.0} MB; the pipeline library's file {:.0} MB (its last save wrote {:.0} MB)",
  677. kept[0],
  678. mb(kept[1]),
  679. kept[2],
  680. mb(kept[3]),
  681. mb(kept[4]),
  682. mb(kept[5]),
  683. );
  684. tracing::info!(
  685. "memory of textures: {} title textures have no host copy yet ({:.0} MB of title memory); \
  686. host copies the host renders to or writes: {} alive {:.0} MB; host copies the title \
  687. fills: {} alive {:.0} MB ({} of them placed), {} let go {:.0} MB and {} made again \
  688. {:.0} MB since the start; {} host copies made in all; passes that made none for lack of \
  689. room: {}; the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \
  690. shared with it in use",
  691. census[2],
  692. mb(census[3]),
  693. census[0],
  694. mb(census[1]),
  695. census[4],
  696. mb(census[5]),
  697. census[6],
  698. kinds[2],
  699. mb(kinds[3]),
  700. kinds[4],
  701. mb(kinds[5]),
  702. kinds[6],
  703. crate::draw::HEAP_TEXTURES_FULL.load(Relaxed),
  704. mb(card[1]),
  705. mb(card[0]),
  706. mb(card[3]),
  707. );
  708. {
  709. let [textures, staging] = crate::pool::memory();
  710. tracing::info!("memory in blocks (VICTORY_TEXTURE_POOL=0 turns them off): {textures} MB of textures, {staging} MB of their staging buffers");
  711. }
  712. let targets = crate::resource::targets_census();
  713. tracing::info!(
  714. "host copies the sweep never lets go: {} the host renders to or writes {:.0} MB ({} of them placed {:.0} MB); of them {} have title memory that is not mapped now {:.0} MB, {} were not used for 30 s and are held by no list and no slot {:.0} MB, {} are both {:.0} MB; and {} copies of textures the title fills that the host copied into {:.0} MB",
  715. targets[0],
  716. mb(targets[1]),
  717. targets[10],
  718. mb(targets[11]),
  719. targets[2],
  720. mb(targets[3]),
  721. targets[4],
  722. mb(targets[5]),
  723. targets[6],
  724. mb(targets[7]),
  725. targets[8],
  726. mb(targets[9]),
  727. );
  728. tracing::info!(
  729. "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \
  730. {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \
  731. asked for in each",
  732. windows[0],
  733. mb(windows[1]),
  734. stagings[0],
  735. mb(stagings[1]),
  736. mb(windows[2]),
  737. );
  738. tracing::info!(
  739. "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \
  740. left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \
  741. outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \
  742. textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \
  743. {} placed in title memory; made so far: {} upload buffers {:.0} MB, {} shared buffers \
  744. {:.0} MB, {} card buffers {:.0} MB",
  745. mb(private),
  746. mb(working),
  747. mb(free),
  748. mb(left),
  749. copies[0],
  750. mb(copies[1]),
  751. copies[2],
  752. mb(copies[3]),
  753. copies[4],
  754. mb(copies[5]),
  755. staged[0],
  756. mb(staged[1]),
  757. staged[2],
  758. textures[0],
  759. mb(textures[1]),
  760. crate::resource::placed_textures(),
  761. made[0],
  762. mb(made[1]),
  763. made[2],
  764. mb(made[3]),
  765. made[4],
  766. mb(made[5]),
  767. );
  768. tracing::info!(
  769. "memory, placed textures: {} of them were asked for again with other filler words in their description (one resource and host copy each since the filler left the key; VICTORY_PLACED_FILLER=1 keeps it)",
  770. crate::resource::placed_filler_twins()
  771. );
  772. // What the line above leaves open: what is alive of the buffers "made
  773. // so far", what the windows hold and what holds them, and what our own
  774. // code has allocated.
  775. let alive: Vec<u64> = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect();
  776. let window = crate::shadow::window_use();
  777. let views = crate::descriptor::views_kept();
  778. let own: Vec<u64> = OWN.iter().map(|o| o.load(Relaxed)).collect();
  779. tracing::info!(
  780. "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})",
  781. alive[0],
  782. alive[1],
  783. mb(alive[2]),
  784. alive[3],
  785. mb(alive[4]),
  786. alive[5],
  787. alive[6],
  788. mb(alive[7]),
  789. window[7] >> 10,
  790. mb(window[0]),
  791. window[1],
  792. mb(window[2]),
  793. window[3],
  794. mb(window[4]),
  795. window[5],
  796. mb(window[6]),
  797. crate::draw::HEAP_VIEWS_ELSEWHERE.load(Relaxed),
  798. views[0],
  799. views[1],
  800. mb(views[2]),
  801. mb(own[..4].iter().sum()),
  802. own[4..].iter().sum::<u64>(),
  803. mb(own[0]),
  804. own[4],
  805. mb(own[1]),
  806. own[5],
  807. mb(own[2]),
  808. own[6],
  809. mb(own[3]),
  810. own[7],
  811. );
  812. // Round 2: what the view table still holds and what goes around it,
  813. // what host lists cost, the card's share that is the layer's own or
  814. // the title's no more, and which big blocks are ours.
  815. let lists: Vec<u64> = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect();
  816. tracing::info!(
  817. "memory, more: views named whole in their records since the start: {} constant buffer \
  818. views, {} views of placed memory; of the view table's entries {} are constant buffer \
  819. views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \
  820. made by the host, {} preludes made for them, private bytes grew {:.0} MB while \
  821. lists were made; twins of depth textures: {:.0} MB; host copies of \
  822. placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \
  823. them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \
  824. let go from memory so far: {:.0} MB; our own blocks of 32 MB and more, in MB: {}",
  825. views[6],
  826. views[7],
  827. views[3],
  828. views[4],
  829. views[5],
  830. lists[0],
  831. lists[1],
  832. lists[2] as i64 as f64 / (1 << 20) as f64,
  833. mb(census[7]),
  834. mb(census[8]),
  835. mb(census[9]),
  836. mb(kept[6]),
  837. big_blocks(),
  838. );
  839. // Round 3: whether windows hold the same memory more than once (they
  840. // can, once they are cut finer than 4 MiB), and how many host lists
  841. // the title made and never used.
  842. tracing::info!(
  843. "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \
  844. memory that is in more than one window, and is copied once for each); host lists never \
  845. reset since they were made: {}",
  846. mb(copies[3]),
  847. mb(crate::shadow::window_cover()),
  848. lists[3],
  849. );
  850. }
  851. /// Microseconds since the first call.
  852. fn now_us() -> u64 {
  853. static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
  854. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  855. }
  856. /// When the last frame was presented and when the last submission returned
  857. /// ([`now_us`]), and whether a list call and a submission followed that
  858. /// present yet.
  859. static PRESENTED_AT: AtomicU64 = AtomicU64::new(0);
  860. static SUBMITTED_AT: AtomicU64 = AtomicU64::new(0);
  861. static RECORDED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
  862. static SUBMITTED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
  863. /// What a thread that submits did between its submissions and in them
  864. /// (microseconds; list calls in nanoseconds).
  865. #[derive(Default, Clone, Copy)]
  866. struct Submitter {
  867. submissions: u64,
  868. /// From a submission's return to the next one's call: wall time, of it
  869. /// the thread running (user, kernel), and inside our list calls.
  870. between: u64,
  871. between_user: u64,
  872. between_kernel: u64,
  873. between_ours: u64,
  874. /// Waiting for the submission lock; running inside submissions.
  875. lock: u64,
  876. inside_user: u64,
  877. inside_kernel: u64,
  878. }
  879. /// By thread: the submitting threads, and list-call time (nanoseconds,
  880. /// calls) of every recording thread.
  881. static SUBMITTERS: Mutex<Vec<(u32, Submitter)>> = Mutex::new(Vec::new());
  882. static RECORDERS: Mutex<Vec<(u32, u64, u64)>> = Mutex::new(Vec::new());
  883. thread_local! {
  884. /// This thread's last submission: when it returned ([`now_us`]) and the
  885. /// thread's processor time then (user, kernel).
  886. static LEFT: std::cell::Cell<Option<(u64, u64, u64)>> = const { std::cell::Cell::new(None) };
  887. /// The thread's processor time when its running submission was called.
  888. static ENTERED: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
  889. /// List-call nanoseconds of this thread since its last submission.
  890. static OURS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
  891. /// List-call time not yet added to `RECORDERS` (nanoseconds, calls).
  892. static UNSENT: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
  893. }
  894. fn thread_id() -> u32 {
  895. // SAFETY: a plain query.
  896. unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }
  897. }
  898. fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 {
  899. (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10
  900. }
  901. /// This thread's processor time so far (user, kernel), in microseconds.
  902. fn thread_times() -> (u64, u64) {
  903. use windows_sys::Win32::Foundation::FILETIME;
  904. use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes};
  905. let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
  906. let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
  907. // SAFETY: our own thread and four valid out pointers.
  908. unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) };
  909. (micros(user), micros(kernel))
  910. }
  911. /// The process's processor time so far (user, kernel), in microseconds.
  912. fn process_times() -> (u64, u64) {
  913. use windows_sys::Win32::Foundation::FILETIME;
  914. use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes};
  915. let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
  916. let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
  917. // SAFETY: our own process and four valid out pointers.
  918. unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) };
  919. (micros(user), micros(kernel))
  920. }
  921. fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter {
  922. let at = match all.iter().position(|s| s.0 == id) {
  923. Some(at) => at,
  924. None => {
  925. all.push((id, Submitter::default()));
  926. all.len() - 1
  927. }
  928. };
  929. &mut all[at].1
  930. }
  931. /// A list call on this thread that began at `started` has returned.
  932. pub(crate) fn recorded(started: std::time::Instant) {
  933. let ns = started.elapsed().as_nanos() as u64;
  934. add(C::RecordCalls, 1);
  935. add(C::RecordNs, ns);
  936. if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) {
  937. let began = now_us().saturating_sub(ns / 1000);
  938. add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed)));
  939. }
  940. OURS.with(|o| o.set(o.get() + ns));
  941. let (unsent, calls) = UNSENT.with(|u| u.get());
  942. let (unsent, calls) = (unsent + ns, calls + 1);
  943. // By thread, a couple of milliseconds at a time.
  944. if unsent < 2_000_000 {
  945. UNSENT.with(|u| u.set((unsent, calls)));
  946. return;
  947. }
  948. UNSENT.with(|u| u.set((0, 0)));
  949. let id = thread_id();
  950. let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner());
  951. match all.iter_mut().find(|r| r.0 == id) {
  952. Some(r) => (r.1, r.2) = (r.1 + unsent, r.2 + calls),
  953. None => all.push((id, unsent, calls)),
  954. }
  955. }
  956. /// A submission is called on this thread (before it waits for the
  957. /// submission lock).
  958. pub(crate) fn submission_begins() {
  959. let now = now_us();
  960. INSIDE.fetch_add(1, Relaxed);
  961. if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) {
  962. add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed)));
  963. }
  964. let (user, kernel) = thread_times();
  965. ENTERED.with(|e| e.set((user, kernel)));
  966. let ours = OURS.with(|o| o.replace(0));
  967. if let Some((left, u, k)) = LEFT.with(|l| l.get()) {
  968. let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner());
  969. let s = submitter(&mut all, thread_id());
  970. s.between += now.saturating_sub(left);
  971. s.between_user += user.saturating_sub(u);
  972. s.between_kernel += kernel.saturating_sub(k);
  973. s.between_ours += ours;
  974. }
  975. }
  976. /// The submission returns; it waited `lock` microseconds for the
  977. /// submission lock.
  978. pub(crate) fn submission_ends(lock: u64) {
  979. let now = now_us();
  980. INSIDE.fetch_sub(1, Relaxed);
  981. SUBMITTED_AT.store(now, Relaxed);
  982. let (user, kernel) = thread_times();
  983. let (u, k) = ENTERED.with(|e| e.get());
  984. LEFT.with(|l| l.set(Some((now, user, kernel))));
  985. OURS.with(|o| o.set(0));
  986. let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner());
  987. let s = submitter(&mut all, thread_id());
  988. s.submissions += 1;
  989. s.lock += lock;
  990. s.inside_user += user.saturating_sub(u);
  991. s.inside_kernel += kernel.saturating_sub(k);
  992. }
  993. /// The submissions being prepared now.
  994. static INSIDE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  995. /// What the frame is at, for the sampling profiler (`VICTORY_PROFILE`): 3
  996. /// in a submission, else 0 after a present until the first list call, 1 until
  997. /// the first submission, 2 behind it.
  998. pub(crate) fn phase() -> u32 {
  999. if INSIDE.load(Relaxed) > 0 {
  1000. 3
  1001. } else if SUBMITTED_SINCE.load(Relaxed) {
  1002. 2
  1003. } else {
  1004. u32::from(RECORDED_SINCE.load(Relaxed))
  1005. }
  1006. }
  1007. /// The title calls its present (before our own copy to the window runs).
  1008. pub(crate) fn present_begins() {
  1009. add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed)));
  1010. }
  1011. /// A frame was presented.
  1012. pub(crate) fn presented() {
  1013. add(C::Frames, 1);
  1014. PRESENTED_AT.store(now_us(), Relaxed);
  1015. RECORDED_SINCE.store(false, Relaxed);
  1016. SUBMITTED_SINCE.store(false, Relaxed);
  1017. }
  1018. fn page_faults() -> u64 {
  1019. use windows_sys::Win32::System::ProcessStatus::{
  1020. K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
  1021. };
  1022. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  1023. let mut c = PROCESS_MEMORY_COUNTERS {
  1024. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  1025. ..Default::default()
  1026. };
  1027. // SAFETY: our own process and a sized structure.
  1028. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  1029. u64::from(c.PageFaultCount)
  1030. }
  1031. /// Logs the counters per frame, and the ranges that took most bytes. The
  1032. /// counters run from line to line, so they are divided by the frames
  1033. /// presented since the last line, not by `frames` (the frames of the last
  1034. /// second or more: a 4 s frame after an unlogged 4 s frame showed two
  1035. /// frames' counts as one's).
  1036. pub(crate) fn log(frames: f64) {
  1037. let counted = COUNT[C::Frames as usize].swap(0, Relaxed);
  1038. let frames = if counted > 0 { counted as f64 } else { frames };
  1039. static FAULTS: AtomicU64 = AtomicU64::new(0);
  1040. let faults = page_faults();
  1041. let faults = faults - FAULTS.swap(faults, Relaxed).min(faults);
  1042. let c: Vec<f64> = COUNT
  1043. .iter()
  1044. .map(|a| a.swap(0, Relaxed) as f64 / frames)
  1045. .collect();
  1046. let mb = |v: f64| v / 1e6;
  1047. let ms = |v: f64| v / 1e3;
  1048. tracing::info!(
  1049. "copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \
  1050. {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \
  1051. {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \
  1052. unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \
  1053. changed, {:.1} MB hashed, {:.1} MB of them changed, {:.1} changes the guard did not see",
  1054. c[C::Submissions as usize],
  1055. c[C::Copies as usize],
  1056. mb(c[C::CopyBytes as usize]),
  1057. c[C::Refreshes as usize],
  1058. mb(c[C::RefreshBytes as usize]),
  1059. c[C::Skipped as usize],
  1060. mb(c[C::SkippedBytes as usize]),
  1061. c[C::Runs as usize],
  1062. ms(c[C::RunUs as usize]),
  1063. c[C::Queries as usize],
  1064. ms(c[C::QueryUs as usize]),
  1065. ms(c[C::MoveUs as usize]),
  1066. mb(c[C::Unmapped as usize]),
  1067. faults as f64 / frames,
  1068. c[C::Watches as usize],
  1069. ms(c[C::WatchUs as usize]),
  1070. mb(c[C::Checked as usize]),
  1071. mb(c[C::Unchanged as usize]),
  1072. c[C::Fallbacks as usize],
  1073. c[C::GuardFaults as usize],
  1074. mb(c[C::TexWatched as usize]),
  1075. mb(c[C::TexHashed as usize]),
  1076. mb(c[C::TexChanged as usize]),
  1077. c[C::TexHot as usize],
  1078. );
  1079. tracing::info!(
  1080. "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \
  1081. threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \
  1082. refused, {:.1} ms searching; notes {:.1} ms; shader-written ranges: {:.0} steps in \
  1083. {:.1} submissions, snapshots {:.1} ms, {:.1} MB compared back; sparse reads {:.1} ms; \
  1084. guards {:.1} ms; {:.1} MB copied whole (memory not watched); {:.1} frame waits \
  1085. sleeping {:.1} ms (all threads); ranges of shaders that cannot store to buffers: \
  1086. {:.0} steps {:.1} MB left out",
  1087. c[C::RecordCalls as usize],
  1088. c[C::RecordNs as usize] / 1e6,
  1089. ms(c[C::PipelineWaitUs as usize]),
  1090. c[C::DynamicAsked as usize],
  1091. c[C::DynamicRefused as usize],
  1092. c[C::DynamicNs as usize] / 1e6,
  1093. c[C::NoteNs as usize] / 1e6,
  1094. c[C::GpuWrites as usize],
  1095. c[C::BackSubmissions as usize],
  1096. ms(c[C::SnapshotUs as usize]),
  1097. mb(c[C::BackCompared as usize]),
  1098. ms(c[C::SparseUs as usize]),
  1099. ms(c[C::GuardUs as usize]),
  1100. mb(c[C::WholeBytes as usize]),
  1101. c[C::PaceWaits as usize],
  1102. ms(c[C::PaceUs as usize]),
  1103. c[C::GpuWritesLeftOut as usize],
  1104. mb(c[C::GpuWritesLeftOutBytes as usize]),
  1105. );
  1106. let [together, written, mapped] =
  1107. [0, 1, 2].map(|n| crate::watch::ALIASES[n].load(std::sync::atomic::Ordering::Relaxed));
  1108. tracing::info!(
  1109. "guards over several views of a page, since the start: {together} blocks guarded with their other views, \
  1110. {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped"
  1111. );
  1112. // Where the wall clock of a frame goes: the phases of a frame, the
  1113. // processor time of the whole process, and what each submitting and
  1114. // recording thread did.
  1115. static CPU: Mutex<(u64, u64)> = Mutex::new((0, 0));
  1116. let (user, kernel) = process_times();
  1117. let (user, kernel) = {
  1118. let mut last = CPU.lock().unwrap_or_else(|e| e.into_inner());
  1119. let spent = (user.saturating_sub(last.0), kernel.saturating_sub(last.1));
  1120. *last = (user, kernel);
  1121. (spent.0 as f64 / 1e3 / frames, spent.1 as f64 / 1e3 / frames)
  1122. };
  1123. tracing::info!(
  1124. "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \
  1125. until the first submission; {:.1} ms from the last submission to the present call; \
  1126. lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \
  1127. all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \
  1128. putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \
  1129. submissions run at the present with their waits not met; waits for memory values: \
  1130. {:.0} looks {:.1} ms; {:.0} host lists made {:.1} ms; {:.0} parts of held submissions \
  1131. ran alone that the next part could have run with",
  1132. ms(c[C::UntilRecordUs as usize]),
  1133. ms(c[C::UntilSubmitUs as usize]),
  1134. ms(c[C::TailUs as usize]),
  1135. c[C::ResetNs as usize] / 1e6,
  1136. ms(c[C::BackScanUs as usize]),
  1137. c[C::BackDiffer as usize],
  1138. ms(c[C::BackSyncUs as usize]),
  1139. c[C::TexUploads as usize],
  1140. c[C::TexSkipped as usize],
  1141. c[C::Forced as usize],
  1142. c[C::WaitChecks as usize],
  1143. c[C::WaitCheckNs as usize] / 1e6,
  1144. c[C::HostLists as usize],
  1145. c[C::HostListNs as usize] / 1e6,
  1146. c[C::PartsTogether as usize],
  1147. );
  1148. // What is copied whole, largest first: memory nobody tells us about.
  1149. let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take();
  1150. let mut whole: Vec<_> = whole.into_iter().flatten().collect();
  1151. whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n));
  1152. tracing::info!(
  1153. " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow",
  1154. ms(c[C::WholeUs as usize]),
  1155. whole.len()
  1156. );
  1157. for ((src, len), (n, us)) in whole.into_iter().take(6) {
  1158. tracing::info!(
  1159. " copied whole from {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame",
  1160. n as f64 / frames,
  1161. (len as u64 * n) as f64 / 1e6 / frames,
  1162. us as f64 / 1e3 / frames
  1163. );
  1164. }
  1165. // The waiting for the card: many short waits or a few long ones, how
  1166. // much of it is for submissions the title gets nothing back from, and
  1167. // the longest one.
  1168. let longest = std::mem::take(&mut *LONGEST.lock().unwrap_or_else(|e| e.into_inner()));
  1169. tracing::info!(
  1170. " waiting for the card per frame: {:.1} submissions under 2 ms ({:.1} ms), {:.1} of 2-8 ms \
  1171. ({:.1} ms), {:.1} of 8-32 ms ({:.1} ms), {:.1} longer ({:.1} ms); {:.1} submissions hand \
  1172. nothing back to the title ({:.1} ms of the waiting); the longest since the last line: \
  1173. {:.1} ms, {}",
  1174. c[C::CardUnder2 as usize],
  1175. ms(c[C::CardUnder2Us as usize]),
  1176. c[C::Card2To8 as usize],
  1177. ms(c[C::Card2To8Us as usize]),
  1178. c[C::Card8To32 as usize],
  1179. ms(c[C::Card8To32Us as usize]),
  1180. c[C::CardOver32 as usize],
  1181. ms(c[C::CardOver32Us as usize]),
  1182. c[C::NothingBack as usize],
  1183. ms(c[C::NothingBackUs as usize]),
  1184. longest.0 as f64 / 1e3,
  1185. longest.1
  1186. );
  1187. let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take();
  1188. let mut by: Vec<_> = by.into_iter().flatten().collect();
  1189. by.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us));
  1190. for (what, (n, us)) in by.into_iter().take(12) {
  1191. tracing::info!(
  1192. " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}",
  1193. us as f64 / 1e3 / frames,
  1194. n as f64 / frames,
  1195. what.chars().take(700).collect::<String>()
  1196. );
  1197. }
  1198. let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take();
  1199. let mut by: Vec<_> = by.into_iter().flatten().collect();
  1200. by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us));
  1201. // All of them together, and by their first word: the forty lines below
  1202. // are the heaviest only (100 of 226 ms waited in run 102), and what the
  1203. // commands do not account for is the layer's own lists (the card
  1204. // copies' passes, preludes) and the waits themselves.
  1205. if !by.is_empty() {
  1206. let mut kinds: Vec<(String, u64, u64)> = Vec::new();
  1207. for (what, (n, us, _)) in &by {
  1208. let word = what.split(' ').next().unwrap_or("").to_owned();
  1209. match kinds.iter_mut().find(|k| k.0 == word) {
  1210. Some(k) => (k.1, k.2) = (k.1 + n, k.2 + us),
  1211. None => kinds.push((word, *n, *us)),
  1212. }
  1213. }
  1214. kinds.sort_by_key(|k| std::cmp::Reverse(k.2));
  1215. let all: u64 = kinds.iter().map(|k| k.2).sum();
  1216. let text: Vec<String> =
  1217. kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect();
  1218. tracing::info!(
  1219. " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}",
  1220. by.len(),
  1221. all as f64 / 1e3 / frames,
  1222. text.join(", ")
  1223. );
  1224. }
  1225. for (what, (n, us, longest)) in by.into_iter().take(40) {
  1226. tracing::info!(
  1227. " the card's time by command (timing run): {:.2} ms a frame in {:.1} commands a frame, the longest {:.2} ms: {what}",
  1228. us as f64 / 1e3 / frames,
  1229. n as f64 / frames,
  1230. longest as f64 / 1e3
  1231. );
  1232. }
  1233. tracing::info!(
  1234. " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \
  1235. for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \
  1236. such waits each); barrier experiment {}",
  1237. c[C::WaitsForGroups as usize],
  1238. c[C::WaitsForBuffers as usize],
  1239. c[C::IndirectBounded as usize],
  1240. barrier_test()
  1241. );
  1242. // What is compared after submissions, largest first, and how much of
  1243. // it shaders had written.
  1244. let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take();
  1245. let mut compared: Vec<_> = compared.into_iter().flatten().collect();
  1246. compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n));
  1247. tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len());
  1248. for ((src, len), (n, written)) in compared.into_iter().take(8) {
  1249. tracing::info!(
  1250. " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back",
  1251. n as f64 / frames,
  1252. (len as u64 * n) as f64 / 1e6 / frames,
  1253. written as f64 / 1e6 / frames
  1254. );
  1255. }
  1256. let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()));
  1257. submitters.sort_by_key(|s| std::cmp::Reverse(s.1.submissions));
  1258. for (id, s) in submitters.into_iter().take(4) {
  1259. let per = |v: u64| v as f64 / 1e3 / frames;
  1260. tracing::info!(
  1261. " thread {id} submitted {:.1}x/frame: between its submissions {:.1} ms (running \
  1262. {:.1} ms user + {:.1} ms kernel; {:.1} ms in list calls), in them running {:.1} ms \
  1263. user + {:.1} ms kernel, {:.1} ms waiting for the submission lock",
  1264. s.submissions as f64 / frames,
  1265. per(s.between),
  1266. per(s.between_user),
  1267. per(s.between_kernel),
  1268. s.between_ours as f64 / 1e6 / frames,
  1269. per(s.inside_user),
  1270. per(s.inside_kernel),
  1271. per(s.lock),
  1272. );
  1273. }
  1274. let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner()));
  1275. recorders.sort_by_key(|r| std::cmp::Reverse(r.1));
  1276. let busiest: Vec<String> = recorders
  1277. .iter()
  1278. .take(6)
  1279. .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames))
  1280. .collect();
  1281. tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", "));
  1282. log_memory();
  1283. let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take();
  1284. let mut ranges: Vec<_> = ranges.into_iter().flatten().collect();
  1285. ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes));
  1286. for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) {
  1287. use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
  1288. // SAFETY: plain data filled in by the query.
  1289. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1290. // SAFETY: a valid out pointer of the right size.
  1291. unsafe { VirtualQuery(src as *const _, &mut info, size_of_val(&info)) };
  1292. let kind = info.Type;
  1293. tracing::info!(
  1294. " copied from {src:#x}+{len:#x} (memory {kind:#x}): {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame",
  1295. n as f64 / frames,
  1296. bytes as f64 / 1e6 / frames,
  1297. us as f64 / 1e3 / frames
  1298. );
  1299. }
  1300. }