copystat.rs 58 KB

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