| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553 |
- //! `xmem.dll`: console memory, served from host memory. The GPU side works
- //! from CPU addresses (unified memory), so memory types and bandwidth
- //! classes change nothing here; what constrains addresses (alignment,
- //! 2 MiB pages, address-bit limits) is honoured.
- #![allow(non_snake_case)]
- // Title code calls these through its import table, passing pointers the real
- // API would trust.
- #![allow(clippy::not_unsafe_ptr_arg_deref)]
- use std::alloc::{Layout, alloc, dealloc};
- use std::collections::{BTreeMap, HashMap};
- use std::ffi::c_void;
- use std::sync::atomic::{AtomicUsize, Ordering};
- use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
- use windows_sys::Win32::Foundation::{
- CloseHandle, ERROR_COMMITMENT_LIMIT, HANDLE, INVALID_HANDLE_VALUE,
- };
- use windows_sys::Win32::System::Memory::{
- CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER,
- MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE,
- MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3,
- MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_COMMIT,
- SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx,
- };
- use windows_sys::Win32::System::ProcessStatus::{
- K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION,
- PROCESS_MEMORY_COUNTERS,
- };
- use windows_sys::Win32::System::Threading::GetCurrentProcess;
- use windows_sys::core::BOOL;
- use crate::{HleModule, hle_export};
- const MIB: usize = 1 << 20;
- /// Whether we run under Wine (its ntdll exports `wine_get_version`).
- pub(crate) fn on_wine() -> bool {
- static WINE: LazyLock<bool> = LazyLock::new(|| {
- use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress};
- // SAFETY: plain lookups in ntdll, always loaded.
- unsafe {
- let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast());
- !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some()
- }
- });
- *WINE
- }
- /// Standard memory the title has handed to the system.
- static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
- // Console additions to the host's flags.
- /// 2 MiB pages; the host reads this bit as large pages, which need a
- /// privilege.
- const PAGES_2M: u32 = 0x2000_0000;
- /// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory.
- const PAGES_64K_BIT: u32 = 0x40_0000;
- const PAGES_64K: u32 = PAGES_2M | PAGES_64K_BIT;
- /// The host's protection constants and `PAGE_GUARD`. Above them the console
- /// adds GPU access bits (0x800-0x40000). Write-combining and uncached are
- /// dropped too: our GPU side reads this memory through the CPU.
- const HOST_PROTECTION: u32 = 0x1ff;
- /// XMem flags of memory both processors reach: all of ours.
- const GRAPHICS: u64 = 3;
- /// XMem flag bit of 32-bit graphics memory.
- const ADDRESS_32BIT: u64 = 4;
- /// The host's write watching (not in windows-sys' memory module).
- const MEM_WRITE_WATCH: u32 = 0x20_0000;
- /// The addresses XMem `flags` allow, first and last: the low 4 GiB for
- /// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the
- /// title's big pools would otherwise crowd out) up to 46 down to 40 bits
- /// from the field at bit 12, or 40 bits without one: the console keeps
- /// title memory there, and its ray-tracing structures must be (
- /// the title's BVH builder refuses one above; the title asks for its GPU heap
- /// with no field). Decision 0001.
- fn address_range(flags: u64) -> (usize, usize) {
- let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) {
- (0, 0) => 40,
- (0, field) => 47 - field,
- _ => return (0, u32::MAX as usize),
- };
- (1 << 32, (1 << bits) - 1)
- }
- pub extern "system" fn XMemVirtualAlloc(
- base: *mut c_void,
- size: usize,
- kind: u32,
- flags: u64,
- protect: u32,
- ) -> *mut c_void {
- let (lowest, highest) = address_range(flags);
- let mut requirements = MEM_ADDRESS_REQUIREMENTS {
- LowestStartingAddress: lowest as *mut c_void,
- HighestEndingAddress: highest as *mut c_void,
- Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M {
- 2 * MIB
- } else {
- 0
- },
- };
- let mut protect = match protect & HOST_PROTECTION {
- 0 => PAGE_NOACCESS,
- p => p,
- };
- // A reservation of 64 KiB pages takes physical pages later
- // (`XMemMapPhysicalPages`); on the host only a placeholder can.
- // shortcut: committing part of such a reservation later would fail
- // (the title's 23 calls never do); replace that part of the
- // placeholder then.
- let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0;
- if placeholder {
- if kind & MEM_REPLACE_PLACEHOLDER != 0 {
- // Part of a placeholder the title split: it stays one.
- return base;
- }
- protect = PAGE_NOACCESS;
- }
- let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
- if placeholder {
- kind |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER;
- }
- let mut parameter = MEM_EXTENDED_PARAMETER::default();
- parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
- parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
- // Address requirements apply to reservations at an address of our choice.
- let constrained = base.is_null();
- if constrained {
- kind |= MEM_RESERVE;
- // The GPU side copies only the pages the title wrote since its last
- // copy (`victory_gpu`, decision 0007); placeholders cannot be
- // watched (their physical-page views are copied whole).
- if kind & MEM_RESERVE_PLACEHOLDER == 0 {
- kind |= MEM_WRITE_WATCH;
- }
- }
- // SAFETY: the title's own arguments, cleaned of console bits; the
- // parameter points at `requirements`, which outlives the call.
- let at = unsafe {
- VirtualAlloc2(
- GetCurrentProcess(),
- base,
- size,
- kind,
- protect,
- if constrained {
- &mut parameter
- } else {
- std::ptr::null_mut()
- },
- constrained.into(),
- )
- };
- if base.is_null() {
- tracing::debug!(
- size,
- kind = format_args!("{kind:#x}"),
- flags = format_args!("{flags:#x}"),
- at = format_args!("{at:p}"),
- "XMemVirtualAlloc"
- );
- }
- if !at.is_null() && !placeholder {
- victory_gpu::title_memory_allocated(at as usize, size);
- }
- at
- }
- /// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
- /// same), then the XMem flags and tag.
- #[repr(C)]
- pub struct BasicInformation {
- host: MEMORY_BASIC_INFORMATION,
- flags: u64,
- tag_code: u32,
- tag: [u8; 4],
- }
- // shortcut: every committed page reports graphics memory and no tag, since
- // all of it is GPU-reachable here (the title's BVH builder, the
- // only caller, wants graphics memory); remember the flags of
- // `XMemVirtualAlloc` regions if a title tells CPU-only memory apart.
- pub extern "system" fn XMemVirtualQuery(
- process: HANDLE,
- address: *const c_void,
- out: *mut BasicInformation,
- ) -> BOOL {
- let size = size_of::<MEMORY_BASIC_INFORMATION>();
- // SAFETY: the title passes room for the whole structure; the host
- // fails on a null one.
- unsafe {
- if VirtualQueryEx(process, address, out.cast(), size) == 0 {
- return 0;
- }
- let info = &mut *out;
- info.flags = if info.host.State == MEM_COMMIT {
- GRAPHICS
- } else {
- 0
- };
- info.tag_code = 0;
- info.tag = [0; 4];
- }
- 1
- }
- // `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up
- // from 2), then the memory type, then bit 33: a 32-bit address.
- const ALIGNMENT_SHIFT: u64 = 24;
- const ALLOC_32BIT: u64 = 1 << 33;
- /// Our block header: the block's size and alignment, just below the
- /// pointer handed out.
- const HEADER: usize = 2 * size_of::<usize>();
- fn layout(size: usize, attributes: u64) -> Option<Layout> {
- // An alignment of at least 16 leaves room for the header.
- let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4);
- Layout::from_size_align(size.checked_add(align)?, align).ok()
- }
- type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
- type FreeRoutine = extern "system" fn(*mut c_void, u64);
- /// The allocation and free routines the title's exe exports as
- /// `__XMemAllocationHooks__` (the title does): `XMemAlloc` and
- /// `XMemFree` call them, for the title's own calls and its middleware's;
- /// the `…Default` exports do not.
- fn hooks() -> [usize; 2] {
- static AT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
- let at = match AT.get() {
- Some(&at) => at,
- // Looked up once the title is mapped, which is before it runs.
- None => match crate::runtime::main_image() {
- Some(base) => *AT.get_or_init(|| {
- use windows_sys::Win32::System::LibraryLoader::GetProcAddress;
- // SAFETY: a mapped image and a NUL-terminated name.
- let at = unsafe {
- GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast())
- }
- .map_or(0, |f| f as usize);
- tracing::info!(found = at != 0, "xmem allocation hooks");
- at
- }),
- None => 0,
- },
- };
- if at == 0 {
- return [0; 2];
- }
- // SAFETY: the export is two routine pointers.
- unsafe { (at as *const [usize; 2]).read() }
- }
- /// The title's general allocator, for middleware too: its hook if it has
- /// one, else [`XMemAllocDefault`].
- pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
- match hooks()[0] {
- 0 => XMemAllocDefault(size, attributes),
- hook => {
- // SAFETY: the title's own routine of this type.
- let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) };
- alloc(size, attributes)
- }
- }
- }
- /// See [`XMemAlloc`].
- pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
- match hooks()[1] {
- 0 => XMemFreeDefault(address, attributes),
- hook => {
- // SAFETY: the title's own routine of this type.
- let free: FreeRoutine = unsafe { std::mem::transmute(hook) };
- free(address, attributes)
- }
- }
- }
- /// The system allocator behind [`XMemAlloc`].
- pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void {
- if attributes & ALLOC_32BIT != 0 {
- return XMemVirtualAlloc(
- std::ptr::null_mut(),
- size,
- MEM_RESERVE | MEM_COMMIT,
- GRAPHICS | ADDRESS_32BIT,
- PAGE_READWRITE,
- );
- }
- let Some(layout) = layout(size, attributes) else {
- return std::ptr::null_mut();
- };
- // shortcut: the host heap's addresses lie above 2^40, unlike the
- // console's; nothing seen builds ray-tracing structures in this memory
- // (the title uses its GPU heap). Sub-allocate from a
- // reservation below 2^40 if one does.
- // SAFETY: the layout has a non-zero size.
- let block = unsafe { alloc(layout) };
- if block.is_null() {
- return block.cast();
- }
- // SAFETY: the block holds the alignment (at least the header) and then
- // `size` bytes.
- unsafe {
- let user = block.add(layout.align());
- user.sub(HEADER)
- .cast::<[usize; 2]>()
- .write([layout.size(), layout.align()]);
- user.cast()
- }
- }
- /// Frees what [`XMemAllocDefault`] returned, given the same attributes.
- pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
- if address.is_null() {
- return;
- }
- // SAFETY: the address came from `XMemAlloc` with these attributes: a
- // whole reservation, or a header-prefixed block.
- unsafe {
- if attributes & ALLOC_32BIT != 0 {
- VirtualFree(address, 0, MEM_RELEASE);
- return;
- }
- let user = address.cast::<u8>();
- let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read();
- dealloc(
- user.sub(align),
- Layout::from_size_align_unchecked(size, align),
- );
- }
- }
- /// A retail console has no tools memory.
- pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL {
- 0
- }
- // Physical pages: on the console, 64 KiB frames a title maps into its own
- // reservations, at more than one address if it likes. Here each allocation
- // is a pagefile-backed section, its pages are 64 KiB slices of it, and a
- // mapping is a view of consecutive slices in place of a host placeholder.
- const PAGE: usize = 64 << 10;
- struct Section {
- handle: HANDLE,
- pages: usize,
- /// A view of the whole section, kept ([`Section::window`]); 0 if the
- /// host gave none.
- window: std::sync::OnceLock<usize>,
- /// A bit per page: committed, as far as [`Section::window`] asked.
- committed: Box<[std::sync::atomic::AtomicU64]>,
- }
- impl Section {
- /// Where bytes of `n` pages from page `index` on can be written,
- /// whether or not the pages are mapped anywhere, committed.
- ///
- /// Every DirectStorage write mapped a view of its pages, committed it,
- /// faulted each of its 4 KiB pages in and unmapped it again, all of it
- /// under the process's one address-space lock, with 24 workers, the
- /// title's own mapping calls (about 100,000 views of one page) and our
- /// guards asking for the same lock. One view of the section, kept,
- /// costs that once per page.
- /// `VICTORY_SECTION_WINDOW=0`: a view for each write, as before.
- fn window(&self, index: usize, n: usize) -> Option<usize> {
- use std::sync::atomic::Ordering;
- use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile};
- static ON: LazyLock<bool> =
- LazyLock::new(|| std::env::var_os("VICTORY_SECTION_WINDOW").is_none_or(|v| v != "0"));
- if !*ON || index + n > self.pages {
- return None;
- }
- let base = *self.window.get_or_init(|| {
- // SAFETY: the whole of a section we own.
- unsafe { MapViewOfFile(self.handle, FILE_MAP_WRITE, 0, 0, self.pages * PAGE) }.Value as usize
- });
- if base == 0 {
- return None;
- }
- let missing = |page: usize| self.committed[page / 64].load(Ordering::Acquire) >> (page % 64) & 1 == 0;
- let mut page = index;
- while page < index + n {
- if !missing(page) {
- page += 1;
- continue;
- }
- let run = (page..index + n).take_while(|&p| missing(p)).count();
- if run == 0 {
- continue; // another worker committed it meanwhile
- }
- if !commit(base + page * PAGE, run * PAGE) {
- return None;
- }
- for p in page..page + run {
- self.committed[p / 64].fetch_or(1 << (p % 64), Ordering::AcqRel);
- }
- page += run;
- }
- Some(base + index * PAGE)
- }
- }
- // SAFETY: a section handle may be used from any thread.
- unsafe impl Send for Section {}
- // SAFETY: as above.
- unsafe impl Sync for Section {}
- impl Drop for Section {
- fn drop(&mut self) {
- use windows_sys::Win32::System::Memory::UnmapViewOfFile;
- if let Some(&base) = self.window.get()
- && base != 0
- {
- // SAFETY: our view; whoever writes through it holds the section.
- unsafe {
- UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
- Value: base as *mut c_void,
- })
- };
- }
- victory_gpu::title_memory_section_gone(self.handle as usize);
- // SAFETY: our handle; views keep the section alive on their own.
- unsafe { CloseHandle(self.handle) };
- }
- }
- /// Where a page lives, or what a view starts with: a section and a page
- /// index in it.
- #[derive(Clone)]
- struct Slice {
- section: Arc<Section>,
- index: usize,
- }
- #[derive(Default)]
- struct Physical {
- next_page: usize,
- pages: HashMap<usize, Slice>,
- /// Mapped views by address: their length and what they show.
- views: BTreeMap<usize, (usize, Slice)>,
- /// The other way: the views (by address) that show a page, by the page's
- /// section and index. Views of more than [`SHORT`] pages are in `long`.
- shown: HashMap<(usize, usize), Vec<usize>>,
- long: Vec<usize>,
- }
- /// Pages of a view noted page by page in [`Physical::shown`].
- const SHORT: usize = 64;
- impl Physical {
- fn note_view(&mut self, base: usize, len: usize, slice: &Slice) {
- if len / PAGE > SHORT {
- self.long.push(base);
- return;
- }
- let section = Arc::as_ptr(&slice.section) as usize;
- for k in 0..len / PAGE {
- self.shown.entry((section, slice.index + k)).or_default().push(base);
- }
- }
- fn forget_view(&mut self, base: usize, len: usize, slice: &Slice) {
- if len / PAGE > SHORT {
- self.long.retain(|&b| b != base);
- return;
- }
- let section = Arc::as_ptr(&slice.section) as usize;
- for k in 0..len / PAGE {
- let key = (section, slice.index + k);
- if let Some(views) = self.shown.get_mut(&key) {
- views.retain(|&b| b != base);
- if views.is_empty() {
- self.shown.remove(&key);
- }
- }
- }
- }
- /// Where the title sees `n` pages from `slice` on: addresses and bytes.
- fn shown_at(&self, slice: &Slice, n: usize) -> Vec<(usize, usize)> {
- let section = Arc::as_ptr(&slice.section) as usize;
- let mut out: Vec<(usize, usize)> = Vec::new();
- for k in 0..n {
- for &base in self.shown.get(&(section, slice.index + k)).into_iter().flatten() {
- if let Some((_, s)) = self.views.get(&base) {
- out.push((base + (slice.index + k - s.index) * PAGE, PAGE));
- }
- }
- }
- for &base in &self.long {
- let Some((len, s)) = self.views.get(&base) else { continue };
- let from = slice.index.max(s.index);
- let to = (slice.index + n).min(s.index + len / PAGE);
- if Arc::as_ptr(&s.section) as usize == section && from < to {
- out.push((base + (from - s.index) * PAGE, (to - from) * PAGE));
- }
- }
- out
- }
- }
- /// DirectStorage has put bytes `[offset, offset + len)` of `pages` into
- /// memory: the GPU side is told where the title sees them, so that what it
- /// copied there before they arrived (a texture uploaded when its view was
- /// written holds whatever the pages held then) is copied again.
- /// `VICTORY_STREAM_NOTICE=0`: not told, as before.
- pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) {
- if !stream_notice() || len == 0 {
- return;
- }
- let mut seen: Vec<(usize, usize)> = {
- let physical = physical();
- let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default();
- numbers
- .iter()
- .filter_map(|n| physical.pages.get(n))
- .flat_map(|slice| physical.shown_at(slice, 1))
- .collect()
- };
- seen.sort_unstable();
- let mut runs: Vec<(usize, usize)> = Vec::new();
- for (at, len) in seen {
- match runs.last_mut() {
- Some(last) if last.0 + last.1 == at => last.1 += len,
- _ => runs.push((at, len)),
- }
- }
- for (at, len) in runs {
- victory_gpu::kernel_will_write(at, len);
- }
- }
- /// See [`pages_written`].
- pub(crate) fn stream_notice() -> bool {
- static ON: LazyLock<bool> =
- LazyLock::new(|| std::env::var_os("VICTORY_STREAM_NOTICE").is_none_or(|v| v != "0"));
- *ON
- }
- static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| {
- Mutex::new(Physical {
- // Page numbers are opaque to titles; 0 stays unused.
- next_page: 0x10_0000,
- ..Default::default()
- })
- });
- fn physical() -> MutexGuard<'static, Physical> {
- PHYSICAL.lock().unwrap_or_else(|e| e.into_inner())
- }
- /// `count` is in and out (pages wanted, pages given); all or nothing here.
- pub extern "system" fn XMemAllocatePhysicalPages(
- flags: u64,
- count: *mut usize,
- pages: *mut usize,
- ) -> BOOL {
- if count.is_null() || pages.is_null() {
- return 0;
- }
- // SAFETY: checked non-null.
- let n = unsafe { *count };
- let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else {
- return 0;
- };
- // A pagefile-backed section of `size` bytes, its pages committed when
- // first mapped or written (`commit`): the title asks for 6.1
- // GiB at once, which a busy host often cannot commit (error 1450).
- // SAFETY: plain section creation.
- let handle = unsafe {
- CreateFileMappingW(
- INVALID_HANDLE_VALUE,
- std::ptr::null(),
- // Under Wine a committed section is a sparse file, free until
- // touched, and committing a reserved one page by page costs a
- // wineserver request each that scans every range committed so
- // far: commit it whole there.
- PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE },
- (size as u64 >> 32) as u32,
- size as u32,
- std::ptr::null(),
- )
- };
- if handle.is_null() {
- let error = std::io::Error::last_os_error();
- tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed");
- // SAFETY: checked non-null.
- unsafe { count.write(0) };
- return 0;
- }
- tracing::debug!(
- n,
- flags = format_args!("{flags:#x}"),
- "XMemAllocatePhysicalPages"
- );
- // For the GPU side's in-place census: only a committed section can be
- // opened as a host heap.
- victory_gpu::title_memory_section(handle as usize, size as u64, on_wine());
- let section = Arc::new(Section {
- handle,
- pages: n,
- window: std::sync::OnceLock::new(),
- committed: (0..n.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(),
- });
- let mut physical = physical();
- let first = physical.next_page;
- physical.next_page += n * FRAMES;
- for index in 0..n {
- let slice = Slice {
- section: section.clone(),
- index,
- };
- let number = first + index * FRAMES;
- physical.pages.insert(number, slice);
- // SAFETY: the title passes room for `n` page numbers.
- unsafe { pages.add(index).write(number) };
- }
- 1
- }
- /// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of
- /// 16: the title keeps them as 21-bit `number >> 4` and rebuilds
- /// them with `<< 4` (128 GiB of pages at most).
- const FRAMES: usize = PAGE >> 12;
- /// Pages still mapped stay readable through their views until unmapped.
- pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL {
- if pages.is_null() {
- return 0;
- }
- let mut physical = physical();
- for i in 0..n {
- // SAFETY: the title passes `n` page numbers.
- physical.pages.remove(&unsafe { *pages.add(i) });
- }
- 1
- }
- /// A view of our own on consecutive slices of one section, committed and
- /// writable, unmapped when dropped.
- struct View {
- at: MEMORY_MAPPED_VIEW_ADDRESS,
- len: usize,
- }
- impl View {
- /// Maps `n` slices from `slice` on.
- fn map(slice: &Slice, n: usize) -> Option<View> {
- use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile};
- let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE);
- // SAFETY: slices of a section we own; the view is ours until dropped.
- let at = unsafe {
- MapViewOfFile(
- slice.section.handle,
- FILE_MAP_WRITE,
- (offset >> 32) as u32,
- offset as u32,
- len,
- )
- };
- if at.Value.is_null() {
- tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not mapped for a write");
- return None;
- }
- let view = View { at, len };
- if !commit(at.Value as usize, len) {
- tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not committed for a write");
- return None;
- }
- Some(view)
- }
- fn bytes(&mut self) -> &mut [u8] {
- // SAFETY: the view holds `len` committed read-write bytes, ours
- // alone while `self` lives (other views of the slices only alias
- // them, as the console's do).
- unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) }
- }
- }
- impl Drop for View {
- fn drop(&mut self) {
- use windows_sys::Win32::System::Memory::UnmapViewOfFile;
- // SAFETY: our view.
- unsafe { UnmapViewOfFile(self.at) };
- }
- }
- /// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB
- /// each), as runs of consecutive slices of one section: each run's first
- /// slice and its length in pages. One look at the page table, which the
- /// title's own mapping calls share with every DirectStorage worker. `None`
- /// if a page is unknown or `pages` ends early.
- fn runs(pages: &[usize], offset: usize, len: usize) -> Option<Vec<(Slice, usize)>> {
- let end = offset.checked_add(len)?;
- let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?;
- let physical = physical();
- let mut runs: Vec<(Slice, usize)> = Vec::new();
- for page in pages {
- let Some(slice) = physical.pages.get(page) else {
- tracing::warn!(page, offset, len, "a physical page the title does not own (any more)");
- return None;
- };
- match runs.last_mut() {
- Some((first, n))
- if Arc::ptr_eq(&first.section, &slice.section)
- && slice.index == first.index + *n =>
- {
- *n += 1;
- }
- _ => runs.push((slice.clone(), 1)),
- }
- }
- Some(runs)
- }
- /// Whether the title owns every page under bytes `[offset, offset + len)`.
- pub(crate) fn pages_known(pages: &[usize], offset: usize, len: usize) -> bool {
- let physical = physical();
- pages
- .get(offset / PAGE..(offset + len).div_ceil(PAGE))
- .is_some_and(|pages| pages.iter().all(|page| physical.pages.contains_key(page)))
- }
- /// Where the title sees the pages under bytes `[offset, offset + len)` now,
- /// in order (for the streaming trace: whether that changed while a request
- /// wrote them).
- pub(crate) fn pages_shown(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> {
- let physical = physical();
- let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default();
- let mut shown: Vec<(usize, usize)> = numbers
- .iter()
- .filter_map(|n| physical.pages.get(n))
- .flat_map(|slice| physical.shown_at(slice, 1))
- .collect();
- shown.sort_unstable();
- shown
- }
- /// Copies `data` into physical pages, from `offset` bytes into the first,
- /// whether or not they are mapped anywhere (DirectStorage destinations).
- /// One view per run of consecutive pages, not one per page: each view
- /// costs a map, a commit and an unmap (which flushes every core's TLB).
- /// False if a page is unknown or the host fails.
- pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool {
- let Some(runs) = runs(pages, offset, data.len()) else {
- return false;
- };
- let (mut within, mut done) = (offset % PAGE, 0);
- for (slice, n) in &runs {
- let k = (n * PAGE - within).min(data.len() - done);
- if let Some(at) = slice.section.window(slice.index, *n) {
- // SAFETY: committed bytes of the section's view, which `runs`
- // holds; the title's other uses of them race as on the console.
- unsafe { std::ptr::copy_nonoverlapping(data[done..].as_ptr(), (at + within) as *mut u8, k) };
- } else {
- let Some(mut view) = View::map(slice, *n) else {
- return false;
- };
- view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]);
- }
- (within, done) = (0, done + k);
- }
- true
- }
- /// Bytes `[offset, offset + len)` of physical pages, writable in place
- /// until dropped: DirectStorage decodes into it instead of a buffer it
- /// would then copy.
- pub(crate) struct PageWindow {
- view: Window,
- within: usize,
- len: usize,
- }
- enum Window {
- /// In the section's own view, which the section holds.
- Kept(usize, #[expect(dead_code, reason = "held for the view")] Arc<Section>),
- Own(View),
- }
- impl PageWindow {
- pub(crate) fn bytes(&mut self) -> &mut [u8] {
- let (within, len) = (self.within, self.len);
- match &mut self.view {
- // SAFETY: committed bytes of the section's view, ours alone as
- // far as the runtime goes (other views alias them, as the
- // console's do).
- Window::Kept(at, _) => unsafe { std::slice::from_raw_parts_mut((*at + within) as *mut u8, len) },
- Window::Own(view) => &mut view.bytes()[within..within + len],
- }
- }
- }
- /// A window on bytes `[offset, offset + len)` of `pages` when they are
- /// consecutive pages of one allocation (how titles usually hand them out);
- /// `None` otherwise (pages of several allocations, out of order, or
- /// unknown, or a host failure), which `write_physical` then handles or
- /// reports.
- pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option<PageWindow> {
- let runs = runs(pages, offset, len)?;
- let [(slice, n)] = runs.as_slice() else {
- return None;
- };
- let view = match slice.section.window(slice.index, *n) {
- Some(at) => Window::Kept(at, slice.section.clone()),
- None => Window::Own(View::map(slice, *n)?),
- };
- Some(PageWindow {
- view,
- within: offset % PAGE,
- len,
- })
- }
- /// Maps `n` pages at `address`, in place of what is mapped there; null
- /// `pages` unmaps. Returns `address`, or null if a page or the host fails.
- pub extern "system" fn XMemMapPhysicalPages(
- address: *mut c_void,
- n: usize,
- pages: *const usize,
- ) -> *mut c_void {
- let base = address as usize;
- let mut physical = physical();
- // Until the pages are mapped again: `unmap` takes whole views away and
- // maps what stays of them again, and a mapped view is a reservation
- // until it is committed. A read of title memory in place must not fall
- // into that gap (`victory_gpu::title_memory_remapping`).
- let _changing = victory_gpu::title_memory_remapping();
- unmap(&mut physical, base, n * PAGE);
- if pages.is_null() {
- return address;
- }
- // SAFETY: the title passes `n` page numbers.
- let pages = unsafe { std::slice::from_raw_parts(pages, n) };
- let mut i = 0;
- while i < n {
- let Some(first) = physical.pages.get(&pages[i]).cloned() else {
- tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page");
- return std::ptr::null_mut();
- };
- // One view per run of consecutive slices of one section.
- let run = 1 + pages[i + 1..]
- .iter()
- .zip(1..)
- .take_while(|&(page, k)| {
- physical.pages.get(page).is_some_and(|s| {
- Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k
- })
- })
- .count();
- if !map(&mut physical, base + i * PAGE, run * PAGE, first) {
- return std::ptr::null_mut();
- }
- i += run;
- }
- address
- }
- /// One page at each address; null `pages`, or a page number 0, unmaps
- /// (the title passes 0 for addresses to clear).
- pub extern "system" fn XMemMapPhysicalPagesScatter(
- addresses: *const *mut c_void,
- n: usize,
- pages: *const usize,
- ) -> BOOL {
- if addresses.is_null() {
- return 0;
- }
- for i in 0..n {
- // SAFETY: the title passes `n` addresses and, unless null, `n` pages.
- let (address, page) = unsafe {
- (
- *addresses.add(i),
- if pages.is_null() || *pages.add(i) == 0 {
- std::ptr::null()
- } else {
- pages.add(i)
- },
- )
- };
- if XMemMapPhysicalPages(address, 1, page).is_null() {
- return 0;
- }
- }
- 1
- }
- /// Maps the physical pages shown at `[from, from + len)` at `to` as well,
- /// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping
- /// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`):
- /// the title maps pages into a pool view, then has the GPU map them into its tiled
- /// heap. Page by page; false if a source page is not mapped physical memory.
- pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
- let (to, from, len) = (to as usize, from as usize, len as usize);
- let mut physical = physical();
- // As in `XMemMapPhysicalPages`: no read in place meets the gap.
- let _changing = victory_gpu::title_memory_remapping();
- unmap(&mut physical, to, len);
- for k in (0..len).step_by(PAGE) {
- if from == 0 {
- break;
- }
- let at = from + k;
- let Some(slice) = physical
- .views
- .range(..=at)
- .next_back()
- .filter(|(base, (size, _))| at < *base + size)
- .map(|(base, (_, s))| Slice {
- index: s.index + (at - base) / PAGE,
- section: s.section.clone(),
- })
- else {
- return false;
- };
- if !map(&mut physical, to + k, PAGE, slice) {
- return false;
- }
- }
- true
- }
- /// Maps `slice` and the slices after it over `[base, base + len)`, which
- /// must lie in one placeholder.
- fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
- // SAFETY: splits the placeholder around the range (failing harmlessly
- // when the range is the whole placeholder), then maps the section
- // there; both act only on placeholders.
- let view = unsafe {
- VirtualFree(
- base as *mut c_void,
- len,
- MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
- );
- MapViewOfFile3(
- slice.section.handle,
- GetCurrentProcess(),
- base as *const c_void,
- (slice.index * PAGE) as u64,
- len,
- MEM_REPLACE_PLACEHOLDER,
- PAGE_READWRITE,
- std::ptr::null_mut(),
- 0,
- )
- };
- if view.Value as usize != base {
- tracing::warn!(
- address = format_args!("{base:#x}"),
- len,
- error = %std::io::Error::last_os_error(),
- "mapping physical pages failed (not a placeholder?)"
- );
- return false;
- }
- if !commit(base, len) {
- // SAFETY: the view just mapped, back to a placeholder.
- unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
- return false;
- }
- // New contents, read-write: the GPU side's copies no longer guard it.
- victory_gpu::title_memory_remapped(base, len);
- // What the range shows now, for the GPU side's in-place census.
- victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64);
- physical.note_view(base, len, &slice);
- physical.views.insert(base, (len, slice));
- true
- }
- /// Commits the section pages a view shows (once per page, whichever view).
- fn commit(base: usize, len: usize) -> bool {
- if on_wine() {
- return true; // sections are committed whole there
- }
- // SAFETY: `[base, base + len)` is a view of a reserved section.
- if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() {
- return true;
- }
- let error = std::io::Error::last_os_error();
- if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) {
- let mut info = PERFORMANCE_INFORMATION {
- cb: size_of::<PERFORMANCE_INFORMATION>() as u32,
- ..Default::default()
- };
- // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION.
- let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0;
- victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info)));
- } else {
- tracing::warn!(len, %error, "committing physical pages failed");
- }
- false
- }
- fn commit_limit_message(
- len: usize,
- error: &std::io::Error,
- info: Option<&PERFORMANCE_INFORMATION>,
- ) -> String {
- let mut message = format!(
- "VIctory: Windows commit limit reached while committing {len} bytes of physical pages: {error}.\n"
- );
- if let Some(info) = info {
- use std::fmt::Write;
- let committed = info.CommitTotal * info.PageSize / MIB;
- let limit = info.CommitLimit * info.PageSize / MIB;
- let _ = writeln!(
- message,
- "System commit: {committed} MiB of {limit} MiB in use."
- );
- }
- message.push_str(
- "Close other applications or increase the Windows paging file size, then retry.\n",
- );
- message
- }
- /// Returns `[base, base + len)` to placeholders; views reaching past it
- /// are mapped again outside it.
- fn unmap(physical: &mut Physical, base: usize, len: usize) {
- // No bytes: no view to return. The search below would still find the
- // view holding `base` and cut it in two there, and its range of views
- // starting inside would run backwards (which `BTreeMap` panics on).
- if len == 0 {
- return;
- }
- let end = base + len;
- // Views do not overlap: the one holding `base`, then those starting
- // inside (the GPU's page mappings make one view per page).
- let first = physical
- .views
- .range(..=base)
- .next_back()
- .filter(|(at, (size, _))| *at + size > base)
- .map(|(at, _)| *at);
- let hit: Vec<usize> = first
- .into_iter()
- .chain(physical.views.range(base + 1..end).map(|(at, _)| *at))
- .collect();
- for at in hit {
- let Some((size, slice)) = physical.views.remove(&at) else {
- continue;
- };
- physical.forget_view(at, size, &slice);
- victory_gpu::title_memory_unmapping(at, size);
- // SAFETY: a view we mapped; it becomes a placeholder again.
- unsafe {
- UnmapViewOfFile2(
- GetCurrentProcess(),
- MEMORY_MAPPED_VIEW_ADDRESS {
- Value: at as *mut c_void,
- },
- MEM_PRESERVE_PLACEHOLDER,
- )
- };
- if at < base {
- map(physical, at, base - at, slice.clone());
- }
- if at + size > end {
- let index = slice.index + (end - at) / PAGE;
- map(physical, end, at + size - end, Slice { index, ..slice });
- }
- }
- }
- /// The oldest layout we know; newer titles pass other flag values (Minecraft
- /// 0x20000001) and read the same leading fields.
- #[repr(C)]
- #[derive(Debug, Default)]
- pub struct WorkingSet {
- pub title_limit: usize,
- pub title_used: usize,
- pub tools_limit: usize,
- pub tools_used: usize,
- pub stack_used: u32,
- pub physical_pages: u32,
- pub gpu_optimal_limit: usize,
- pub gpu_optimal_used: usize,
- pub tools_gpu_optimal_limit: usize,
- pub tools_gpu_optimal_used: usize,
- pub kernel_pool_used: u32,
- pub kernel_pool_limit: u32,
- }
- /// The title's budget and our process's commit as what it uses. No tools
- /// memory: a retail console.
- // shortcut: all fields are filled whatever the flags ask for, and use is
- // not split by bandwidth class (GPU-optimal use reads 0); track
- // allocations per class if a title budgets from that field.
- pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL {
- if out.is_null() {
- return 0;
- }
- let mut counters = PROCESS_MEMORY_COUNTERS {
- cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
- ..Default::default()
- };
- // SAFETY: our own process and a sized structure.
- unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
- let (gpu_optimal, standard) = victory_gpu::console::current().title_memory();
- let stats = WorkingSet {
- title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed),
- title_used: counters.PagefileUsage,
- gpu_optimal_limit: gpu_optimal,
- ..Default::default()
- };
- // What the title is told, logged at the first asking and at every
- // 1,024th: "used" is all the process has committed, the layer's own
- // memory and the card's included (27 GB in run 60's gameplay against a
- // limit of 13.5 GB). A title that budgets its streaming from these two
- // figures believes it is far over its limit.
- // shortcut: the figure is not yet the title's own memory alone (its
- // heaps and the pages it mapped); count those if this line shows the
- // title asking.
- static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
- let asked = ASKED.fetch_add(1, Ordering::Relaxed);
- if asked.is_multiple_of(1024) {
- tracing::info!(
- asked = asked + 1,
- which = _which,
- limit_mb = stats.title_limit >> 20,
- used_mb = stats.title_used >> 20,
- "the title asks how much memory it uses"
- );
- }
- // SAFETY: checked non-null; the title passes room for the structure.
- unsafe { out.write(stats) };
- 1
- }
- /// Hands title memory (standard, in 2 MiB pages) to the system. The other
- /// transfers involve tools memory, which a retail console has none of.
- pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
- const TITLE_TO_SYSTEM: u32 = 0;
- tracing::info!(kind, size, "XMemTransferMemory");
- if size == 0 {
- return 1;
- }
- let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
- return 0;
- };
- let standard = victory_gpu::console::current().title_memory().1;
- let moved = kind == TITLE_TO_SYSTEM
- && TRANSFERRED
- .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
- t.checked_add(size).filter(|&t| t <= standard)
- })
- .is_ok();
- moved.into()
- }
- pub(crate) fn module() -> HleModule {
- HleModule {
- name: "xmem",
- dlls: &["xmem.dll"],
- exports: vec![
- hle_export!(XMemAlloc),
- hle_export!(XMemFree),
- hle_export!(XMemAllocDefault),
- hle_export!(XMemFreeDefault),
- hle_export!(XMemIsToolsMemAvailable),
- hle_export!(XMemAllocatePhysicalPages),
- hle_export!(XMemFreePhysicalPages),
- hle_export!(XMemMapPhysicalPages),
- hle_export!(XMemMapPhysicalPagesScatter),
- hle_export!(XMemVirtualAlloc),
- hle_export!(XMemVirtualQuery),
- hle_export!(XMemGetWorkingSetStatistics),
- hle_export!(XMemTransferMemory),
- ],
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- fn query(address: *const c_void) -> BasicInformation {
- // SAFETY: plain data; zero is a valid value.
- let mut info: BasicInformation = unsafe { std::mem::zeroed() };
- // SAFETY: a pseudo handle needs no closing.
- let process = unsafe { GetCurrentProcess() };
- assert_eq!(XMemVirtualQuery(process, address, &mut info), 1);
- info
- }
- #[test]
- fn alloc_honours_alignment_and_frees() {
- for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] {
- let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type
- let p = XMemAlloc(100, attributes);
- assert!(!p.is_null());
- assert_eq!(p as usize % align, 0, "field {field:#x}");
- // SAFETY: 100 bytes were allocated.
- unsafe { p.cast::<u8>().write_bytes(0xab, 100) };
- XMemFree(p, attributes);
- }
- let p = XMemAlloc(4096, ALLOC_32BIT);
- assert!(!p.is_null() && (p as usize) < 1 << 32);
- XMemFree(p, ALLOC_32BIT);
- }
- #[test]
- fn virtual_alloc_meets_console_constraints() {
- const GPU_READ_WRITE: u32 = 0x2000;
- let p = XMemVirtualAlloc(
- std::ptr::null_mut(),
- 4 * MIB,
- PAGES_2M | MEM_RESERVE | MEM_COMMIT,
- GRAPHICS | 7 << 12, // 40-bit addresses
- PAGE_READWRITE | GPU_READ_WRITE,
- );
- assert!(!p.is_null());
- assert_eq!(p as usize % (2 * MIB), 0);
- assert!((p as usize) < 1 << 40);
- let info = query(p);
- assert_eq!(info.host.State, MEM_COMMIT);
- assert_eq!(info.host.Protect, PAGE_READWRITE);
- assert_eq!(info.flags & GRAPHICS, GRAPHICS);
- // Write-watched, for the GPU side's copies.
- let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0);
- // SAFETY: room for `count` addresses.
- let watched = unsafe {
- windows_sys::Win32::System::Memory::GetWriteWatch(
- 0,
- p,
- 4 * MIB,
- found.as_mut_ptr().cast(),
- &mut count,
- &mut granularity,
- )
- };
- assert_eq!(watched, 0);
- // SAFETY: our own reservation.
- assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
- assert_eq!(query(p).flags, 0);
- // No address field: above the 32-bit range and below 2^40, where
- // the console keeps it.
- let p = XMemVirtualAlloc(
- std::ptr::null_mut(),
- 16 << 30,
- MEM_RESERVE,
- GRAPHICS,
- PAGE_NOACCESS,
- );
- assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}");
- assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}");
- // SAFETY: our own reservation.
- assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
- }
- #[test]
- fn transfers_shrink_the_title_budget() {
- let mut before = WorkingSet::default();
- assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1);
- assert!(before.title_used > 0);
- assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1);
- assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory");
- let standard = victory_gpu::console::current().title_memory().1;
- assert_eq!(XMemTransferMemory(0, standard), 0, "over budget");
- let mut after = WorkingSet::default();
- XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
- assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
- }
- #[test]
- fn statistics_have_the_console_layout() {
- assert_eq!(size_of::<WorkingSet>(), 0x50);
- assert_eq!(size_of::<BasicInformation>(), 0x40);
- assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
- }
- #[test]
- fn commit_limit_report_includes_request_and_system_commit() {
- let error = std::io::Error::from_raw_os_error(ERROR_COMMITMENT_LIMIT as i32);
- let info = PERFORMANCE_INFORMATION {
- CommitTotal: 512,
- CommitLimit: 768,
- PageSize: 4096,
- ..Default::default()
- };
- let report = commit_limit_message(4 * MIB, &error, Some(&info));
- assert!(report.contains("4194304 bytes"));
- assert!(report.contains("2 MiB of 3 MiB in use"));
- let fallback = commit_limit_message(4 * MIB, &error, None);
- for report in [&report, &fallback] {
- assert!(report.contains("os error 1455"));
- assert!(report.contains("Windows paging file size"));
- }
- assert!(!fallback.contains("System commit:"));
- }
- #[test]
- fn physical_pages_map_alias_and_unmap() {
- let mut pages = [0usize; 3];
- let mut n = 3;
- assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
- assert_eq!(n, 3);
- // Packed into 21 bits as `number >> 4`, as the title keeps them.
- for p in pages {
- assert_eq!((p >> 4 & 0x1f_ffff) << 4, p);
- }
- // Reservations of 64 KiB pages, as titles make them for mapping.
- let reserve = || {
- XMemVirtualAlloc(
- std::ptr::null_mut(),
- 3 * PAGE,
- MEM_RESERVE | PAGES_64K,
- 0,
- PAGE_READWRITE,
- )
- };
- let (a, b) = (reserve(), reserve());
- assert!(!a.is_null() && !b.is_null());
- let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE);
- assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
- // The same page at a second address shows the same bytes.
- assert_eq!(
- XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()),
- at(b, 1)
- );
- // SAFETY: both pages are mapped read-write.
- unsafe {
- at(a, 2).cast::<u8>().write(7);
- assert_eq!(at(b, 1).cast::<u8>().read(), 7);
- a.cast::<u8>().write(1);
- }
- // Writes into pages (DirectStorage's) show through their views.
- assert!(write_physical(&pages[2..], 1, &[9]));
- // SAFETY: mapped read-write.
- assert_eq!(unsafe { at(b, 1).cast::<u8>().add(1).read() }, 9);
- // Unmapping the middle page keeps its neighbours.
- assert_eq!(
- XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()),
- at(a, 1)
- );
- assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
- assert_eq!(query(a).host.State, MEM_COMMIT);
- assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT);
- // SAFETY: still mapped.
- assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 7);
- // A scattered page lands in the hole.
- let addresses = [at(a, 1)];
- assert_eq!(
- XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()),
- 1
- );
- // SAFETY: page 0 is now mapped at both `a` and `a + PAGE`.
- assert_eq!(unsafe { at(a, 1).cast::<u8>().read() }, 1);
- // Page number 0 unmaps.
- assert_eq!(
- XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()),
- 1
- );
- assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
- // The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`.
- assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64));
- // SAFETY: mapped read-write.
- assert_eq!(unsafe { b.cast::<u8>().read() }, 7);
- assert!(map_alias(b as u64, 0, PAGE as u64));
- assert_eq!(query(b).host.State, MEM_RESERVE);
- assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64));
- assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
- assert_eq!(XMemIsToolsMemAvailable(), 0);
- }
- /// A thread that reads a mapped page in place, as the GPU side reads a
- /// texture, never meets the moment in which the runtime has taken the
- /// page's view away to map it again: mapping the same pages at the same
- /// address unmaps the view and maps a new one, and without the lock the
- /// reader faults on a page "reserved, never committed" (the crashes of
- /// runs 71 and 74).
- #[test]
- fn a_read_in_place_never_meets_the_gap_of_a_remapping() {
- use std::sync::atomic::{AtomicBool, Ordering};
- let mut pages = [0usize; 3];
- let mut n = 3;
- assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
- let a = XMemVirtualAlloc(
- std::ptr::null_mut(),
- 3 * PAGE,
- MEM_RESERVE | PAGES_64K,
- 0,
- PAGE_READWRITE,
- );
- assert!(!a.is_null());
- assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
- // SAFETY: mapped read-write.
- unsafe { a.cast::<u8>().write(1) };
- let first = a as usize;
- let stop = std::sync::Arc::new(AtomicBool::new(false));
- let reader = {
- let stop = stop.clone();
- std::thread::spawn(move || {
- let mut reads = 0u64;
- while !stop.load(Ordering::Relaxed) {
- let _reading = victory_gpu::title_memory_reading();
- // SAFETY: the page is mapped whenever no change of
- // mapping is under way, and none is while `_reading`
- // is held.
- assert_eq!(unsafe { (first as *const u8).read_volatile() }, 1);
- reads += 1;
- }
- reads
- })
- };
- for _ in 0..2000 {
- // The same pages at the same address: the view goes and comes
- // back, with the same bytes.
- assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
- }
- stop.store(true, Ordering::Relaxed);
- assert!(reader.join().expect("the reader never faulted") > 0);
- assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a);
- assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
- }
- #[test]
- fn mapping_no_pages_changes_nothing() {
- let pages = allocate(2);
- let a = XMemVirtualAlloc(
- std::ptr::null_mut(),
- 2 * PAGE,
- MEM_RESERVE | PAGES_64K,
- 0,
- PAGE_READWRITE,
- );
- assert!(!a.is_null());
- assert_eq!(XMemMapPhysicalPages(a, 2, pages.as_ptr()), a);
- // SAFETY: both pages are mapped read-write.
- unsafe { a.cast::<u8>().write(5) };
- let second = a.wrapping_byte_add(PAGE);
- // A count of 0 at the start of a view, inside it and past it: with
- // pages, without (an unmap), and as the GPU's page-mapping copy.
- for at in [a, second, a.wrapping_byte_add(2 * PAGE)] {
- assert_eq!(XMemMapPhysicalPages(at, 0, pages.as_ptr()), at);
- assert_eq!(XMemMapPhysicalPages(at, 0, std::ptr::null()), at);
- assert!(map_alias(at as u64, a as u64, 0));
- assert!(map_alias(at as u64, 0, 0));
- }
- // The view is still the one view it was.
- let view = physical().views.get(&(a as usize)).map(|v| v.0);
- assert_eq!(view, Some(2 * PAGE));
- assert_eq!(query(a).host.State, MEM_COMMIT);
- assert_eq!(query(second).host.State, MEM_COMMIT);
- // SAFETY: still mapped.
- assert_eq!(unsafe { a.cast::<u8>().read() }, 5);
- // A count of 1 still unmaps that page alone.
- assert_eq!(XMemMapPhysicalPages(second, 1, std::ptr::null()), second);
- assert_eq!(query(second).host.State, MEM_RESERVE);
- assert_eq!(query(a).host.State, MEM_COMMIT);
- assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a);
- assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1);
- }
- /// `n` pages of one new allocation.
- fn allocate(n: usize) -> Vec<usize> {
- let (mut pages, mut given) = (vec![0; n], n);
- assert_eq!(
- XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()),
- 1
- );
- assert_eq!(given, n);
- pages
- }
- /// The bytes of one page, through a view of our own.
- fn page_bytes(page: usize) -> Vec<u8> {
- let slice = physical().pages.get(&page).cloned().expect("known page");
- View::map(&slice, 1).expect("mapped").bytes().to_vec()
- }
- #[test]
- fn runs_group_consecutive_pages_of_one_allocation() {
- let (a, b) = (allocate(3), allocate(1));
- let lengths = |pages: &[usize], offset, len| {
- runs(pages, offset, len).map(|r| r.iter().map(|&(_, n)| n).collect::<Vec<_>>())
- };
- assert_eq!(lengths(&a, 0, 3 * PAGE), Some(vec![3]));
- // Only the pages the bytes reach.
- assert_eq!(lengths(&a, PAGE + 5, 10), Some(vec![1]));
- assert_eq!(lengths(&a, PAGE - 1, 2), Some(vec![2]));
- assert_eq!(lengths(&a, 0, 0), Some(vec![]));
- // Out of order, or across allocations: one run each.
- assert_eq!(
- lengths(&[a[0], a[2], a[1]], 0, 3 * PAGE),
- Some(vec![1, 1, 1])
- );
- assert_eq!(lengths(&[a[1], a[2], b[0]], 0, 3 * PAGE), Some(vec![2, 1]));
- // A slice that follows on in another section starts a run.
- assert_eq!(lengths(&[b[0], a[1]], 0, 2 * PAGE), Some(vec![1, 1]));
- // Too few pages for the bytes, or an unknown one.
- assert_eq!(lengths(&a, 0, 3 * PAGE + 1), None);
- assert_eq!(lengths(&[a[0], 0x10], 0, 2 * PAGE), None);
- assert_eq!(lengths(&a, usize::MAX, 2), None);
- assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1);
- assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
- }
- #[test]
- fn writes_cross_runs_and_allocations() {
- let (a, b) = (allocate(2), allocate(1));
- let pages = [a[0], a[1], b[0]];
- let data: Vec<u8> = (0..2 * PAGE + 64).map(|i| (i * 7 % 251) as u8).collect();
- let offset = PAGE - 32;
- // Past the third page: the second run is too short.
- assert!(!write_physical(&pages, offset, &data));
- assert!(write_physical(&pages, offset, &data[..2 * PAGE]));
- let seen: Vec<u8> = pages.iter().flat_map(|&p| page_bytes(p)).collect();
- assert!(seen[..offset].iter().all(|&b| b == 0), "before the offset");
- assert_eq!(seen[offset..offset + 2 * PAGE], data[..2 * PAGE]);
- assert!(seen[offset + 2 * PAGE..].iter().all(|&b| b == 0), "after");
- assert!(
- !write_physical(&[a[0], 0x10], 0, &data[..PAGE + 1]),
- "unknown page"
- );
- assert_eq!(XMemFreePhysicalPages(2, a.as_ptr()), 1);
- assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
- }
- #[test]
- fn page_windows_cover_one_run_in_place() {
- let (a, b) = (allocate(3), allocate(1));
- let mut window = page_window(&a, PAGE + 3, PAGE).expect("one run");
- assert_eq!(window.bytes().len(), PAGE);
- window.bytes().fill(0x5a);
- drop(window);
- let (second, third) = (page_bytes(a[1]), page_bytes(a[2]));
- assert!(second[..3].iter().all(|&b| b == 0));
- assert!(second[3..].iter().all(|&b| b == 0x5a));
- assert!(third[..3].iter().all(|&b| b == 0x5a));
- assert!(third[3..].iter().all(|&b| b == 0));
- // Several runs, or an unknown page: no window.
- assert!(page_window(&[a[0], b[0]], 0, PAGE + 1).is_none());
- assert!(page_window(&[a[1], a[0]], 0, PAGE + 1).is_none());
- assert!(page_window(&[0x10], 0, 1).is_none());
- // One page of several is still one run.
- assert!(page_window(&[a[0], b[0]], 0, PAGE).is_some());
- assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1);
- assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
- }
- }
|