copystat.rs 57 KB

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