use std::collections::HashMap; use std::sync::Mutex; use std::sync::atomic::{AtomicU64, AtomicU8, Ordering::Relaxed}; pub(crate) enum C { Submissions, Copies, CopyBytes, Refreshes, RefreshBytes, Skipped, SkippedBytes, Runs, RunUs, Queries, QueryUs, MoveUs, Unmapped, Watches, WatchUs, Checked, Unchanged, Fallbacks, GuardFaults, TexWatched, TexHashed, TexChanged, TexHot, Frames, RecordCalls, RecordNs, PipelineWaitUs, DynamicAsked, DynamicRefused, DynamicNs, NoteNs, GpuWrites, SnapshotUs, BackCompared, SparseUs, GuardUs, WholeBytes, BackSubmissions, PaceWaits, PaceUs, UntilRecordUs, UntilSubmitUs, TailUs, ResetNs, BackScanUs, BackDiffer, BackSyncUs, TexUploads, TexSkipped, Forced, GpuWritesLeftOut, GpuWritesLeftOutBytes, WaitChecks, WaitCheckNs, HostLists, HostListNs, PartsTogether, WholeUs, CardUnder2, Card2To8, Card8To32, CardOver32, CardUnder2Us, Card2To8Us, Card8To32Us, CardOver32Us, NothingBack, NothingBackUs, WaitsForGroups, WaitsForBuffers, IndirectBounded, GroupsEndWrites, GroupsBeginWrites, GroupsOther, RootSameHit, RootSameMiss, RootTailAsked, RootTailCovered, CardLateMoved, CardLateMovedBytes, CardLateRefused, TableEntries, TableEntriesSame, BatchArgsWritten, WaitsQuiet, ReadBacksMade, ReadBacksReused, ReadBacksMadeBytes, CbvShared, FreshSameUsed, FreshSameUsedSlots, WaitsLeftOut, UavGlobals, UavOnResources, UavFolded, UavQuiet, } const COUNTERS: usize = 128; #[repr(align(64))] struct Bank([AtomicU64; N]); const BANKS: usize = 32; static COUNT: [Bank; BANKS] = [const { Bank([const { AtomicU64::new(0) }; COUNTERS]) }; BANKS]; #[inline] fn bank() -> usize { static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); thread_local!(static MINE: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }); MINE.try_with(|mine| { if mine.get() == usize::MAX { mine.set(NEXT.fetch_add(1, Relaxed) % BANKS); } mine.get() }) .unwrap_or(0) } pub(crate) fn add(c: C, n: u64) { COUNT[bank()].0[c as usize].fetch_add(n, Relaxed); } pub(crate) fn peek(c: C) -> u64 { let i = c as usize; COUNT.iter().map(|b| b.0[i].load(Relaxed)).sum() } fn taken(i: usize) -> u64 { COUNT.iter().map(|b| b.0[i].swap(0, Relaxed)).sum() } pub(crate) fn mode() -> u8 { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); *MODE.get_or_init(|| match std::env::var("EONACAT_XS_COPY_MODE").as_deref() { Ok("plain") => 1, Ok("none") => 2, _ => 0, }) } type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>; static RANGES: Mutex> = Mutex::new(None); static WHOLE: Mutex>> = Mutex::new(None); pub(crate) fn whole(src: usize, len: usize, us: u64) { add(C::WholeUs, us); let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); e.0 += 1; e.1 += us; } static LONGEST: Mutex<(u64, String)> = Mutex::new((0, String::new())); static WAITS_BY_WORK: Mutex>> = Mutex::new(None); static COMMANDS_BY_WORK: Mutex>> = Mutex::new(None); pub(crate) fn command_took(op: &str, ms: f64) { let us = (ms * 1e3) as u64; let key = command_key(op); let mut sizes = COMMAND_SIZES.lock().unwrap_or_else(|e| e.into_inner()); let e = sizes.get_or_insert_with(HashMap::new).entry(key.clone()).or_default(); let e = e.entry(command_size(op)).or_insert((0, 0)); e.0 += 1; e.1 += us; drop(sizes); let mut by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); let e = by.get_or_insert_with(HashMap::new).entry(key).or_insert((0, 0, 0)); e.0 += 1; e.1 += us; e.2 = e.2.max(us); } static COMMAND_SIZES: Mutex>>> = Mutex::new(None); fn command_size(op: &str) -> String { let head = op.split(" | ").next().unwrap_or(op); let head = head.split('[').next().unwrap_or(head); let head = head.split(" at ").next().unwrap_or(head); head.split(' ').skip(1).filter(|w| !w.is_empty()).collect::>().join(" ") } fn command_key(op: &str) -> String { let head = op.split(" | ").next().unwrap_or(op); let word = head.split(' ').next().unwrap_or(""); match (head.find('['), head.find(']')) { (Some(a), Some(b)) if a < b => format!("{word} {}", &head[a..=b]), _ => head.split(' ').take(2).collect::>().join(" "), } } pub(crate) fn card_waited(us: u64, what: impl FnOnce() -> String) { let (n, t) = match us { 0..2_000 => (C::CardUnder2, C::CardUnder2Us), 2_000..8_000 => (C::Card2To8, C::Card2To8Us), 8_000..32_000 => (C::Card8To32, C::Card8To32Us), _ => (C::CardOver32, C::CardOver32Us), }; add(n, 1); add(t, us); let text = what(); { let mut by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); let e = by.get_or_insert_with(HashMap::new).entry(text.clone()).or_insert((0, 0)); e.0 += 1; e.1 += us; } let mut longest = LONGEST.lock().unwrap_or_else(|e| e.into_inner()); if us > longest.0 { *longest = (us, text); } } static GROUP_BARRIERS: Mutex>> = Mutex::new(None); pub(crate) fn group_barrier(kind: u32, values: [u32; 4]) { let mut seen = GROUP_BARRIERS.lock().unwrap_or_else(|e| e.into_inner()); *seen.get_or_insert_with(HashMap::new).entry((kind, values)).or_default() += 1; } pub(crate) fn barrier_test() -> u8 { barrier_cycle(); BARRIER_TEST.load(Relaxed) } static BARRIER_TEST: AtomicU8 = AtomicU8::new(0); fn barrier_cycle() -> Option { static CYCLE: std::sync::OnceLock> = std::sync::OnceLock::new(); *CYCLE.get_or_init(|| { let mode = match std::env::var("EONACAT_XS_BARRIER_TEST").as_deref() { Ok("groups") => 1, Ok("indirect") => 2, Ok("both") => 3, Ok("cycle") => { let secs = std::env::var("EONACAT_XS_BARRIER_TEST_SECS").ok().and_then(|v| v.parse().ok()); return Some(secs.unwrap_or(90).max(1)); } _ => 0, }; BARRIER_TEST.store(mode, Relaxed); None }) } fn barrier_next() { static START: std::sync::OnceLock = std::sync::OnceLock::new(); let Some(secs) = barrier_cycle() else { return; }; let start = *START.get_or_init(std::time::Instant::now); let mode = (start.elapsed().as_secs() / secs % 4) as u8; if BARRIER_TEST.swap(mode, Relaxed) != mode { tracing::info!("barrier experiment {mode} from here (cycle of {secs} s each)"); } } static COMPARED: Mutex>> = Mutex::new(None); pub(crate) fn compared(src: usize, len: usize, written: usize) { let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner()); let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); e.0 += 1; e.1 += written as u64; } pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner()); let e = map .get_or_insert_with(HashMap::new) .entry((src, len)) .or_insert((0, 0, 0, kind)); e.0 += 1; e.1 += len as u64; e.2 += us; } static OWN: [Bank<8>; BANKS] = [const { Bank([const { AtomicU64::new(0) }; 8]) }; BANKS]; fn owned(i: usize) -> u64 { OWN.iter().fold(0u64, |sum, b| sum.wrapping_add(b.0[i].load(Relaxed))) } fn block_class(size: usize) -> usize { match size { 0..0x1000 => 0, 0x1000..0x1_0000 => 1, 0x1_0000..0x10_0000 => 2, _ => 3, } } fn own(size: usize, made: bool) { let class = block_class(size); let own = &OWN[bank()].0; if made { own[class].fetch_add(size as u64, Relaxed); own[4 + class].fetch_add(1, Relaxed); } else { own[class].fetch_sub(size as u64, Relaxed); own[4 + class].fetch_sub(1, Relaxed); } } static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = [const { std::sync::atomic::AtomicUsize::new(0) }; 64]; static BIG_BYTES: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64]; const BIG: usize = 32 << 20; fn big(at: *mut u8, size: usize, made: bool) { if size < BIG { return; } if made && size >= 64 << 20 { name_big(size); } for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) { if made { if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() { bytes.store(size as u64, Relaxed); return; } } else if place.load(Relaxed) == at as usize { bytes.store(0, Relaxed); place.store(0, Relaxed); return; } } } thread_local! { static NAMING_BIG: std::cell::Cell = const { std::cell::Cell::new(false) }; } fn name_big(size: usize) { if NAMING_BIG.with(|n| n.replace(true)) { return; } static NAMED: AtomicU64 = AtomicU64::new(0); if NAMED.fetch_add(1, Relaxed) < 24 { let trace = std::backtrace::Backtrace::force_capture(); tracing::info!(mb = size >> 20, "a block of ours of 64 MB or more made: {trace}"); } NAMING_BIG.with(|n| n.set(false)); } fn big_blocks() -> String { let mut sizes: Vec = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect(); sizes.sort_unstable_by(|a, b| b.cmp(a)); let text: Vec = sizes.iter().map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)).collect(); if text.is_empty() { "none".into() } else { text.join(", ") } } #[allow(dead_code)] struct Counting; unsafe impl std::alloc::GlobalAlloc for Counting { unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { let at = unsafe { mimalloc::MiMalloc.alloc(layout) }; if !at.is_null() { own(layout.size(), true); big(at, layout.size(), true); } at } unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { let at = unsafe { mimalloc::MiMalloc.alloc_zeroed(layout) }; if !at.is_null() { own(layout.size(), true); big(at, layout.size(), true); } at } unsafe fn dealloc(&self, at: *mut u8, layout: std::alloc::Layout) { own(layout.size(), false); big(at, layout.size(), false); unsafe { mimalloc::MiMalloc.dealloc(at, layout) }; } unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { let moved = unsafe { mimalloc::MiMalloc.realloc(at, layout, size) }; if !moved.is_null() { own(layout.size(), false); own(size, true); big(at, layout.size(), false); big(moved, size, true); } moved } } #[cfg(feature = "diagnostics")] #[global_allocator] static HEAP: Counting = Counting; #[cfg(test)] mod command_tests { #[test] fn commands_are_named_by_their_pipeline() { use super::command_key; assert_eq!( command_key("dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]"), "dispatch [compute 24f989b98dcb03f0]" ); assert_eq!( command_key("indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t"), "indirect [mesh 0750cb2d975c7563, pixel 085d374c5a795549]" ); assert_eq!(command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), "texture upload"); assert_eq!(command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), "alias copy"); } } #[cfg(test)] mod own_tests { use super::{block_class, owned}; use std::sync::atomic::Ordering::Relaxed; #[test] fn blocks_count_in_their_size_class() { assert_eq!(block_class(0), 0); assert_eq!(block_class(4095), 0); assert_eq!(block_class(4096), 1); assert_eq!(block_class(65535), 1); assert_eq!(block_class(65536), 2); assert_eq!(block_class((1 << 20) - 1), 2); assert_eq!(block_class(1 << 20), 3); } #[test] fn big_blocks_are_listed_while_they_live() { let size = (48usize << 20) + 4096; let listed = |at: usize| { super::BIG_AT .iter() .zip(&super::BIG_BYTES) .any(|(place, bytes)| place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64) }; let block = vec![0u8; size]; let at = block.as_ptr() as usize; assert!(listed(at)); assert!(super::big_blocks().contains("48.00")); drop(block); assert!(!listed(at)); } #[test] fn a_block_is_counted_while_it_lives() { let block = std::hint::black_box(vec![1u8; 8 << 20]); assert!(owned(3) >= 8 << 20); assert!(owned(7) >= 1); drop(block); assert!(owned(7) < u64::MAX / 2, "no count below zero"); } } pub(crate) use crate::procmem::process_memory; use crate::procmem::system_memory; fn memory_map() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("EONACAT_XS_MEMORY_MAP").is_none_or(|v| v != "0")) } fn in_memory( asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, usize, u64)>, present: &mut [u64; 10], present_by_base: &mut HashMap, ) { use crate::memcalls::ps::K32QueryWorkingSetEx; use windows_sys::Win32::System::Threading::GetCurrentProcess; let ok = unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) } != 0; if ok { for (a, &(kind, base, bytes)) in asked.iter().zip(stands.iter()) { if a[1] & 1 != 0 { present[kind] += bytes; if kind == 5 || kind == 6 { *present_by_base.entry(base).or_default() += bytes; } } } } asked.clear(); stands.clear(); } fn log_memory_map() { use crate::memcalls::sys::{ MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE, VirtualQuery, }; const KINDS: [&str; 10] = [ "the title's heaps (private, console addresses)", "views of the title's pages (mapped, console addresses)", "the title's page pool (mapped, 1 GB and more)", "process heap segments (private, 15.8 MB each)", "windows of title memory and other 4 MiB allocations", "write-combined (buffers shared with the card)", "other private allocations of 1 MB and more", "other private allocations under 1 MB", "files and other mappings at host addresses", "programs and libraries", ]; const HOST: usize = 1 << 40; const STEP: usize = 64 << 10; let started = std::time::Instant::now(); type Region = (usize, usize, usize, bool, u32, u32); let mut regions: Vec = Vec::new(); let mut at = 0usize; loop { let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 { break; } if m.State != MEM_FREE { regions.push(( m.AllocationBase as usize, m.BaseAddress as usize, m.RegionSize, m.State == MEM_COMMIT, m.Type, m.Protect, )); } let next = (m.BaseAddress as usize).saturating_add(m.RegionSize); if next <= at { break; } at = next; } let mut whole: HashMap = HashMap::new(); for r in ®ions { *whole.entry(r.0).or_default() += r.2; } let kind = |r: &Region| -> usize { let size = whole.get(&r.0).copied().unwrap_or(0); let console = r.0 < HOST; if r.4 == MEM_IMAGE { 9 } else if r.4 == MEM_MAPPED { match (console, size >= 1 << 30) { (false, _) => 8, (true, true) => 2, (true, false) => 1, } } else if console { 0 } else if size == 0xfd_0000 { 3 } else if size == 4 << 20 { 4 } else if r.5 & PAGE_WRITECOMBINE != 0 { 5 } else if size >= 1 << 20 { 6 } else { 7 } }; let mut committed = [0u64; 10]; let mut present = [0u64; 10]; let mut asked: Vec<[usize; 2]> = Vec::with_capacity(4096); let mut stands: Vec<(usize, usize, u64)> = Vec::with_capacity(4096); let mut present_by_base: HashMap = HashMap::new(); for r in regions.iter().filter(|r| r.3) { let k = kind(r); committed[k] += r.2 as u64; let mut offset = 0; while offset < r.2 { asked.push([r.1 + offset, 0]); stands.push((k, r.0, STEP.min(r.2 - offset) as u64)); if asked.len() == 4096 { in_memory(&mut asked, &mut stands, &mut present, &mut present_by_base); } offset += STEP; } } if !asked.is_empty() { in_memory(&mut asked, &mut stands, &mut present, &mut present_by_base); } let text: Vec = (0..KINDS.len()) .filter(|&k| committed[k] > 0) .map(|k| format!("{} {} MB ({} MB in memory)", KINDS[k], committed[k] >> 20, present[k] >> 20)) .collect(); tracing::info!( "memory map ({} regions, {} ms): {}", regions.len(), started.elapsed().as_millis(), text.join("; ") ); let mut by_allocation: HashMap = HashMap::new(); for r in regions.iter().filter(|r| r.3) { let k = kind(r); if k == 5 || k == 6 { by_allocation.entry(r.0).or_insert((k, 0)).1 += r.2 as u64; } } let (total, biggest) = format_biggest_groups(&by_allocation, &whole, &present_by_base, 20); tracing::info!( "memory map, other private allocations by size, the {} biggest groups of {total} \ (committed, in memory): {}", biggest.len(), biggest.join("; ") ); log_console_private(®ions, &whole); } #[derive(Default)] struct Group { count: u64, committed: u64, present: u64, } fn format_biggest_groups( by_allocation: &HashMap, whole: &HashMap, present_by_base: &HashMap, limit: usize, ) -> (usize, Vec) { let mut groups: HashMap<(usize, usize), Group> = HashMap::new(); for (base, &(k, bytes)) in by_allocation { let group = groups.entry((k, whole.get(base).copied().unwrap_or(0))).or_default(); group.count += 1; group.committed += bytes; group.present += present_by_base.get(base).copied().unwrap_or(0); } let mut groups: Vec<((usize, usize), Group)> = groups.into_iter().collect(); groups.sort_by_key(|entry| (std::cmp::Reverse(entry.1.committed), entry.0.0, entry.0.1)); let total = groups.len(); let biggest: Vec = groups .iter() .take(limit) .map(|entry| { let (k, size) = entry.0; let group = &entry.1; let n = group.count; let mb = group.committed >> 20; let present = group.present >> 20; let wc = if k == 5 { " write-combined" } else { "" }; format!( "{n} of {:.2} MB{wc}: {mb} MB ({present} MB in memory)", size as f64 / (1 << 20) as f64 ) }) .collect(); (total, biggest) } fn log_console_private(regions: &[(usize, usize, usize, bool, u32, u32)], whole: &HashMap) { use crate::memcalls::sys::{GetWriteWatch, MEM_PRIVATE}; const HOST: usize = 1 << 40; let mb = |v: u64| v >> 20; let mut allocations: HashMap = HashMap::new(); for r in regions.iter().filter(|r| r.3 && r.0 < HOST && r.4 == MEM_PRIVATE) { allocations.entry(r.0).or_insert((0, r.5, r.1)).0 += r.2 as u64; } let watched = |at: usize| { let mut address = std::ptr::null_mut(); let mut count = 1usize; let mut granularity = 0u32; unsafe { GetWriteWatch(0, at as *const _, 4096, &mut address, &mut count, &mut granularity) == 0 } }; let (mut ours, mut ours_bytes) = (0u64, 0u64); let mut others: HashMap = HashMap::new(); for (&base, &(bytes, protect, first)) in &allocations { if watched(first) { ours += 1; ours_bytes += bytes; } else { others.insert(base, (bytes, protect, whole.get(&base).copied().unwrap_or(0))); } } let group = |list: &mut dyn Iterator, most: usize| -> (usize, usize, String) { let mut groups: HashMap<(usize, u32), (u64, u64)> = HashMap::new(); for (size, protect, bytes) in list { let g = groups.entry((size, protect)).or_default(); g.0 += 1; g.1 += bytes; } let n = groups.len(); let mut groups: Vec<_> = groups.into_iter().collect(); groups.sort_by_key(|g| std::cmp::Reverse(g.1.1)); let text: Vec = groups .iter() .take(most) .map(|&((size, protect), (n, bytes))| { format!("{n} of {:.2} MB protection {protect:#x}: {} MB", size as f64 / (1 << 20) as f64, mb(bytes)) }) .collect(); (n, text.len(), text.join("; ")) }; let others_bytes: u64 = others.values().map(|o| o.0).sum(); let (kinds, shown, by_size) = group(&mut others.values().map(|&(bytes, protect, size)| (size, protect, bytes)), 12); let mut biggest: Vec<(&usize, &(u64, u32, usize))> = others.iter().collect(); biggest.sort_by_key(|(_, o)| std::cmp::Reverse(o.0)); let biggest: Vec = biggest .iter() .take(8) .map(|&(base, &(bytes, protect, size))| { format!("{:#x}: {} of {} MB, protection {protect:#x}", *base, mb(bytes), mb(size as u64)) }) .collect(); tracing::info!( "memory map, the title's heaps by maker: write-watched (the title's allocations, our arenas) {ours} \ allocations, {} MB; others {} allocations, {} MB, by size and protection, the {shown} biggest groups of \ {kinds}: {by_size}; the biggest: {}", mb(ours_bytes), others.len(), mb(others_bytes), biggest.join("; ") ); static BEFORE: Mutex>> = Mutex::new(None); let mut before = BEFORE.lock().unwrap_or_else(|e| e.into_inner()); if let Some(was) = before.as_ref() { let came: Vec<(usize, u32, u64)> = others .iter() .filter(|(base, _)| !was.contains_key(base)) .map(|(_, &(bytes, protect, size))| (size, protect, bytes)) .collect(); let came_bytes: u64 = came.iter().map(|c| c.2).sum(); let (mut grew, mut grew_bytes) = (0u64, 0u64); for (base, o) in &others { if let Some(w) = was.get(base) && o.0 > w.0 { grew += 1; grew_bytes += o.0 - w.0; } } let (mut went, mut went_bytes) = (0u64, 0u64); for (base, w) in was { if !others.contains_key(base) { went += 1; went_bytes += w.0; } } let (_, _, came_by_size) = group(&mut came.iter().copied(), 8); tracing::info!( "memory map, the title's heaps not write-watched since the last map: {} allocations came, {} MB \ ({came_by_size}); {grew} grew by {} MB; {went} went, {} MB", came.len(), mb(came_bytes), mb(grew_bytes), mb(went_bytes) ); } *before = Some(others); } #[derive(Clone, Copy)] struct Census { textures: [u64; 10], targets: [u64; 16], at: std::time::Instant, took_us: u64, inline: bool, } static CENSUS: Mutex> = Mutex::new(None); const CENSUS_CHUNK: usize = 4096; fn census_period() -> Option { static PERIOD: std::sync::OnceLock> = std::sync::OnceLock::new(); *PERIOD.get_or_init(|| { let s = std::env::var("EONACAT_XS_CENSUS_S").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(60); (s > 0).then(|| std::time::Duration::from_secs(s)) }) } fn census_inline() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("EONACAT_XS_CENSUS_INLINE").is_ok_and(|v| v == "1")) } fn take_census(inline: bool) -> Census { let start = std::time::Instant::now(); let chunk = (!inline).then_some(CENSUS_CHUNK); let textures = crate::resource::census(chunk); let targets = crate::resource::targets_census(chunk); Census { textures, targets, at: std::time::Instant::now(), took_us: start.elapsed().as_micros() as u64, inline } } fn census_for_line() -> Option { static RUNNING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); let last = *CENSUS.lock().unwrap_or_else(|e| e.into_inner()); let period = census_period()?; let due = last.is_none_or(|c| c.at.elapsed() + std::time::Duration::from_millis(500) >= period); if !due { return last; } if census_inline() { let c = take_census(true); *CENSUS.lock().unwrap_or_else(|e| e.into_inner()) = Some(c); return Some(c); } if !RUNNING.swap(true, Relaxed) { let walk = std::thread::Builder::new().name("eonacat-census".into()).spawn(|| { let c = take_census(false); *CENSUS.lock().unwrap_or_else(|e| e.into_inner()) = Some(c); RUNNING.store(false, Relaxed); }); if walk.is_err() { RUNNING.store(false, Relaxed); } } last } pub(crate) fn log_memory() { use std::sync::atomic::Ordering::Relaxed; crate::memprobe::start(); let mb = |v: u64| v as f64 / (1 << 20) as f64; let (working, private) = process_memory(); let (free, left) = system_memory(); let copies = crate::shadow::memory(); let staged = crate::texture::memory(); let textures = [0, 1].map(|i| crate::resource::HOST_TEXTURES[i].load(Relaxed)); let made: Vec = crate::host::MADE.iter().map(|m| m.load(Relaxed)).collect(); let windows = crate::shadow::windows(); let stagings = crate::texture::let_go(); let taken = census_for_line(); let census = taken.map_or([0; 10], |c| c.textures); let kinds: Vec = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect(); let card = crate::host::host() .and_then(|h| h.video_memory()) .unwrap_or_default(); if let Some(h) = crate::host::host() { h.log_video_memory("with the memory line"); } static LINES: AtomicU64 = AtomicU64::new(0); static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if memory_map() && LINES.fetch_add(1, Relaxed) % 6 == 5 && !WALKING.swap(true, Relaxed) { let walk = std::thread::Builder::new().name("eonacat-memory-map".into()).spawn(|| { log_memory_map(); WALKING.store(false, Relaxed); }); if walk.is_err() { WALKING.store(false, Relaxed); } } let kept = crate::pipeline::kept(); tracing::info!( "memory kept beside the lines below: {} shader containers {:.0} MB, {} translations \ {:.0} MB; the pipeline library's file {:.0} MB (its last save wrote {:.0} MB)", kept[0], mb(kept[1]), kept[2], mb(kept[3]), mb(kept[4]), mb(kept[5]), ); tracing::info!( "memory of textures: {} title textures have no host copy yet ({:.0} MB of title memory); \ host copies the host renders to or writes: {} alive {:.0} MB; host copies the title \ fills: {} alive {:.0} MB ({} of them placed), {} let go {:.0} MB and {} made again \ {:.0} MB since the start; {} host copies made in all; passes that made none for lack of \ room: {}; the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \ shared with it in use", census[2], mb(census[3]), census[0], mb(census[1]), census[4], mb(census[5]), census[6], kinds[2], mb(kinds[3]), kinds[4], mb(kinds[5]), kinds[6], crate::draw::HEAP_TEXTURES_FULL.load(Relaxed), mb(card[1]), mb(card[0]), mb(card[3]), ); { let out = crate::resource::STREAMED_OUT.each_ref().map(|n| n.load(Relaxed)); let gone = crate::descriptor::host::GONE_NEUTRAL.each_ref().map(|n| n.load(Relaxed)); tracing::info!( "memory of streamed-out textures: host copies of placed textures the title fills whose memory is not mapped \ now {:.0} MB, of them {:.0} MB still shown by a slot (estimates from every 16th); since the start the sweep \ let go {} such copies first ({:.0} MB; EONACAT_XS_SWEEP_UNMAPPED=0: not); slots given up as streamed out {} \ shown the neutral texture, {} of them put first in the queue when their memory came back \ (EONACAT_XS_GONE_NEUTRAL=0: null, as before)", mb(census[8]), mb(census[9]), out[0], mb(out[1]), gone[0], gone[1], ); let stood = crate::descriptor::host::NEUTRAL_KINDS.each_ref().map(|n| n.load(Relaxed)); tracing::info!( "texture slots shown a gray stand-in since the start, by kind: 2D {} 1D {} 3D {} cube {} \ (EONACAT_XS_NEUTRAL_ALL_KINDS=0: 1D, 3D and cubes a null view, as before)", stood[0], stood[1], stood[2], stood[3], ); tracing::info!( "texture memory kept: soft budget {} (EONACAT_XS_TEXTURE_SOFT_MB), sweeps past it {}; empty texture blocks kept now at most {} (EONACAT_XS_SPARE_BLOCKS)", crate::resource::soft_budget().map_or("off".to_owned(), |b| format!("{} MB", b >> 20)), crate::resource::SOFT_SWEEPS.load(Relaxed), crate::pool::spares_now(), ); let h = crate::resource::unmapped_holders(); tracing::info!( "what holds host copies of placed textures whose memory is not mapped now (every 4th): all {} {:.0} MB; \ a list not reset {} {:.0} MB; another reference (slot, transition, twin) {} {:.0} MB; never asked for {} \ {:.0} MB; asked for within 5 s {} {:.0} MB; within 5-30 s {} {:.0} MB; written by the host {} {:.0} MB; \ held by nothing, idle 30 s+ {} {:.0} MB", h[0], mb(h[1]), h[2], mb(h[3]), h[4], mb(h[5]), h[6], mb(h[7]), h[8], mb(h[9]), h[10], mb(h[11]), h[12], mb(h[13]), h[14], mb(h[15]), ); let s = crate::resource::SWEEP_LIMITED.each_ref().map(|n| n.load(Relaxed)); tracing::info!( "sweeps with a limit since the start (card over its line): {}, asked to let go {:.0} MB, let go {:.0} MB, \ {} old enough copies looked at", s[0], mb(s[1]), mb(s[2]), s[3], ); } { let [textures, staging] = crate::pool::memory(); tracing::info!("memory in blocks (EONACAT_XS_TEXTURE_POOL=0 turns them off): {textures} MB of textures, {staging} MB of their staging buffers"); let [q0, q1, q2, q3] = crate::pool::texture_fullness(); tracing::info!( "texture blocks by how full they are (EONACAT_XS_POOL_FULLEST=0: pieces from the first block with room): \ under 25 % {q0}, 25-50 % {q1}, 50-75 % {q2}, 75 % and more {q3}" ); { let [copies, bytes] = crate::resource::host_pressure_reclaimed(); let [blocks, block_bytes] = crate::pool::let_go(); tracing::info!( "host memory reclamation since the start: {copies} unmapped texture copies let go under host pressure ({:.0} MB); {blocks} empty pool blocks let go to Windows ({:.0} MB)", mb(bytes), mb(block_bytes) ); } } match taken { Some(c) => tracing::info!( "memory census (title textures, for the two lines that follow and 'memory, more'): taken {:.0} s ago in \ {:.1} ms, {} (EONACAT_XS_CENSUS_S={} sets the period, EONACAT_XS_CENSUS_INLINE=1 takes it on this thread)", c.at.elapsed().as_secs_f64(), c.took_us as f64 / 1e3, if c.inline { "on the presenting thread" } else { "on a thread of its own, in chunks" }, census_period().map_or(0, |p| p.as_secs()), ), None => tracing::info!( "memory census (title textures): none yet, the counts that follow are 0 (EONACAT_XS_CENSUS_S={}; 0 = never)", census_period().map_or(0, |p| p.as_secs()), ), } let targets = taken.map_or([0; 16], |c| c.targets); let [targets_made, targets_released] = crate::resource::TARGET_TEXTURES.each_ref().map(|n| n.load(Relaxed)); tracing::info!( "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. Of the first, {} whose title memory has a newer target now {:.0} MB and {} whose title memory is not mapped now, placed or not, {:.0} MB; title textures the host renders to or writes since the start: {targets_made} made, {targets_released} released", targets[0], mb(targets[1]), targets[10], mb(targets[11]), targets[2], mb(targets[3]), targets[4], mb(targets[5]), targets[6], mb(targets[7]), targets[8], mb(targets[9]), targets[12], mb(targets[13]), targets[14], mb(targets[15]), ); let w = crate::shadow::windows_by_use(); tracing::info!( "windows outside buffers by use (idle: no draw for 10 s, no list or slot): on the card {} in use {:.0} MB, {} idle {:.0} MB; in the PC's memory {} in use {:.0} MB, {} idle {:.0} MB; turned away from the card since the start {} {:.0} MB (EONACAT_XS_CARD_WINDOWS_IDLE_MS lets idle ones on the card go sooner)", w[0], mb(w[1]), w[2], mb(w[3]), w[4], mb(w[5]), w[6], mb(w[7]), w[8], mb(w[9]) ); tracing::info!( "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ asked for in each", windows[0], mb(windows[1]), stagings[0], mb(stagings[1]), mb(windows[2]), ); tracing::info!( "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \ left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \ outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \ textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \ {} placed in title memory; made so far: {} upload buffers {:.0} MB, {} shared buffers \ {:.0} MB, {} card buffers {:.0} MB", mb(private), mb(working), mb(free), mb(left), copies[0], mb(copies[1]), copies[2], mb(copies[3]), copies[4], mb(copies[5]), staged[0], mb(staged[1]), staged[2], textures[0], mb(textures[1]), crate::resource::placed_textures(), made[0], mb(made[1]), made[2], mb(made[3]), made[4], mb(made[5]), ); tracing::info!( "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; EONACAT_XS_PLACED_FILLER=1 keeps it)", crate::resource::placed_filler_twins() ); let alive: Vec = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect(); let window = crate::shadow::window_use(); let views = crate::descriptor::views_kept(); let own: Vec = (0..8).map(owned).collect(); tracing::info!( "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 {})", alive[0], alive[1], mb(alive[2]), alive[3], mb(alive[4]), alive[5], alive[6], mb(alive[7]), window[7] >> 10, mb(window[0]), window[1], mb(window[2]), window[3], mb(window[4]), window[5], mb(window[6]), crate::draw::HEAP_VIEWS_ELSEWHERE.load(Relaxed), views[0], views[1], mb(views[2]), mb(own[..4].iter().sum()), own[4..].iter().sum::(), mb(own[0]), own[4], mb(own[1]), own[5], mb(own[2]), own[6], mb(own[3]), own[7], ); let lists: Vec = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect(); tracing::info!( "memory, more: views named whole in their records since the start: {} constant buffer \ views, {} views of placed memory; of the view table's entries {} are constant buffer \ views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \ made by the host, {} preludes made for them ({} alive), private bytes grew {:.0} MB while \ lists were made; twins of depth textures: {:.0} MB; host copies of \ placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \ them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \ let go from memory so far: {:.0} MB; our own blocks of 32 MB and more, in MB: {}", views[6], views[7], views[3], views[4], views[5], lists[0], lists[1], crate::host::PRELUDES_ALIVE.load(Relaxed), lists[2] as i64 as f64 / (1 << 20) as f64, mb(census[7]), mb(census[8]), mb(census[9]), mb(kept[6]), big_blocks(), ); tracing::info!( "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \ memory that is in more than one window, and is copied once for each); host lists never \ reset since they were made: {}; windows grown (EONACAT_XS_WINDOW_GROW): {} since the start, \ {} taken over and still held {:.0} MB, {} slots of the heap and {} of draws' tables moved \ to the longer one", mb(copies[3]), mb(crate::shadow::window_cover()), lists[3], crate::shadow::GROWN[0].load(Relaxed), crate::shadow::taken_over_held().0, mb(crate::shadow::taken_over_held().1), crate::shadow::GROWN[1].load(Relaxed), crate::shadow::GROWN[2].load(Relaxed), ); if crate::shadow::grow() { log_heap_elsewhere(); } } fn log_heap_elsewhere() { use crate::draw::{ HEAP_ELSEWHERE_OUTSIDE, HEAP_ELSEWHERE_SLOTS, HEAP_ELSEWHERE_WHY, HEAP_LOOKS, HEAP_MADE_AGAIN_NULL, HEAP_VIEWS_ELSEWHERE, HEAP_VIEWS_STILL_ELSEWHERE, }; let w = |shown: usize, found: usize| HEAP_ELSEWHERE_WHY[shown * 5 + found].load(Relaxed); let (looks, passes) = (HEAP_LOOKS[0].load(Relaxed), HEAP_LOOKS[1].load(Relaxed)); let elsewhere = HEAP_VIEWS_ELSEWHERE.load(Relaxed); let named = [w(0, 1), w(1, 1), w(2, 1), w(1, 2), w(1, 3), w(3, 1), w(3, 3), (0..5).map(|f| w(4, f)).sum::()]; tracing::info!( "memory, heap slots elsewhere: {elsewhere} in {looks} looks over {passes} passes ({:.3} a pass), \ {} distinct slots; still elsewhere after being made again {}; begin outside their buffer {}; \ shown -> found: taken over -> window {}, window -> window {}, own bytes -> window {}, \ window -> own bytes {}, window -> title buffer {}, title buffer -> window {}, \ title buffer -> title buffer {}, let go -> any {}, other {}; made again on the longer window \ and left null {}", elsewhere as f64 / passes.max(1) as f64, HEAP_ELSEWHERE_SLOTS.lock().unwrap_or_else(|e| e.into_inner()).len(), HEAP_VIEWS_STILL_ELSEWHERE.load(Relaxed), HEAP_ELSEWHERE_OUTSIDE.load(Relaxed), named[0], named[1], named[2], named[3], named[4], named[5], named[6], named[7], elsewhere.saturating_sub(named.iter().sum()), HEAP_MADE_AGAIN_NULL.load(Relaxed), ); let [taken, not_made, below, below_unsized, above] = crate::shadow::window_trim(); let mb = |v: u64| v as f64 / (1 << 20) as f64; tracing::info!( "memory, windows cut nearer: {taken} asks of draws took a longer window of their cell instead of \ making the cell's own ({:.0} MB not made, since the start); of the windows alive, {:.0} MB lie \ below the lowest ask's 256 KiB step ({:.0} MB of them in windows asked for without a length: \ EONACAT_XS_WINDOW_TAILS=1) and {:.0} MB past the highest ask's 1 MiB line in windows only asked for \ with a length (EONACAT_XS_WINDOW_KB=1024)", mb(not_made), mb(below), mb(below_unsized), mb(above), ); } fn now_us() -> u64 { static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 } static PRESENTED_AT: AtomicU64 = AtomicU64::new(0); static SUBMITTED_AT: AtomicU64 = AtomicU64::new(0); static RECORDED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); static SUBMITTED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); #[derive(Default, Clone, Copy)] struct Submitter { submissions: u64, between: u64, between_user: u64, between_kernel: u64, between_ours: u64, lock: u64, inside_user: u64, inside_kernel: u64, } static SUBMITTERS: Mutex> = Mutex::new(Vec::new()); static RECORDERS: Mutex> = Mutex::new(Vec::new()); thread_local! { static LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; static ENTERED: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; static OURS: std::cell::Cell = const { std::cell::Cell::new(0) }; static UNSENT: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; } fn thread_id() -> u32 { unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } } fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10 } fn thread_times() -> (u64, u64) { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; (micros(user), micros(kernel)) } fn process_times() -> (u64, u64) { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; (micros(user), micros(kernel)) } fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter { let at = match all.iter().position(|s| s.0 == id) { Some(at) => at, None => { all.push((id, Submitter::default())); all.len() - 1 } }; &mut all[at].1 } fn call_stats_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("EONACAT_XS_CALL_STATS").is_some_and(|v| v == "1")) } static BY_METHOD: Mutex> = Mutex::new(Vec::new()); thread_local! { static MINE: std::cell::RefCell<(u32, Vec<(&'static str, u64, u64)>)> = const { std::cell::RefCell::new((0, Vec::new())) }; } pub(crate) fn by_method(method: &'static str, started: std::time::Instant) { if !call_stats_on() { return; } let ns = started.elapsed().as_nanos() as u64; MINE.with(|mine| { let mut mine = mine.borrow_mut(); let (calls, counts) = &mut *mine; match counts.iter_mut().find(|c| std::ptr::eq(c.0, method)) { Some(c) => { c.1 += 1; c.2 += ns; } None => counts.push((method, 1, ns)), } *calls += 1; if *calls >= 1024 { *calls = 0; let mut all = BY_METHOD.lock().unwrap_or_else(|e| e.into_inner()); for (m, n, t) in counts.drain(..) { match all.iter_mut().find(|c| c.0 == m) { Some(c) => { c.1 += n; c.2 += t; } None => all.push((m, n, t)), } } } }); } pub(crate) fn stage_mark() -> Option { call_stats_on().then(std::time::Instant::now) } pub(crate) fn stage(stage: &'static str, mark: &mut Option) { if let Some(at) = *mark { by_method(stage, at); *mark = Some(std::time::Instant::now()); } } fn method_name(full: &str) -> &str { let full = full.split('<').next().unwrap_or(full); let full = full.trim_end_matches("::{{closure}}"); full.rsplit("::").next().unwrap_or(full) } #[cfg(test)] mod method_name_tests { #[test] fn a_closure_type_name_is_cut_to_its_method() { assert_eq!(super::method_name("crate::list::state::draw_indexed::{{closure}}"), "draw_indexed"); assert_eq!(super::method_name("crate::list::with_binding::{{closure}}"), "with_binding"); assert_eq!(super::method_name("execute_indirect"), "execute_indirect"); } } pub(crate) fn recorded(started: std::time::Instant) { let took = started.elapsed(); let ns = took.as_nanos() as u64; crate::timeline::called(took); add(C::RecordCalls, 1); add(C::RecordNs, ns); if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { let began = now_us().saturating_sub(ns / 1000); add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed))); } OURS.with(|o| o.set(o.get() + ns)); let (unsent, calls) = UNSENT.with(|u| u.get()); let (unsent, calls) = (unsent + ns, calls + 1); if unsent < 2_000_000 { UNSENT.with(|u| u.set((unsent, calls))); return; } UNSENT.with(|u| u.set((0, 0))); let id = thread_id(); let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner()); match all.iter_mut().find(|r| r.0 == id) { Some(r) => (r.1, r.2) = (r.1 + unsent, r.2 + calls), None => all.push((id, unsent, calls)), } } pub(crate) fn submission_begins() { let now = now_us(); INSIDE.fetch_add(1, Relaxed); if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) { add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed))); } let (user, kernel) = thread_times(); ENTERED.with(|e| e.set((user, kernel))); let ours = OURS.with(|o| o.replace(0)); if let Some((left, u, k)) = LEFT.with(|l| l.get()) { let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); let s = submitter(&mut all, thread_id()); s.between += now.saturating_sub(left); s.between_user += user.saturating_sub(u); s.between_kernel += kernel.saturating_sub(k); s.between_ours += ours; } } pub(crate) fn submission_ends(lock: u64) { let now = now_us(); INSIDE.fetch_sub(1, Relaxed); SUBMITTED_AT.store(now, Relaxed); let (user, kernel) = thread_times(); let (u, k) = ENTERED.with(|e| e.get()); LEFT.with(|l| l.set(Some((now, user, kernel)))); OURS.with(|o| o.set(0)); let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); let s = submitter(&mut all, thread_id()); s.submissions += 1; s.lock += lock; s.inside_user += user.saturating_sub(u); s.inside_kernel += kernel.saturating_sub(k); } static INSIDE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); pub(crate) fn phase() -> u32 { if INSIDE.load(Relaxed) > 0 { 3 } else if SUBMITTED_SINCE.load(Relaxed) { 2 } else { u32::from(RECORDED_SINCE.load(Relaxed)) } } pub(crate) fn present_begins() { add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed))); } pub(crate) fn presented() { add(C::Frames, 1); PRESENTED_AT.store(now_us(), Relaxed); RECORDED_SINCE.store(false, Relaxed); SUBMITTED_SINCE.store(false, Relaxed); } fn page_faults() -> u64 { use crate::memcalls::ps::{ K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, }; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut c = PROCESS_MEMORY_COUNTERS { cb: size_of::() as u32, ..Default::default() }; unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; u64::from(c.PageFaultCount) } pub(crate) fn log(frames: f64) { let counted = taken(C::Frames as usize); let frames = if counted > 0 { counted as f64 } else { frames }; static FAULTS: AtomicU64 = AtomicU64::new(0); let faults = page_faults(); let faults = faults - FAULTS.swap(faults, Relaxed).min(faults); let c: Vec = (0..COUNTERS).map(|i| taken(i) as f64 / frames).collect(); let mb = |v: f64| v / 1e6; let ms = |v: f64| v / 1e3; tracing::info!( "copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \ {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \ {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \ unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \ changed, {:.1} MB hashed, {:.1} MB of them changed, {:.1} changes the guard did not see", c[C::Submissions as usize], c[C::Copies as usize], mb(c[C::CopyBytes as usize]), c[C::Refreshes as usize], mb(c[C::RefreshBytes as usize]), c[C::Skipped as usize], mb(c[C::SkippedBytes as usize]), c[C::Runs as usize], ms(c[C::RunUs as usize]), c[C::Queries as usize], ms(c[C::QueryUs as usize]), ms(c[C::MoveUs as usize]), mb(c[C::Unmapped as usize]), faults as f64 / frames, c[C::Watches as usize], ms(c[C::WatchUs as usize]), mb(c[C::Checked as usize]), mb(c[C::Unchanged as usize]), c[C::Fallbacks as usize], c[C::GuardFaults as usize], mb(c[C::TexWatched as usize]), mb(c[C::TexHashed as usize]), mb(c[C::TexChanged as usize]), c[C::TexHot as usize], ); tracing::info!( "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \ threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \ refused, {:.1} ms searching; notes {:.1} ms; shader-written ranges: {:.0} steps in \ {:.1} submissions, snapshots {:.1} ms, {:.1} MB compared back; sparse reads {:.1} ms; \ guards {:.1} ms; {:.1} MB copied whole (memory not watched); {:.1} frame waits \ sleeping {:.1} ms (all threads); ranges of shaders that cannot store to buffers: \ {:.0} steps {:.1} MB left out", c[C::RecordCalls as usize], c[C::RecordNs as usize] / 1e6, ms(c[C::PipelineWaitUs as usize]), c[C::DynamicAsked as usize], c[C::DynamicRefused as usize], c[C::DynamicNs as usize] / 1e6, c[C::NoteNs as usize] / 1e6, c[C::GpuWrites as usize], c[C::BackSubmissions as usize], ms(c[C::SnapshotUs as usize]), mb(c[C::BackCompared as usize]), ms(c[C::SparseUs as usize]), ms(c[C::GuardUs as usize]), mb(c[C::WholeBytes as usize]), c[C::PaceWaits as usize], ms(c[C::PaceUs as usize]), c[C::GpuWritesLeftOut as usize], mb(c[C::GpuWritesLeftOutBytes as usize]), ); let [together, written, mapped] = [0, 1, 2].map(|n| crate::watch::ALIASES[n].load(std::sync::atomic::Ordering::Relaxed)); tracing::info!( "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped" ); tracing::info!( "waits for the write trackers' locks per frame, all threads (number, time): {}", crate::watch::lock_waits(frames) ); let [copies, blocks, opened, stores, unknown, full, stayed, copied_same, records] = [0, 1, 2, 3, 4, 5, 6, 7, 8].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); tracing::info!( "the title's writes beside the guards, since the start: {copies} copies (EONACAT_XS_COPY_BESIDE=1), {blocks} blocks, {opened} opened; \ {stores} stores (EONACAT_XS_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many; left out for changing nothing: {stayed} stores, {copied_same} parts of copies, {records} copies of descriptors; \ the busiest stores (left out/changed): {}", crate::titlewrite::busiest() ); static CPU: Mutex<(u64, u64)> = Mutex::new((0, 0)); let (user, kernel) = process_times(); let (user, kernel) = { let mut last = CPU.lock().unwrap_or_else(|e| e.into_inner()); let spent = (user.saturating_sub(last.0), kernel.saturating_sub(last.1)); *last = (user, kernel); (spent.0 as f64 / 1e3 / frames, spent.1 as f64 / 1e3 / frames) }; tracing::info!( "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \ until the first submission; {:.1} ms from the last submission to the present call; \ lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \ all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \ putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \ submissions run at the present with their waits not met; waits for memory values: \ {:.0} looks {:.1} ms; {:.0} host lists made {:.1} ms; {:.0} parts of held submissions \ ran alone that the next part could have run with", ms(c[C::UntilRecordUs as usize]), ms(c[C::UntilSubmitUs as usize]), ms(c[C::TailUs as usize]), c[C::ResetNs as usize] / 1e6, ms(c[C::BackScanUs as usize]), c[C::BackDiffer as usize], ms(c[C::BackSyncUs as usize]), c[C::TexUploads as usize], c[C::TexSkipped as usize], c[C::Forced as usize], c[C::WaitChecks as usize], c[C::WaitCheckNs as usize] / 1e6, c[C::HostLists as usize], c[C::HostListNs as usize] / 1e6, c[C::PartsTogether as usize], ); let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut whole: Vec<_> = whole.into_iter().flatten().collect(); whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); tracing::info!( " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow", ms(c[C::WholeUs as usize]), whole.len() ); for ((src, len), (n, us)) in whole.into_iter().take(6) { tracing::info!( " copied whole from {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", n as f64 / frames, (len as u64 * n) as f64 / 1e6 / frames, us as f64 / 1e3 / frames ); } let longest = std::mem::take(&mut *LONGEST.lock().unwrap_or_else(|e| e.into_inner())); tracing::info!( " waiting for the card per frame: {:.1} submissions under 2 ms ({:.1} ms), {:.1} of 2-8 ms \ ({:.1} ms), {:.1} of 8-32 ms ({:.1} ms), {:.1} longer ({:.1} ms); {:.1} submissions hand \ nothing back to the title ({:.1} ms of the waiting); the longest since the last line: \ {:.1} ms, {}", c[C::CardUnder2 as usize], ms(c[C::CardUnder2Us as usize]), c[C::Card2To8 as usize], ms(c[C::Card2To8Us as usize]), c[C::Card8To32 as usize], ms(c[C::Card8To32Us as usize]), c[C::CardOver32 as usize], ms(c[C::CardOver32Us as usize]), c[C::NothingBack as usize], ms(c[C::NothingBackUs as usize]), longest.0 as f64 / 1e3, longest.1 ); let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut by: Vec<_> = by.into_iter().flatten().collect(); by.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); for (what, (n, us)) in by.into_iter().take(12) { tracing::info!( " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}", us as f64 / 1e3 / frames, n as f64 / frames, what.chars().take(700).collect::() ); } let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut by: Vec<_> = by.into_iter().flatten().collect(); by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); if !by.is_empty() { let mut kinds: Vec<(String, u64, u64)> = Vec::new(); for (what, (n, us, _)) in &by { let word = what.split(' ').next().unwrap_or("").to_owned(); match kinds.iter_mut().find(|k| k.0 == word) { Some(k) => (k.1, k.2) = (k.1 + n, k.2 + us), None => kinds.push((word, *n, *us)), } } kinds.sort_by_key(|k| std::cmp::Reverse(k.2)); let all: u64 = kinds.iter().map(|k| k.2).sum(); let text: Vec = kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect(); tracing::info!( " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}", by.len(), all as f64 / 1e3 / frames, text.join(", ") ); } let mut sizes = COMMAND_SIZES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); for (i, (what, (n, us, longest))) in by.into_iter().take(40).enumerate() { tracing::info!( " the card's time by command (timing run): {:.2} ms a frame in {:.1} commands a frame, the longest {:.2} ms: {what}", us as f64 / 1e3 / frames, n as f64 / frames, longest as f64 / 1e3 ); let Some(by_size) = sizes.remove(&what).filter(|_| i < 10) else { continue; }; let mut by_size: Vec<_> = by_size.into_iter().collect(); by_size.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); let text: Vec = by_size .iter() .take(6) .map(|(size, (n, us))| { format!("{size}: {:.1}x {:.2} ms", *n as f64 / frames, *us as f64 / 1e3 / frames) }) .collect(); tracing::info!(" by size, {} sizes: {}", by_size.len(), text.join(", ")); } tracing::info!( " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \ for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \ such waits each), {:.0} batched clamps ended by a record written since the last; {:.0} of all these after nothing that writes; \ {:.0} title waits left out after one with only bindings since; barrier experiment {}", c[C::WaitsForGroups as usize], c[C::WaitsForBuffers as usize], c[C::IndirectBounded as usize], c[C::BatchArgsWritten as usize], c[C::WaitsQuiet as usize], c[C::WaitsLeftOut as usize], barrier_test() ); tracing::info!( " the title's barrier group calls, per frame: {:.0} end an unordered access, {:.0} only begin one, \ {:.0} name none", c[C::GroupsEndWrites as usize], c[C::GroupsBeginWrites as usize], c[C::GroupsOther as usize] ); tracing::info!( " root views, per frame: {:.0} bound as the list bound them before, {:.0} looked up (EONACAT_XS_ROOT_SAME)", c[C::RootSameHit as usize], c[C::RootSameMiss as usize] ); tracing::info!( " root SRV tables, per frame: {:.0} bytes of host copy asked, {:.0} of them left out as an earlier tail covered them (EONACAT_XS_ROOT_TAILS)", c[C::RootTailAsked as usize], c[C::RootTailCovered as usize] ); tracing::info!( " table entries not made afresh, per frame: {:.0}, {:.0} of them left as they were (EONACAT_XS_TABLE_SAME)", c[C::TableEntries as usize], c[C::TableEntriesSame as usize] ); tracing::info!( " tables with no room that read the same records' run of another table, per frame: {:.0}, {:.0} \ slots", c[C::FreshSameUsed as usize], c[C::FreshSameUsedSlots as usize] ); tracing::info!( " the title's own unordered access barriers, per frame: {:.0} on every resource, {:.0} on one; \ {:.0} covered by another in the same call, {:.0} after nothing that writes (EONACAT_XS_UAV_FOLD {})", c[C::UavGlobals as usize], c[C::UavOnResources as usize], c[C::UavFolded as usize], c[C::UavQuiet as usize], if crate::list::uav_fold() { "on" } else { "off" } ); let barriers = GROUP_BARRIERS.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut barriers: Vec<_> = barriers.into_iter().flatten().collect(); barriers.sort_by_key(|&(_, n)| std::cmp::Reverse(n)); for ((kind, [sync_before, sync_after, before, after]), n) in barriers.into_iter().take(24) { tracing::info!( " barriers in groups: {:.1} a frame of kind {kind} (0 global, 1 texture, 2 buffer), sync \ {sync_before:#x} -> {sync_after:#x}, access {before:#x} -> {after:#x}", n as f64 / frames ); } barrier_next(); let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut compared: Vec<_> = compared.into_iter().flatten().collect(); compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len()); for ((src, len), (n, written)) in compared.into_iter().take(8) { tracing::info!( " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back", n as f64 / frames, (len as u64 * n) as f64 / 1e6 / frames, written as f64 / 1e6 / frames ); } let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner())); submitters.sort_by_key(|s| std::cmp::Reverse(s.1.submissions)); for (id, s) in submitters.into_iter().take(4) { let per = |v: u64| v as f64 / 1e3 / frames; tracing::info!( " thread {id} submitted {:.1}x/frame: between its submissions {:.1} ms (running \ {:.1} ms user + {:.1} ms kernel; {:.1} ms in list calls), in them running {:.1} ms \ user + {:.1} ms kernel, {:.1} ms waiting for the submission lock", s.submissions as f64 / frames, per(s.between), per(s.between_user), per(s.between_kernel), s.between_ours as f64 / 1e6 / frames, per(s.inside_user), per(s.inside_kernel), per(s.lock), ); } let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner())); recorders.sort_by_key(|r| std::cmp::Reverse(r.1)); let busiest: Vec = recorders .iter() .take(6) .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames)) .collect(); tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", ")); if call_stats_on() { let mut all = std::mem::take(&mut *BY_METHOD.lock().unwrap_or_else(|e| e.into_inner())); all.sort_by_key(|c| std::cmp::Reverse(c.2)); let top: Vec = all .iter() .take(26) .map(|&(m, n, t)| { format!( "{} {:.0}/frame {:.1} us {:.1} ms", method_name(m), n as f64 / frames, t as f64 / 1e3 / n.max(1) as f64, t as f64 / 1e6 / frames ) }) .collect(); tracing::info!(" list calls by method, all threads (EONACAT_XS_CALL_STATS=1): {}", top.join(", ")); } if !crate::host::sweeper::ask_census() { log_memory(); } let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) { use crate::memcalls::sys::{MEMORY_BASIC_INFORMATION, VirtualQuery}; let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; unsafe { VirtualQuery(src as *const _, &mut info, size_of_val(&info)) }; let kind = info.Type; tracing::info!( " copied from {src:#x}+{len:#x} (memory {kind:#x}): {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", n as f64 / frames, bytes as f64 / 1e6 / frames, us as f64 / 1e3 / frames ); } } #[cfg(test)] mod memory_map_tests { use super::format_biggest_groups; use std::collections::HashMap; type World = ( HashMap, HashMap, HashMap, ); fn add( world: &mut World, base: usize, (kind, whole, committed, in_memory): (usize, usize, u64, u64), ) { world.0.insert(base, (kind, committed)); world.1.insert(base, whole); world.2.insert(base, in_memory); } #[test] fn vram_blocks_show_nothing_in_memory() { let mut world = World::default(); add(&mut world, 0x1000, (5, 64 << 20, 64 << 20, 0)); let (total, biggest) = format_biggest_groups(&world.0, &world.1, &world.2, 20); assert_eq!(total, 1); assert_eq!(biggest.join("; "), "1 of 64.00 MB write-combined: 64 MB (0 MB in memory)"); } #[test] fn a_group_says_what_of_it_is_in_memory() { let mut world = World::default(); add(&mut world, 0x1000, (5, 64 << 20, 64 << 20, 0)); add(&mut world, 0x2000, (5, 64 << 20, 64 << 20, 64 << 20)); let (total, biggest) = format_biggest_groups(&world.0, &world.1, &world.2, 20); assert_eq!(total, 1); assert_eq!(biggest.join("; "), "2 of 64.00 MB write-combined: 128 MB (64 MB in memory)"); } #[test] fn biggest_are_first_and_equal_sizes_keep_the_same_order() { let mut world = World::default(); add(&mut world, 0x3000, (5, 32 << 20, 28 << 20, 28 << 20)); add(&mut world, 0x4000, (6, 32 << 20, 20 << 20, 20 << 20)); add(&mut world, 0x5000, (6, 1 << 30, 40 << 20, 40 << 20)); add(&mut world, 0x6000, (5, 64 << 20, 20 << 20, 0)); let (total, biggest) = format_biggest_groups(&world.0, &world.1, &world.2, 2); assert_eq!(total, 4); assert_eq!( biggest.join("; "), "1 of 1024.00 MB: 40 MB (40 MB in memory); \ 1 of 32.00 MB write-combined: 28 MB (28 MB in memory)" ); let (_, all) = format_biggest_groups(&world.0, &world.1, &world.2, 20); assert_eq!( all.join("; "), "1 of 1024.00 MB: 40 MB (40 MB in memory); \ 1 of 32.00 MB write-combined: 28 MB (28 MB in memory); \ 1 of 64.00 MB write-combined: 20 MB (0 MB in memory); \ 1 of 32.00 MB: 20 MB (20 MB in memory)" ); } }