copystat.rs 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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. tracing::info!(
  713. "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \
  714. {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \
  715. asked for in each",
  716. windows[0],
  717. mb(windows[1]),
  718. stagings[0],
  719. mb(stagings[1]),
  720. mb(windows[2]),
  721. );
  722. tracing::info!(
  723. "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \
  724. left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \
  725. outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \
  726. textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \
  727. {} placed in title memory; made so far: {} upload buffers {:.0} MB, {} shared buffers \
  728. {:.0} MB, {} card buffers {:.0} MB",
  729. mb(private),
  730. mb(working),
  731. mb(free),
  732. mb(left),
  733. copies[0],
  734. mb(copies[1]),
  735. copies[2],
  736. mb(copies[3]),
  737. copies[4],
  738. mb(copies[5]),
  739. staged[0],
  740. mb(staged[1]),
  741. staged[2],
  742. textures[0],
  743. mb(textures[1]),
  744. crate::resource::placed_textures(),
  745. made[0],
  746. mb(made[1]),
  747. made[2],
  748. mb(made[3]),
  749. made[4],
  750. mb(made[5]),
  751. );
  752. tracing::info!(
  753. "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)",
  754. crate::resource::placed_filler_twins()
  755. );
  756. // What the line above leaves open: what is alive of the buffers "made
  757. // so far", what the windows hold and what holds them, and what our own
  758. // code has allocated.
  759. let alive: Vec<u64> = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect();
  760. let window = crate::shadow::window_use();
  761. let views = crate::descriptor::views_kept();
  762. let own: Vec<u64> = OWN.iter().map(|o| o.load(Relaxed)).collect();
  763. tracing::info!(
  764. "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 {})",
  765. alive[0],
  766. alive[1],
  767. mb(alive[2]),
  768. alive[3],
  769. mb(alive[4]),
  770. alive[5],
  771. alive[6],
  772. mb(alive[7]),
  773. window[7] >> 10,
  774. mb(window[0]),
  775. window[1],
  776. mb(window[2]),
  777. window[3],
  778. mb(window[4]),
  779. window[5],
  780. mb(window[6]),
  781. crate::draw::HEAP_VIEWS_ELSEWHERE.load(Relaxed),
  782. views[0],
  783. views[1],
  784. mb(views[2]),
  785. mb(own[..4].iter().sum()),
  786. own[4..].iter().sum::<u64>(),
  787. mb(own[0]),
  788. own[4],
  789. mb(own[1]),
  790. own[5],
  791. mb(own[2]),
  792. own[6],
  793. mb(own[3]),
  794. own[7],
  795. );
  796. // Round 2: what the view table still holds and what goes around it,
  797. // what host lists cost, the card's share that is the layer's own or
  798. // the title's no more, and which big blocks are ours.
  799. let lists: Vec<u64> = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect();
  800. tracing::info!(
  801. "memory, more: views named whole in their records since the start: {} constant buffer \
  802. views, {} views of placed memory; of the view table's entries {} are constant buffer \
  803. views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \
  804. made by the host, {} preludes made for them, private bytes grew {:.0} MB while \
  805. lists were made; twins of depth textures: {:.0} MB; host copies of \
  806. placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \
  807. them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \
  808. let go from memory so far: {:.0} MB; our own blocks of 32 MB and more, in MB: {}",
  809. views[6],
  810. views[7],
  811. views[3],
  812. views[4],
  813. views[5],
  814. lists[0],
  815. lists[1],
  816. lists[2] as i64 as f64 / (1 << 20) as f64,
  817. mb(census[7]),
  818. mb(census[8]),
  819. mb(census[9]),
  820. mb(kept[6]),
  821. big_blocks(),
  822. );
  823. // Round 3: whether windows hold the same memory more than once (they
  824. // can, once they are cut finer than 4 MiB), and how many host lists
  825. // the title made and never used.
  826. tracing::info!(
  827. "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \
  828. memory that is in more than one window, and is copied once for each); host lists never \
  829. reset since they were made: {}",
  830. mb(copies[3]),
  831. mb(crate::shadow::window_cover()),
  832. lists[3],
  833. );
  834. }
  835. /// Microseconds since the first call.
  836. fn now_us() -> u64 {
  837. static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
  838. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  839. }
  840. /// When the last frame was presented and when the last submission returned
  841. /// ([`now_us`]), and whether a list call and a submission followed that
  842. /// present yet.
  843. static PRESENTED_AT: AtomicU64 = AtomicU64::new(0);
  844. static SUBMITTED_AT: AtomicU64 = AtomicU64::new(0);
  845. static RECORDED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
  846. static SUBMITTED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
  847. /// What a thread that submits did between its submissions and in them
  848. /// (microseconds; list calls in nanoseconds).
  849. #[derive(Default, Clone, Copy)]
  850. struct Submitter {
  851. submissions: u64,
  852. /// From a submission's return to the next one's call: wall time, of it
  853. /// the thread running (user, kernel), and inside our list calls.
  854. between: u64,
  855. between_user: u64,
  856. between_kernel: u64,
  857. between_ours: u64,
  858. /// Waiting for the submission lock; running inside submissions.
  859. lock: u64,
  860. inside_user: u64,
  861. inside_kernel: u64,
  862. }
  863. /// By thread: the submitting threads, and list-call time (nanoseconds,
  864. /// calls) of every recording thread.
  865. static SUBMITTERS: Mutex<Vec<(u32, Submitter)>> = Mutex::new(Vec::new());
  866. static RECORDERS: Mutex<Vec<(u32, u64, u64)>> = Mutex::new(Vec::new());
  867. thread_local! {
  868. /// This thread's last submission: when it returned ([`now_us`]) and the
  869. /// thread's processor time then (user, kernel).
  870. static LEFT: std::cell::Cell<Option<(u64, u64, u64)>> = const { std::cell::Cell::new(None) };
  871. /// The thread's processor time when its running submission was called.
  872. static ENTERED: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
  873. /// List-call nanoseconds of this thread since its last submission.
  874. static OURS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
  875. /// List-call time not yet added to `RECORDERS` (nanoseconds, calls).
  876. static UNSENT: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
  877. }
  878. fn thread_id() -> u32 {
  879. // SAFETY: a plain query.
  880. unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }
  881. }
  882. fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 {
  883. (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10
  884. }
  885. /// This thread's processor time so far (user, kernel), in microseconds.
  886. fn thread_times() -> (u64, u64) {
  887. use windows_sys::Win32::Foundation::FILETIME;
  888. use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes};
  889. let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
  890. let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
  891. // SAFETY: our own thread and four valid out pointers.
  892. unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) };
  893. (micros(user), micros(kernel))
  894. }
  895. /// The process's processor time so far (user, kernel), in microseconds.
  896. fn process_times() -> (u64, u64) {
  897. use windows_sys::Win32::Foundation::FILETIME;
  898. use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes};
  899. let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
  900. let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
  901. // SAFETY: our own process and four valid out pointers.
  902. unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) };
  903. (micros(user), micros(kernel))
  904. }
  905. fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter {
  906. let at = match all.iter().position(|s| s.0 == id) {
  907. Some(at) => at,
  908. None => {
  909. all.push((id, Submitter::default()));
  910. all.len() - 1
  911. }
  912. };
  913. &mut all[at].1
  914. }
  915. /// A list call on this thread that began at `started` has returned.
  916. pub(crate) fn recorded(started: std::time::Instant) {
  917. let ns = started.elapsed().as_nanos() as u64;
  918. add(C::RecordCalls, 1);
  919. add(C::RecordNs, ns);
  920. if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) {
  921. let began = now_us().saturating_sub(ns / 1000);
  922. add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed)));
  923. }
  924. OURS.with(|o| o.set(o.get() + ns));
  925. let (unsent, calls) = UNSENT.with(|u| u.get());
  926. let (unsent, calls) = (unsent + ns, calls + 1);
  927. // By thread, a couple of milliseconds at a time.
  928. if unsent < 2_000_000 {
  929. UNSENT.with(|u| u.set((unsent, calls)));
  930. return;
  931. }
  932. UNSENT.with(|u| u.set((0, 0)));
  933. let id = thread_id();
  934. let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner());
  935. match all.iter_mut().find(|r| r.0 == id) {
  936. Some(r) => (r.1, r.2) = (r.1 + unsent, r.2 + calls),
  937. None => all.push((id, unsent, calls)),
  938. }
  939. }
  940. /// A submission is called on this thread (before it waits for the
  941. /// submission lock).
  942. pub(crate) fn submission_begins() {
  943. let now = now_us();
  944. if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) {
  945. add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed)));
  946. }
  947. let (user, kernel) = thread_times();
  948. ENTERED.with(|e| e.set((user, kernel)));
  949. let ours = OURS.with(|o| o.replace(0));
  950. if let Some((left, u, k)) = LEFT.with(|l| l.get()) {
  951. let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner());
  952. let s = submitter(&mut all, thread_id());
  953. s.between += now.saturating_sub(left);
  954. s.between_user += user.saturating_sub(u);
  955. s.between_kernel += kernel.saturating_sub(k);
  956. s.between_ours += ours;
  957. }
  958. }
  959. /// The submission returns; it waited `lock` microseconds for the
  960. /// submission lock.
  961. pub(crate) fn submission_ends(lock: u64) {
  962. let now = now_us();
  963. SUBMITTED_AT.store(now, Relaxed);
  964. let (user, kernel) = thread_times();
  965. let (u, k) = ENTERED.with(|e| e.get());
  966. LEFT.with(|l| l.set(Some((now, user, kernel))));
  967. OURS.with(|o| o.set(0));
  968. let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner());
  969. let s = submitter(&mut all, thread_id());
  970. s.submissions += 1;
  971. s.lock += lock;
  972. s.inside_user += user.saturating_sub(u);
  973. s.inside_kernel += kernel.saturating_sub(k);
  974. }
  975. /// The title calls its present (before our own copy to the window runs).
  976. pub(crate) fn present_begins() {
  977. add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed)));
  978. }
  979. /// A frame was presented.
  980. pub(crate) fn presented() {
  981. add(C::Frames, 1);
  982. PRESENTED_AT.store(now_us(), Relaxed);
  983. RECORDED_SINCE.store(false, Relaxed);
  984. SUBMITTED_SINCE.store(false, Relaxed);
  985. }
  986. fn page_faults() -> u64 {
  987. use windows_sys::Win32::System::ProcessStatus::{
  988. K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
  989. };
  990. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  991. let mut c = PROCESS_MEMORY_COUNTERS {
  992. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  993. ..Default::default()
  994. };
  995. // SAFETY: our own process and a sized structure.
  996. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  997. u64::from(c.PageFaultCount)
  998. }
  999. /// Logs the counters per frame, and the ranges that took most bytes. The
  1000. /// counters run from line to line, so they are divided by the frames
  1001. /// presented since the last line, not by `frames` (the frames of the last
  1002. /// second or more: a 4 s frame after an unlogged 4 s frame showed two
  1003. /// frames' counts as one's).
  1004. pub(crate) fn log(frames: f64) {
  1005. let counted = COUNT[C::Frames as usize].swap(0, Relaxed);
  1006. let frames = if counted > 0 { counted as f64 } else { frames };
  1007. static FAULTS: AtomicU64 = AtomicU64::new(0);
  1008. let faults = page_faults();
  1009. let faults = faults - FAULTS.swap(faults, Relaxed).min(faults);
  1010. let c: Vec<f64> = COUNT
  1011. .iter()
  1012. .map(|a| a.swap(0, Relaxed) as f64 / frames)
  1013. .collect();
  1014. let mb = |v: f64| v / 1e6;
  1015. let ms = |v: f64| v / 1e3;
  1016. tracing::info!(
  1017. "copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \
  1018. {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \
  1019. {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \
  1020. unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \
  1021. changed, {:.1} MB hashed, {:.1} MB of them changed, {:.1} changes the guard did not see",
  1022. c[C::Submissions as usize],
  1023. c[C::Copies as usize],
  1024. mb(c[C::CopyBytes as usize]),
  1025. c[C::Refreshes as usize],
  1026. mb(c[C::RefreshBytes as usize]),
  1027. c[C::Skipped as usize],
  1028. mb(c[C::SkippedBytes as usize]),
  1029. c[C::Runs as usize],
  1030. ms(c[C::RunUs as usize]),
  1031. c[C::Queries as usize],
  1032. ms(c[C::QueryUs as usize]),
  1033. ms(c[C::MoveUs as usize]),
  1034. mb(c[C::Unmapped as usize]),
  1035. faults as f64 / frames,
  1036. c[C::Watches as usize],
  1037. ms(c[C::WatchUs as usize]),
  1038. mb(c[C::Checked as usize]),
  1039. mb(c[C::Unchanged as usize]),
  1040. c[C::Fallbacks as usize],
  1041. c[C::GuardFaults as usize],
  1042. mb(c[C::TexWatched as usize]),
  1043. mb(c[C::TexHashed as usize]),
  1044. mb(c[C::TexChanged as usize]),
  1045. c[C::TexHot as usize],
  1046. );
  1047. tracing::info!(
  1048. "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \
  1049. threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \
  1050. refused, {:.1} ms searching; notes {:.1} ms; shader-written ranges: {:.0} steps in \
  1051. {:.1} submissions, snapshots {:.1} ms, {:.1} MB compared back; sparse reads {:.1} ms; \
  1052. guards {:.1} ms; {:.1} MB copied whole (memory not watched); {:.1} frame waits \
  1053. sleeping {:.1} ms (all threads); ranges of shaders that cannot store to buffers: \
  1054. {:.0} steps {:.1} MB left out",
  1055. c[C::RecordCalls as usize],
  1056. c[C::RecordNs as usize] / 1e6,
  1057. ms(c[C::PipelineWaitUs as usize]),
  1058. c[C::DynamicAsked as usize],
  1059. c[C::DynamicRefused as usize],
  1060. c[C::DynamicNs as usize] / 1e6,
  1061. c[C::NoteNs as usize] / 1e6,
  1062. c[C::GpuWrites as usize],
  1063. c[C::BackSubmissions as usize],
  1064. ms(c[C::SnapshotUs as usize]),
  1065. mb(c[C::BackCompared as usize]),
  1066. ms(c[C::SparseUs as usize]),
  1067. ms(c[C::GuardUs as usize]),
  1068. mb(c[C::WholeBytes as usize]),
  1069. c[C::PaceWaits as usize],
  1070. ms(c[C::PaceUs as usize]),
  1071. c[C::GpuWritesLeftOut as usize],
  1072. mb(c[C::GpuWritesLeftOutBytes as usize]),
  1073. );
  1074. // Where the wall clock of a frame goes: the phases of a frame, the
  1075. // processor time of the whole process, and what each submitting and
  1076. // recording thread did.
  1077. static CPU: Mutex<(u64, u64)> = Mutex::new((0, 0));
  1078. let (user, kernel) = process_times();
  1079. let (user, kernel) = {
  1080. let mut last = CPU.lock().unwrap_or_else(|e| e.into_inner());
  1081. let spent = (user.saturating_sub(last.0), kernel.saturating_sub(last.1));
  1082. *last = (user, kernel);
  1083. (spent.0 as f64 / 1e3 / frames, spent.1 as f64 / 1e3 / frames)
  1084. };
  1085. tracing::info!(
  1086. "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \
  1087. until the first submission; {:.1} ms from the last submission to the present call; \
  1088. lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \
  1089. all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \
  1090. putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \
  1091. submissions run at the present with their waits not met; waits for memory values: \
  1092. {:.0} looks {:.1} ms; {:.0} host lists made {:.1} ms; {:.0} parts of held submissions \
  1093. ran alone that the next part could have run with",
  1094. ms(c[C::UntilRecordUs as usize]),
  1095. ms(c[C::UntilSubmitUs as usize]),
  1096. ms(c[C::TailUs as usize]),
  1097. c[C::ResetNs as usize] / 1e6,
  1098. ms(c[C::BackScanUs as usize]),
  1099. c[C::BackDiffer as usize],
  1100. ms(c[C::BackSyncUs as usize]),
  1101. c[C::TexUploads as usize],
  1102. c[C::TexSkipped as usize],
  1103. c[C::Forced as usize],
  1104. c[C::WaitChecks as usize],
  1105. c[C::WaitCheckNs as usize] / 1e6,
  1106. c[C::HostLists as usize],
  1107. c[C::HostListNs as usize] / 1e6,
  1108. c[C::PartsTogether as usize],
  1109. );
  1110. // What is copied whole, largest first: memory nobody tells us about.
  1111. let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take();
  1112. let mut whole: Vec<_> = whole.into_iter().flatten().collect();
  1113. whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n));
  1114. tracing::info!(
  1115. " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow",
  1116. ms(c[C::WholeUs as usize]),
  1117. whole.len()
  1118. );
  1119. for ((src, len), (n, us)) in whole.into_iter().take(6) {
  1120. tracing::info!(
  1121. " copied whole from {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame",
  1122. n as f64 / frames,
  1123. (len as u64 * n) as f64 / 1e6 / frames,
  1124. us as f64 / 1e3 / frames
  1125. );
  1126. }
  1127. // The waiting for the card: many short waits or a few long ones, how
  1128. // much of it is for submissions the title gets nothing back from, and
  1129. // the longest one.
  1130. let longest = std::mem::take(&mut *LONGEST.lock().unwrap_or_else(|e| e.into_inner()));
  1131. tracing::info!(
  1132. " waiting for the card per frame: {:.1} submissions under 2 ms ({:.1} ms), {:.1} of 2-8 ms \
  1133. ({:.1} ms), {:.1} of 8-32 ms ({:.1} ms), {:.1} longer ({:.1} ms); {:.1} submissions hand \
  1134. nothing back to the title ({:.1} ms of the waiting); the longest since the last line: \
  1135. {:.1} ms, {}",
  1136. c[C::CardUnder2 as usize],
  1137. ms(c[C::CardUnder2Us as usize]),
  1138. c[C::Card2To8 as usize],
  1139. ms(c[C::Card2To8Us as usize]),
  1140. c[C::Card8To32 as usize],
  1141. ms(c[C::Card8To32Us as usize]),
  1142. c[C::CardOver32 as usize],
  1143. ms(c[C::CardOver32Us as usize]),
  1144. c[C::NothingBack as usize],
  1145. ms(c[C::NothingBackUs as usize]),
  1146. longest.0 as f64 / 1e3,
  1147. longest.1
  1148. );
  1149. let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take();
  1150. let mut by: Vec<_> = by.into_iter().flatten().collect();
  1151. by.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us));
  1152. for (what, (n, us)) in by.into_iter().take(12) {
  1153. tracing::info!(
  1154. " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}",
  1155. us as f64 / 1e3 / frames,
  1156. n as f64 / frames,
  1157. what.chars().take(700).collect::<String>()
  1158. );
  1159. }
  1160. let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take();
  1161. let mut by: Vec<_> = by.into_iter().flatten().collect();
  1162. by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us));
  1163. // All of them together, and by their first word: the forty lines below
  1164. // are the heaviest only (100 of 226 ms waited in run 102), and what the
  1165. // commands do not account for is the layer's own lists (the card
  1166. // copies' passes, preludes) and the waits themselves.
  1167. if !by.is_empty() {
  1168. let mut kinds: Vec<(String, u64, u64)> = Vec::new();
  1169. for (what, (n, us, _)) in &by {
  1170. let word = what.split(' ').next().unwrap_or("").to_owned();
  1171. match kinds.iter_mut().find(|k| k.0 == word) {
  1172. Some(k) => (k.1, k.2) = (k.1 + n, k.2 + us),
  1173. None => kinds.push((word, *n, *us)),
  1174. }
  1175. }
  1176. kinds.sort_by_key(|k| std::cmp::Reverse(k.2));
  1177. let all: u64 = kinds.iter().map(|k| k.2).sum();
  1178. let text: Vec<String> =
  1179. kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect();
  1180. tracing::info!(
  1181. " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}",
  1182. by.len(),
  1183. all as f64 / 1e3 / frames,
  1184. text.join(", ")
  1185. );
  1186. }
  1187. for (what, (n, us, longest)) in by.into_iter().take(40) {
  1188. tracing::info!(
  1189. " the card's time by command (timing run): {:.2} ms a frame in {:.1} commands a frame, the longest {:.2} ms: {what}",
  1190. us as f64 / 1e3 / frames,
  1191. n as f64 / frames,
  1192. longest as f64 / 1e3
  1193. );
  1194. }
  1195. tracing::info!(
  1196. " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \
  1197. for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \
  1198. such waits each); barrier experiment {}",
  1199. c[C::WaitsForGroups as usize],
  1200. c[C::WaitsForBuffers as usize],
  1201. c[C::IndirectBounded as usize],
  1202. barrier_test()
  1203. );
  1204. // What is compared after submissions, largest first, and how much of
  1205. // it shaders had written.
  1206. let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take();
  1207. let mut compared: Vec<_> = compared.into_iter().flatten().collect();
  1208. compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n));
  1209. tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len());
  1210. for ((src, len), (n, written)) in compared.into_iter().take(8) {
  1211. tracing::info!(
  1212. " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back",
  1213. n as f64 / frames,
  1214. (len as u64 * n) as f64 / 1e6 / frames,
  1215. written as f64 / 1e6 / frames
  1216. );
  1217. }
  1218. let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()));
  1219. submitters.sort_by_key(|s| std::cmp::Reverse(s.1.submissions));
  1220. for (id, s) in submitters.into_iter().take(4) {
  1221. let per = |v: u64| v as f64 / 1e3 / frames;
  1222. tracing::info!(
  1223. " thread {id} submitted {:.1}x/frame: between its submissions {:.1} ms (running \
  1224. {:.1} ms user + {:.1} ms kernel; {:.1} ms in list calls), in them running {:.1} ms \
  1225. user + {:.1} ms kernel, {:.1} ms waiting for the submission lock",
  1226. s.submissions as f64 / frames,
  1227. per(s.between),
  1228. per(s.between_user),
  1229. per(s.between_kernel),
  1230. s.between_ours as f64 / 1e6 / frames,
  1231. per(s.inside_user),
  1232. per(s.inside_kernel),
  1233. per(s.lock),
  1234. );
  1235. }
  1236. let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner()));
  1237. recorders.sort_by_key(|r| std::cmp::Reverse(r.1));
  1238. let busiest: Vec<String> = recorders
  1239. .iter()
  1240. .take(6)
  1241. .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames))
  1242. .collect();
  1243. tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", "));
  1244. log_memory();
  1245. let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take();
  1246. let mut ranges: Vec<_> = ranges.into_iter().flatten().collect();
  1247. ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes));
  1248. for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) {
  1249. use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
  1250. // SAFETY: plain data filled in by the query.
  1251. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1252. // SAFETY: a valid out pointer of the right size.
  1253. unsafe { VirtualQuery(src as *const _, &mut info, size_of_val(&info)) };
  1254. let kind = info.Type;
  1255. tracing::info!(
  1256. " copied from {src:#x}+{len:#x} (memory {kind:#x}): {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame",
  1257. n as f64 / frames,
  1258. bytes as f64 / 1e6 / frames,
  1259. us as f64 / 1e3 / frames
  1260. );
  1261. }
  1262. }