xmem.rs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. //! `xmem.dll`: console memory, served from host memory. The GPU side works
  2. //! from CPU addresses (unified memory), so memory types and bandwidth
  3. //! classes change nothing here; what constrains addresses (alignment,
  4. //! 2 MiB pages, address-bit limits) is honoured.
  5. #![allow(non_snake_case)]
  6. // Title code calls these through its import table, passing pointers the real
  7. // API would trust.
  8. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  9. use std::alloc::{Layout, alloc, dealloc};
  10. use std::collections::{BTreeMap, HashMap};
  11. use std::ffi::c_void;
  12. use std::sync::atomic::{AtomicUsize, Ordering};
  13. use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
  14. use windows_sys::Win32::Foundation::{
  15. CloseHandle, ERROR_COMMITMENT_LIMIT, HANDLE, INVALID_HANDLE_VALUE,
  16. };
  17. use windows_sys::Win32::System::Memory::{
  18. CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER,
  19. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE,
  20. MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3,
  21. MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_COMMIT,
  22. SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx,
  23. };
  24. use windows_sys::Win32::System::ProcessStatus::{
  25. K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION,
  26. PROCESS_MEMORY_COUNTERS,
  27. };
  28. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  29. use windows_sys::core::BOOL;
  30. use crate::{HleModule, hle_export};
  31. const MIB: usize = 1 << 20;
  32. /// Whether we run under Wine (its ntdll exports `wine_get_version`).
  33. pub(crate) fn on_wine() -> bool {
  34. static WINE: LazyLock<bool> = LazyLock::new(|| {
  35. use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress};
  36. // SAFETY: plain lookups in ntdll, always loaded.
  37. unsafe {
  38. let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast());
  39. !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some()
  40. }
  41. });
  42. *WINE
  43. }
  44. /// Standard memory the title has handed to the system.
  45. static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
  46. // Console additions to the host's flags.
  47. /// 2 MiB pages; the host reads this bit as large pages, which need a
  48. /// privilege.
  49. const PAGES_2M: u32 = 0x2000_0000;
  50. /// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory.
  51. const PAGES_64K_BIT: u32 = 0x40_0000;
  52. const PAGES_64K: u32 = PAGES_2M | PAGES_64K_BIT;
  53. /// The host's protection constants and `PAGE_GUARD`. Above them the console
  54. /// adds GPU access bits (0x800-0x40000). Write-combining and uncached are
  55. /// dropped too: our GPU side reads this memory through the CPU.
  56. const HOST_PROTECTION: u32 = 0x1ff;
  57. /// XMem flags of memory both processors reach: all of ours.
  58. const GRAPHICS: u64 = 3;
  59. /// XMem flag bit of 32-bit graphics memory.
  60. const ADDRESS_32BIT: u64 = 4;
  61. /// The host's write watching (not in windows-sys' memory module).
  62. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  63. /// The addresses XMem `flags` allow, first and last: the low 4 GiB for
  64. /// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the
  65. /// title's big pools would otherwise crowd out) up to 46 down to 40 bits
  66. /// from the field at bit 12, or 40 bits without one: the console keeps
  67. /// title memory there, and its ray-tracing structures must be (
  68. /// the title's BVH builder refuses one above; the title asks for its GPU heap
  69. /// with no field). Decision 0001.
  70. fn address_range(flags: u64) -> (usize, usize) {
  71. let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) {
  72. (0, 0) => 40,
  73. (0, field) => 47 - field,
  74. _ => return (0, u32::MAX as usize),
  75. };
  76. (1 << 32, (1 << bits) - 1)
  77. }
  78. pub extern "system" fn XMemVirtualAlloc(
  79. base: *mut c_void,
  80. size: usize,
  81. kind: u32,
  82. flags: u64,
  83. protect: u32,
  84. ) -> *mut c_void {
  85. let (lowest, highest) = address_range(flags);
  86. let mut requirements = MEM_ADDRESS_REQUIREMENTS {
  87. LowestStartingAddress: lowest as *mut c_void,
  88. HighestEndingAddress: highest as *mut c_void,
  89. Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M {
  90. 2 * MIB
  91. } else {
  92. 0
  93. },
  94. };
  95. let mut protect = match protect & HOST_PROTECTION {
  96. 0 => PAGE_NOACCESS,
  97. p => p,
  98. };
  99. // A reservation of 64 KiB pages takes physical pages later
  100. // (`XMemMapPhysicalPages`); on the host only a placeholder can.
  101. // shortcut: committing part of such a reservation later would fail
  102. // (the title's 23 calls never do); replace that part of the
  103. // placeholder then.
  104. let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0;
  105. if placeholder {
  106. if kind & MEM_REPLACE_PLACEHOLDER != 0 {
  107. // Part of a placeholder the title split: it stays one.
  108. return base;
  109. }
  110. protect = PAGE_NOACCESS;
  111. }
  112. let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
  113. if placeholder {
  114. kind |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER;
  115. }
  116. let mut parameter = MEM_EXTENDED_PARAMETER::default();
  117. parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
  118. parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
  119. // Address requirements apply to reservations at an address of our choice.
  120. let constrained = base.is_null();
  121. if constrained {
  122. kind |= MEM_RESERVE;
  123. // The GPU side copies only the pages the title wrote since its last
  124. // copy (`victory_gpu`, decision 0007); placeholders cannot be
  125. // watched (their physical-page views are copied whole).
  126. if kind & MEM_RESERVE_PLACEHOLDER == 0 {
  127. kind |= MEM_WRITE_WATCH;
  128. }
  129. }
  130. // SAFETY: the title's own arguments, cleaned of console bits; the
  131. // parameter points at `requirements`, which outlives the call.
  132. let at = unsafe {
  133. VirtualAlloc2(
  134. GetCurrentProcess(),
  135. base,
  136. size,
  137. kind,
  138. protect,
  139. if constrained {
  140. &mut parameter
  141. } else {
  142. std::ptr::null_mut()
  143. },
  144. constrained.into(),
  145. )
  146. };
  147. if base.is_null() {
  148. tracing::debug!(
  149. size,
  150. kind = format_args!("{kind:#x}"),
  151. flags = format_args!("{flags:#x}"),
  152. at = format_args!("{at:p}"),
  153. "XMemVirtualAlloc"
  154. );
  155. }
  156. if !at.is_null() && !placeholder {
  157. victory_gpu::title_memory_allocated(at as usize, size);
  158. }
  159. at
  160. }
  161. /// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
  162. /// same), then the XMem flags and tag.
  163. #[repr(C)]
  164. pub struct BasicInformation {
  165. host: MEMORY_BASIC_INFORMATION,
  166. flags: u64,
  167. tag_code: u32,
  168. tag: [u8; 4],
  169. }
  170. // shortcut: every committed page reports graphics memory and no tag, since
  171. // all of it is GPU-reachable here (the title's BVH builder, the
  172. // only caller, wants graphics memory); remember the flags of
  173. // `XMemVirtualAlloc` regions if a title tells CPU-only memory apart.
  174. pub extern "system" fn XMemVirtualQuery(
  175. process: HANDLE,
  176. address: *const c_void,
  177. out: *mut BasicInformation,
  178. ) -> BOOL {
  179. let size = size_of::<MEMORY_BASIC_INFORMATION>();
  180. // SAFETY: the title passes room for the whole structure; the host
  181. // fails on a null one.
  182. unsafe {
  183. if VirtualQueryEx(process, address, out.cast(), size) == 0 {
  184. return 0;
  185. }
  186. let info = &mut *out;
  187. info.flags = if info.host.State == MEM_COMMIT {
  188. GRAPHICS
  189. } else {
  190. 0
  191. };
  192. info.tag_code = 0;
  193. info.tag = [0; 4];
  194. }
  195. 1
  196. }
  197. // `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up
  198. // from 2), then the memory type, then bit 33: a 32-bit address.
  199. const ALIGNMENT_SHIFT: u64 = 24;
  200. const ALLOC_32BIT: u64 = 1 << 33;
  201. /// Our block header: the block's size and alignment, just below the
  202. /// pointer handed out.
  203. const HEADER: usize = 2 * size_of::<usize>();
  204. fn layout(size: usize, attributes: u64) -> Option<Layout> {
  205. // An alignment of at least 16 leaves room for the header.
  206. let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4);
  207. Layout::from_size_align(size.checked_add(align)?, align).ok()
  208. }
  209. type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
  210. type FreeRoutine = extern "system" fn(*mut c_void, u64);
  211. /// The allocation and free routines the title's exe exports as
  212. /// `__XMemAllocationHooks__` (the title does): `XMemAlloc` and
  213. /// `XMemFree` call them, for the title's own calls and its middleware's;
  214. /// the `…Default` exports do not.
  215. fn hooks() -> [usize; 2] {
  216. static AT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
  217. let at = match AT.get() {
  218. Some(&at) => at,
  219. // Looked up once the title is mapped, which is before it runs.
  220. None => match crate::runtime::main_image() {
  221. Some(base) => *AT.get_or_init(|| {
  222. use windows_sys::Win32::System::LibraryLoader::GetProcAddress;
  223. // SAFETY: a mapped image and a NUL-terminated name.
  224. let at = unsafe {
  225. GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast())
  226. }
  227. .map_or(0, |f| f as usize);
  228. tracing::info!(found = at != 0, "xmem allocation hooks");
  229. at
  230. }),
  231. None => 0,
  232. },
  233. };
  234. if at == 0 {
  235. return [0; 2];
  236. }
  237. // SAFETY: the export is two routine pointers.
  238. unsafe { (at as *const [usize; 2]).read() }
  239. }
  240. /// The title's general allocator, for middleware too: its hook if it has
  241. /// one, else [`XMemAllocDefault`].
  242. pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
  243. match hooks()[0] {
  244. 0 => XMemAllocDefault(size, attributes),
  245. hook => {
  246. // SAFETY: the title's own routine of this type.
  247. let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) };
  248. alloc(size, attributes)
  249. }
  250. }
  251. }
  252. /// See [`XMemAlloc`].
  253. pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
  254. match hooks()[1] {
  255. 0 => XMemFreeDefault(address, attributes),
  256. hook => {
  257. // SAFETY: the title's own routine of this type.
  258. let free: FreeRoutine = unsafe { std::mem::transmute(hook) };
  259. free(address, attributes)
  260. }
  261. }
  262. }
  263. /// The system allocator behind [`XMemAlloc`].
  264. pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void {
  265. if attributes & ALLOC_32BIT != 0 {
  266. return XMemVirtualAlloc(
  267. std::ptr::null_mut(),
  268. size,
  269. MEM_RESERVE | MEM_COMMIT,
  270. GRAPHICS | ADDRESS_32BIT,
  271. PAGE_READWRITE,
  272. );
  273. }
  274. let Some(layout) = layout(size, attributes) else {
  275. return std::ptr::null_mut();
  276. };
  277. // shortcut: the host heap's addresses lie above 2^40, unlike the
  278. // console's; nothing seen builds ray-tracing structures in this memory
  279. // (the title uses its GPU heap). Sub-allocate from a
  280. // reservation below 2^40 if one does.
  281. // SAFETY: the layout has a non-zero size.
  282. let block = unsafe { alloc(layout) };
  283. if block.is_null() {
  284. return block.cast();
  285. }
  286. // SAFETY: the block holds the alignment (at least the header) and then
  287. // `size` bytes.
  288. unsafe {
  289. let user = block.add(layout.align());
  290. user.sub(HEADER)
  291. .cast::<[usize; 2]>()
  292. .write([layout.size(), layout.align()]);
  293. user.cast()
  294. }
  295. }
  296. /// Frees what [`XMemAllocDefault`] returned, given the same attributes.
  297. pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
  298. if address.is_null() {
  299. return;
  300. }
  301. // SAFETY: the address came from `XMemAlloc` with these attributes: a
  302. // whole reservation, or a header-prefixed block.
  303. unsafe {
  304. if attributes & ALLOC_32BIT != 0 {
  305. VirtualFree(address, 0, MEM_RELEASE);
  306. return;
  307. }
  308. let user = address.cast::<u8>();
  309. let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read();
  310. dealloc(
  311. user.sub(align),
  312. Layout::from_size_align_unchecked(size, align),
  313. );
  314. }
  315. }
  316. /// A retail console has no tools memory.
  317. pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL {
  318. 0
  319. }
  320. // Physical pages: on the console, 64 KiB frames a title maps into its own
  321. // reservations, at more than one address if it likes. Here each allocation
  322. // is a pagefile-backed section, its pages are 64 KiB slices of it, and a
  323. // mapping is a view of consecutive slices in place of a host placeholder.
  324. const PAGE: usize = 64 << 10;
  325. struct Section {
  326. handle: HANDLE,
  327. pages: usize,
  328. /// A view of the whole section, kept ([`Section::window`]); 0 if the
  329. /// host gave none.
  330. window: std::sync::OnceLock<usize>,
  331. /// A bit per page: committed, as far as [`Section::window`] asked.
  332. committed: Box<[std::sync::atomic::AtomicU64]>,
  333. }
  334. impl Section {
  335. /// Where bytes of `n` pages from page `index` on can be written,
  336. /// whether or not the pages are mapped anywhere, committed.
  337. ///
  338. /// Every DirectStorage write mapped a view of its pages, committed it,
  339. /// faulted each of its 4 KiB pages in and unmapped it again, all of it
  340. /// under the process's one address-space lock, with 24 workers, the
  341. /// title's own mapping calls (about 100,000 views of one page) and our
  342. /// guards asking for the same lock. One view of the section, kept,
  343. /// costs that once per page.
  344. /// `VICTORY_SECTION_WINDOW=0`: a view for each write, as before.
  345. fn window(&self, index: usize, n: usize) -> Option<usize> {
  346. use std::sync::atomic::Ordering;
  347. use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile};
  348. static ON: LazyLock<bool> =
  349. LazyLock::new(|| std::env::var_os("VICTORY_SECTION_WINDOW").is_none_or(|v| v != "0"));
  350. if !*ON || index + n > self.pages {
  351. return None;
  352. }
  353. let base = *self.window.get_or_init(|| {
  354. // SAFETY: the whole of a section we own.
  355. unsafe { MapViewOfFile(self.handle, FILE_MAP_WRITE, 0, 0, self.pages * PAGE) }.Value as usize
  356. });
  357. if base == 0 {
  358. return None;
  359. }
  360. let missing = |page: usize| self.committed[page / 64].load(Ordering::Acquire) >> (page % 64) & 1 == 0;
  361. let mut page = index;
  362. while page < index + n {
  363. if !missing(page) {
  364. page += 1;
  365. continue;
  366. }
  367. let run = (page..index + n).take_while(|&p| missing(p)).count();
  368. if run == 0 {
  369. continue; // another worker committed it meanwhile
  370. }
  371. if !commit(base + page * PAGE, run * PAGE) {
  372. return None;
  373. }
  374. for p in page..page + run {
  375. self.committed[p / 64].fetch_or(1 << (p % 64), Ordering::AcqRel);
  376. }
  377. page += run;
  378. }
  379. Some(base + index * PAGE)
  380. }
  381. }
  382. // SAFETY: a section handle may be used from any thread.
  383. unsafe impl Send for Section {}
  384. // SAFETY: as above.
  385. unsafe impl Sync for Section {}
  386. impl Drop for Section {
  387. fn drop(&mut self) {
  388. use windows_sys::Win32::System::Memory::UnmapViewOfFile;
  389. if let Some(&base) = self.window.get()
  390. && base != 0
  391. {
  392. // SAFETY: our view; whoever writes through it holds the section.
  393. unsafe {
  394. UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
  395. Value: base as *mut c_void,
  396. })
  397. };
  398. }
  399. victory_gpu::title_memory_section_gone(self.handle as usize);
  400. // SAFETY: our handle; views keep the section alive on their own.
  401. unsafe { CloseHandle(self.handle) };
  402. }
  403. }
  404. /// Where a page lives, or what a view starts with: a section and a page
  405. /// index in it.
  406. #[derive(Clone)]
  407. struct Slice {
  408. section: Arc<Section>,
  409. index: usize,
  410. }
  411. #[derive(Default)]
  412. struct Physical {
  413. next_page: usize,
  414. pages: HashMap<usize, Slice>,
  415. /// Mapped views by address: their length and what they show.
  416. views: BTreeMap<usize, (usize, Slice)>,
  417. /// The other way: the views (by address) that show a page, by the page's
  418. /// section and index. Views of more than [`SHORT`] pages are in `long`.
  419. shown: HashMap<(usize, usize), Vec<usize>>,
  420. long: Vec<usize>,
  421. }
  422. /// Pages of a view noted page by page in [`Physical::shown`].
  423. const SHORT: usize = 64;
  424. impl Physical {
  425. fn note_view(&mut self, base: usize, len: usize, slice: &Slice) {
  426. if len / PAGE > SHORT {
  427. self.long.push(base);
  428. return;
  429. }
  430. let section = Arc::as_ptr(&slice.section) as usize;
  431. for k in 0..len / PAGE {
  432. self.shown.entry((section, slice.index + k)).or_default().push(base);
  433. }
  434. }
  435. fn forget_view(&mut self, base: usize, len: usize, slice: &Slice) {
  436. if len / PAGE > SHORT {
  437. self.long.retain(|&b| b != base);
  438. return;
  439. }
  440. let section = Arc::as_ptr(&slice.section) as usize;
  441. for k in 0..len / PAGE {
  442. let key = (section, slice.index + k);
  443. if let Some(views) = self.shown.get_mut(&key) {
  444. views.retain(|&b| b != base);
  445. if views.is_empty() {
  446. self.shown.remove(&key);
  447. }
  448. }
  449. }
  450. }
  451. /// Where the title sees `n` pages from `slice` on: addresses and bytes.
  452. fn shown_at(&self, slice: &Slice, n: usize) -> Vec<(usize, usize)> {
  453. let section = Arc::as_ptr(&slice.section) as usize;
  454. let mut out: Vec<(usize, usize)> = Vec::new();
  455. for k in 0..n {
  456. for &base in self.shown.get(&(section, slice.index + k)).into_iter().flatten() {
  457. if let Some((_, s)) = self.views.get(&base) {
  458. out.push((base + (slice.index + k - s.index) * PAGE, PAGE));
  459. }
  460. }
  461. }
  462. for &base in &self.long {
  463. let Some((len, s)) = self.views.get(&base) else { continue };
  464. let from = slice.index.max(s.index);
  465. let to = (slice.index + n).min(s.index + len / PAGE);
  466. if Arc::as_ptr(&s.section) as usize == section && from < to {
  467. out.push((base + (from - s.index) * PAGE, (to - from) * PAGE));
  468. }
  469. }
  470. out
  471. }
  472. }
  473. /// DirectStorage has put bytes `[offset, offset + len)` of `pages` into
  474. /// memory: the GPU side is told where the title sees them, so that what it
  475. /// copied there before they arrived (a texture uploaded when its view was
  476. /// written holds whatever the pages held then) is copied again.
  477. /// `VICTORY_STREAM_NOTICE=0`: not told, as before.
  478. pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) {
  479. if !stream_notice() || len == 0 {
  480. return;
  481. }
  482. let mut seen: Vec<(usize, usize)> = {
  483. let physical = physical();
  484. let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default();
  485. numbers
  486. .iter()
  487. .filter_map(|n| physical.pages.get(n))
  488. .flat_map(|slice| physical.shown_at(slice, 1))
  489. .collect()
  490. };
  491. seen.sort_unstable();
  492. let mut runs: Vec<(usize, usize)> = Vec::new();
  493. for (at, len) in seen {
  494. match runs.last_mut() {
  495. Some(last) if last.0 + last.1 == at => last.1 += len,
  496. _ => runs.push((at, len)),
  497. }
  498. }
  499. for (at, len) in runs {
  500. victory_gpu::kernel_will_write(at, len);
  501. }
  502. }
  503. /// See [`pages_written`].
  504. pub(crate) fn stream_notice() -> bool {
  505. static ON: LazyLock<bool> =
  506. LazyLock::new(|| std::env::var_os("VICTORY_STREAM_NOTICE").is_none_or(|v| v != "0"));
  507. *ON
  508. }
  509. static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| {
  510. Mutex::new(Physical {
  511. // Page numbers are opaque to titles; 0 stays unused.
  512. next_page: 0x10_0000,
  513. ..Default::default()
  514. })
  515. });
  516. fn physical() -> MutexGuard<'static, Physical> {
  517. PHYSICAL.lock().unwrap_or_else(|e| e.into_inner())
  518. }
  519. /// `count` is in and out (pages wanted, pages given); all or nothing here.
  520. pub extern "system" fn XMemAllocatePhysicalPages(
  521. flags: u64,
  522. count: *mut usize,
  523. pages: *mut usize,
  524. ) -> BOOL {
  525. if count.is_null() || pages.is_null() {
  526. return 0;
  527. }
  528. // SAFETY: checked non-null.
  529. let n = unsafe { *count };
  530. let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else {
  531. return 0;
  532. };
  533. // A pagefile-backed section of `size` bytes, its pages committed when
  534. // first mapped or written (`commit`): the title asks for 6.1
  535. // GiB at once, which a busy host often cannot commit (error 1450).
  536. // SAFETY: plain section creation.
  537. let handle = unsafe {
  538. CreateFileMappingW(
  539. INVALID_HANDLE_VALUE,
  540. std::ptr::null(),
  541. // Under Wine a committed section is a sparse file, free until
  542. // touched, and committing a reserved one page by page costs a
  543. // wineserver request each that scans every range committed so
  544. // far: commit it whole there.
  545. PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE },
  546. (size as u64 >> 32) as u32,
  547. size as u32,
  548. std::ptr::null(),
  549. )
  550. };
  551. if handle.is_null() {
  552. let error = std::io::Error::last_os_error();
  553. tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed");
  554. // SAFETY: checked non-null.
  555. unsafe { count.write(0) };
  556. return 0;
  557. }
  558. tracing::debug!(
  559. n,
  560. flags = format_args!("{flags:#x}"),
  561. "XMemAllocatePhysicalPages"
  562. );
  563. // For the GPU side's in-place census: only a committed section can be
  564. // opened as a host heap.
  565. victory_gpu::title_memory_section(handle as usize, size as u64, on_wine());
  566. let section = Arc::new(Section {
  567. handle,
  568. pages: n,
  569. window: std::sync::OnceLock::new(),
  570. committed: (0..n.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(),
  571. });
  572. let mut physical = physical();
  573. let first = physical.next_page;
  574. physical.next_page += n * FRAMES;
  575. for index in 0..n {
  576. let slice = Slice {
  577. section: section.clone(),
  578. index,
  579. };
  580. let number = first + index * FRAMES;
  581. physical.pages.insert(number, slice);
  582. // SAFETY: the title passes room for `n` page numbers.
  583. unsafe { pages.add(index).write(number) };
  584. }
  585. 1
  586. }
  587. /// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of
  588. /// 16: the title keeps them as 21-bit `number >> 4` and rebuilds
  589. /// them with `<< 4` (128 GiB of pages at most).
  590. const FRAMES: usize = PAGE >> 12;
  591. /// Pages still mapped stay readable through their views until unmapped.
  592. pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL {
  593. if pages.is_null() {
  594. return 0;
  595. }
  596. let mut physical = physical();
  597. for i in 0..n {
  598. // SAFETY: the title passes `n` page numbers.
  599. physical.pages.remove(&unsafe { *pages.add(i) });
  600. }
  601. 1
  602. }
  603. /// A view of our own on consecutive slices of one section, committed and
  604. /// writable, unmapped when dropped.
  605. struct View {
  606. at: MEMORY_MAPPED_VIEW_ADDRESS,
  607. len: usize,
  608. }
  609. impl View {
  610. /// Maps `n` slices from `slice` on.
  611. fn map(slice: &Slice, n: usize) -> Option<View> {
  612. use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile};
  613. let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE);
  614. // SAFETY: slices of a section we own; the view is ours until dropped.
  615. let at = unsafe {
  616. MapViewOfFile(
  617. slice.section.handle,
  618. FILE_MAP_WRITE,
  619. (offset >> 32) as u32,
  620. offset as u32,
  621. len,
  622. )
  623. };
  624. if at.Value.is_null() {
  625. tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not mapped for a write");
  626. return None;
  627. }
  628. let view = View { at, len };
  629. if !commit(at.Value as usize, len) {
  630. tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not committed for a write");
  631. return None;
  632. }
  633. Some(view)
  634. }
  635. fn bytes(&mut self) -> &mut [u8] {
  636. // SAFETY: the view holds `len` committed read-write bytes, ours
  637. // alone while `self` lives (other views of the slices only alias
  638. // them, as the console's do).
  639. unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) }
  640. }
  641. }
  642. impl Drop for View {
  643. fn drop(&mut self) {
  644. use windows_sys::Win32::System::Memory::UnmapViewOfFile;
  645. // SAFETY: our view.
  646. unsafe { UnmapViewOfFile(self.at) };
  647. }
  648. }
  649. /// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB
  650. /// each), as runs of consecutive slices of one section: each run's first
  651. /// slice and its length in pages. One look at the page table, which the
  652. /// title's own mapping calls share with every DirectStorage worker. `None`
  653. /// if a page is unknown or `pages` ends early.
  654. fn runs(pages: &[usize], offset: usize, len: usize) -> Option<Vec<(Slice, usize)>> {
  655. let end = offset.checked_add(len)?;
  656. let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?;
  657. let physical = physical();
  658. let mut runs: Vec<(Slice, usize)> = Vec::new();
  659. for page in pages {
  660. let Some(slice) = physical.pages.get(page) else {
  661. tracing::warn!(page, offset, len, "a physical page the title does not own (any more)");
  662. return None;
  663. };
  664. match runs.last_mut() {
  665. Some((first, n))
  666. if Arc::ptr_eq(&first.section, &slice.section)
  667. && slice.index == first.index + *n =>
  668. {
  669. *n += 1;
  670. }
  671. _ => runs.push((slice.clone(), 1)),
  672. }
  673. }
  674. Some(runs)
  675. }
  676. /// Whether the title owns every page under bytes `[offset, offset + len)`.
  677. pub(crate) fn pages_known(pages: &[usize], offset: usize, len: usize) -> bool {
  678. let physical = physical();
  679. pages
  680. .get(offset / PAGE..(offset + len).div_ceil(PAGE))
  681. .is_some_and(|pages| pages.iter().all(|page| physical.pages.contains_key(page)))
  682. }
  683. /// Where the title sees the pages under bytes `[offset, offset + len)` now,
  684. /// in order (for the streaming trace: whether that changed while a request
  685. /// wrote them).
  686. pub(crate) fn pages_shown(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> {
  687. let physical = physical();
  688. let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default();
  689. let mut shown: Vec<(usize, usize)> = numbers
  690. .iter()
  691. .filter_map(|n| physical.pages.get(n))
  692. .flat_map(|slice| physical.shown_at(slice, 1))
  693. .collect();
  694. shown.sort_unstable();
  695. shown
  696. }
  697. /// Copies `data` into physical pages, from `offset` bytes into the first,
  698. /// whether or not they are mapped anywhere (DirectStorage destinations).
  699. /// One view per run of consecutive pages, not one per page: each view
  700. /// costs a map, a commit and an unmap (which flushes every core's TLB).
  701. /// False if a page is unknown or the host fails.
  702. pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool {
  703. let Some(runs) = runs(pages, offset, data.len()) else {
  704. return false;
  705. };
  706. let (mut within, mut done) = (offset % PAGE, 0);
  707. for (slice, n) in &runs {
  708. let k = (n * PAGE - within).min(data.len() - done);
  709. if let Some(at) = slice.section.window(slice.index, *n) {
  710. // SAFETY: committed bytes of the section's view, which `runs`
  711. // holds; the title's other uses of them race as on the console.
  712. unsafe { std::ptr::copy_nonoverlapping(data[done..].as_ptr(), (at + within) as *mut u8, k) };
  713. } else {
  714. let Some(mut view) = View::map(slice, *n) else {
  715. return false;
  716. };
  717. view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]);
  718. }
  719. (within, done) = (0, done + k);
  720. }
  721. true
  722. }
  723. /// Bytes `[offset, offset + len)` of physical pages, writable in place
  724. /// until dropped: DirectStorage decodes into it instead of a buffer it
  725. /// would then copy.
  726. pub(crate) struct PageWindow {
  727. view: Window,
  728. within: usize,
  729. len: usize,
  730. }
  731. enum Window {
  732. /// In the section's own view, which the section holds.
  733. Kept(usize, #[expect(dead_code, reason = "held for the view")] Arc<Section>),
  734. Own(View),
  735. }
  736. impl PageWindow {
  737. pub(crate) fn bytes(&mut self) -> &mut [u8] {
  738. let (within, len) = (self.within, self.len);
  739. match &mut self.view {
  740. // SAFETY: committed bytes of the section's view, ours alone as
  741. // far as the runtime goes (other views alias them, as the
  742. // console's do).
  743. Window::Kept(at, _) => unsafe { std::slice::from_raw_parts_mut((*at + within) as *mut u8, len) },
  744. Window::Own(view) => &mut view.bytes()[within..within + len],
  745. }
  746. }
  747. }
  748. /// A window on bytes `[offset, offset + len)` of `pages` when they are
  749. /// consecutive pages of one allocation (how titles usually hand them out);
  750. /// `None` otherwise (pages of several allocations, out of order, or
  751. /// unknown, or a host failure), which `write_physical` then handles or
  752. /// reports.
  753. pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option<PageWindow> {
  754. let runs = runs(pages, offset, len)?;
  755. let [(slice, n)] = runs.as_slice() else {
  756. return None;
  757. };
  758. let view = match slice.section.window(slice.index, *n) {
  759. Some(at) => Window::Kept(at, slice.section.clone()),
  760. None => Window::Own(View::map(slice, *n)?),
  761. };
  762. Some(PageWindow {
  763. view,
  764. within: offset % PAGE,
  765. len,
  766. })
  767. }
  768. /// Maps `n` pages at `address`, in place of what is mapped there; null
  769. /// `pages` unmaps. Returns `address`, or null if a page or the host fails.
  770. pub extern "system" fn XMemMapPhysicalPages(
  771. address: *mut c_void,
  772. n: usize,
  773. pages: *const usize,
  774. ) -> *mut c_void {
  775. let base = address as usize;
  776. let mut physical = physical();
  777. // Until the pages are mapped again: `unmap` takes whole views away and
  778. // maps what stays of them again, and a mapped view is a reservation
  779. // until it is committed. A read of title memory in place must not fall
  780. // into that gap (`victory_gpu::title_memory_remapping`).
  781. let _changing = victory_gpu::title_memory_remapping();
  782. unmap(&mut physical, base, n * PAGE);
  783. if pages.is_null() {
  784. return address;
  785. }
  786. // SAFETY: the title passes `n` page numbers.
  787. let pages = unsafe { std::slice::from_raw_parts(pages, n) };
  788. let mut i = 0;
  789. while i < n {
  790. let Some(first) = physical.pages.get(&pages[i]).cloned() else {
  791. tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page");
  792. return std::ptr::null_mut();
  793. };
  794. // One view per run of consecutive slices of one section.
  795. let run = 1 + pages[i + 1..]
  796. .iter()
  797. .zip(1..)
  798. .take_while(|&(page, k)| {
  799. physical.pages.get(page).is_some_and(|s| {
  800. Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k
  801. })
  802. })
  803. .count();
  804. if !map(&mut physical, base + i * PAGE, run * PAGE, first) {
  805. return std::ptr::null_mut();
  806. }
  807. i += run;
  808. }
  809. address
  810. }
  811. /// One page at each address; null `pages`, or a page number 0, unmaps
  812. /// (the title passes 0 for addresses to clear).
  813. pub extern "system" fn XMemMapPhysicalPagesScatter(
  814. addresses: *const *mut c_void,
  815. n: usize,
  816. pages: *const usize,
  817. ) -> BOOL {
  818. if addresses.is_null() {
  819. return 0;
  820. }
  821. for i in 0..n {
  822. // SAFETY: the title passes `n` addresses and, unless null, `n` pages.
  823. let (address, page) = unsafe {
  824. (
  825. *addresses.add(i),
  826. if pages.is_null() || *pages.add(i) == 0 {
  827. std::ptr::null()
  828. } else {
  829. pages.add(i)
  830. },
  831. )
  832. };
  833. if XMemMapPhysicalPages(address, 1, page).is_null() {
  834. return 0;
  835. }
  836. }
  837. 1
  838. }
  839. /// Maps the physical pages shown at `[from, from + len)` at `to` as well,
  840. /// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping
  841. /// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`):
  842. /// the title maps pages into a pool view, then has the GPU map them into its tiled
  843. /// heap. Page by page; false if a source page is not mapped physical memory.
  844. pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
  845. let (to, from, len) = (to as usize, from as usize, len as usize);
  846. let mut physical = physical();
  847. // As in `XMemMapPhysicalPages`: no read in place meets the gap.
  848. let _changing = victory_gpu::title_memory_remapping();
  849. unmap(&mut physical, to, len);
  850. for k in (0..len).step_by(PAGE) {
  851. if from == 0 {
  852. break;
  853. }
  854. let at = from + k;
  855. let Some(slice) = physical
  856. .views
  857. .range(..=at)
  858. .next_back()
  859. .filter(|(base, (size, _))| at < *base + size)
  860. .map(|(base, (_, s))| Slice {
  861. index: s.index + (at - base) / PAGE,
  862. section: s.section.clone(),
  863. })
  864. else {
  865. return false;
  866. };
  867. if !map(&mut physical, to + k, PAGE, slice) {
  868. return false;
  869. }
  870. }
  871. true
  872. }
  873. /// Maps `slice` and the slices after it over `[base, base + len)`, which
  874. /// must lie in one placeholder.
  875. fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
  876. // SAFETY: splits the placeholder around the range (failing harmlessly
  877. // when the range is the whole placeholder), then maps the section
  878. // there; both act only on placeholders.
  879. let view = unsafe {
  880. VirtualFree(
  881. base as *mut c_void,
  882. len,
  883. MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
  884. );
  885. MapViewOfFile3(
  886. slice.section.handle,
  887. GetCurrentProcess(),
  888. base as *const c_void,
  889. (slice.index * PAGE) as u64,
  890. len,
  891. MEM_REPLACE_PLACEHOLDER,
  892. PAGE_READWRITE,
  893. std::ptr::null_mut(),
  894. 0,
  895. )
  896. };
  897. if view.Value as usize != base {
  898. tracing::warn!(
  899. address = format_args!("{base:#x}"),
  900. len,
  901. error = %std::io::Error::last_os_error(),
  902. "mapping physical pages failed (not a placeholder?)"
  903. );
  904. return false;
  905. }
  906. if !commit(base, len) {
  907. // SAFETY: the view just mapped, back to a placeholder.
  908. unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
  909. return false;
  910. }
  911. // New contents, read-write: the GPU side's copies no longer guard it.
  912. victory_gpu::title_memory_remapped(base, len);
  913. // What the range shows now, for the GPU side's in-place census.
  914. victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64);
  915. physical.note_view(base, len, &slice);
  916. physical.views.insert(base, (len, slice));
  917. true
  918. }
  919. /// Commits the section pages a view shows (once per page, whichever view).
  920. fn commit(base: usize, len: usize) -> bool {
  921. if on_wine() {
  922. return true; // sections are committed whole there
  923. }
  924. // SAFETY: `[base, base + len)` is a view of a reserved section.
  925. if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() {
  926. return true;
  927. }
  928. let error = std::io::Error::last_os_error();
  929. if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) {
  930. let mut info = PERFORMANCE_INFORMATION {
  931. cb: size_of::<PERFORMANCE_INFORMATION>() as u32,
  932. ..Default::default()
  933. };
  934. // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION.
  935. let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0;
  936. victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info)));
  937. } else {
  938. tracing::warn!(len, %error, "committing physical pages failed");
  939. }
  940. false
  941. }
  942. fn commit_limit_message(
  943. len: usize,
  944. error: &std::io::Error,
  945. info: Option<&PERFORMANCE_INFORMATION>,
  946. ) -> String {
  947. let mut message = format!(
  948. "VIctory: Windows commit limit reached while committing {len} bytes of physical pages: {error}.\n"
  949. );
  950. if let Some(info) = info {
  951. use std::fmt::Write;
  952. let committed = info.CommitTotal * info.PageSize / MIB;
  953. let limit = info.CommitLimit * info.PageSize / MIB;
  954. let _ = writeln!(
  955. message,
  956. "System commit: {committed} MiB of {limit} MiB in use."
  957. );
  958. }
  959. message.push_str(
  960. "Close other applications or increase the Windows paging file size, then retry.\n",
  961. );
  962. message
  963. }
  964. /// Returns `[base, base + len)` to placeholders; views reaching past it
  965. /// are mapped again outside it.
  966. fn unmap(physical: &mut Physical, base: usize, len: usize) {
  967. // No bytes: no view to return. The search below would still find the
  968. // view holding `base` and cut it in two there, and its range of views
  969. // starting inside would run backwards (which `BTreeMap` panics on).
  970. if len == 0 {
  971. return;
  972. }
  973. let end = base + len;
  974. // Views do not overlap: the one holding `base`, then those starting
  975. // inside (the GPU's page mappings make one view per page).
  976. let first = physical
  977. .views
  978. .range(..=base)
  979. .next_back()
  980. .filter(|(at, (size, _))| *at + size > base)
  981. .map(|(at, _)| *at);
  982. let hit: Vec<usize> = first
  983. .into_iter()
  984. .chain(physical.views.range(base + 1..end).map(|(at, _)| *at))
  985. .collect();
  986. for at in hit {
  987. let Some((size, slice)) = physical.views.remove(&at) else {
  988. continue;
  989. };
  990. physical.forget_view(at, size, &slice);
  991. victory_gpu::title_memory_unmapping(at, size);
  992. // SAFETY: a view we mapped; it becomes a placeholder again.
  993. unsafe {
  994. UnmapViewOfFile2(
  995. GetCurrentProcess(),
  996. MEMORY_MAPPED_VIEW_ADDRESS {
  997. Value: at as *mut c_void,
  998. },
  999. MEM_PRESERVE_PLACEHOLDER,
  1000. )
  1001. };
  1002. if at < base {
  1003. map(physical, at, base - at, slice.clone());
  1004. }
  1005. if at + size > end {
  1006. let index = slice.index + (end - at) / PAGE;
  1007. map(physical, end, at + size - end, Slice { index, ..slice });
  1008. }
  1009. }
  1010. }
  1011. /// The oldest layout we know; newer titles pass other flag values (Minecraft
  1012. /// 0x20000001) and read the same leading fields.
  1013. #[repr(C)]
  1014. #[derive(Debug, Default)]
  1015. pub struct WorkingSet {
  1016. pub title_limit: usize,
  1017. pub title_used: usize,
  1018. pub tools_limit: usize,
  1019. pub tools_used: usize,
  1020. pub stack_used: u32,
  1021. pub physical_pages: u32,
  1022. pub gpu_optimal_limit: usize,
  1023. pub gpu_optimal_used: usize,
  1024. pub tools_gpu_optimal_limit: usize,
  1025. pub tools_gpu_optimal_used: usize,
  1026. pub kernel_pool_used: u32,
  1027. pub kernel_pool_limit: u32,
  1028. }
  1029. /// The title's budget and our process's commit as what it uses. No tools
  1030. /// memory: a retail console.
  1031. // shortcut: all fields are filled whatever the flags ask for, and use is
  1032. // not split by bandwidth class (GPU-optimal use reads 0); track
  1033. // allocations per class if a title budgets from that field.
  1034. pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL {
  1035. if out.is_null() {
  1036. return 0;
  1037. }
  1038. let mut counters = PROCESS_MEMORY_COUNTERS {
  1039. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  1040. ..Default::default()
  1041. };
  1042. // SAFETY: our own process and a sized structure.
  1043. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
  1044. let (gpu_optimal, standard) = victory_gpu::console::current().title_memory();
  1045. let stats = WorkingSet {
  1046. title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed),
  1047. title_used: counters.PagefileUsage,
  1048. gpu_optimal_limit: gpu_optimal,
  1049. ..Default::default()
  1050. };
  1051. // What the title is told, logged at the first asking and at every
  1052. // 1,024th: "used" is all the process has committed, the layer's own
  1053. // memory and the card's included (27 GB in run 60's gameplay against a
  1054. // limit of 13.5 GB). A title that budgets its streaming from these two
  1055. // figures believes it is far over its limit.
  1056. // shortcut: the figure is not yet the title's own memory alone (its
  1057. // heaps and the pages it mapped); count those if this line shows the
  1058. // title asking.
  1059. static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1060. let asked = ASKED.fetch_add(1, Ordering::Relaxed);
  1061. if asked.is_multiple_of(1024) {
  1062. tracing::info!(
  1063. asked = asked + 1,
  1064. which = _which,
  1065. limit_mb = stats.title_limit >> 20,
  1066. used_mb = stats.title_used >> 20,
  1067. "the title asks how much memory it uses"
  1068. );
  1069. }
  1070. // SAFETY: checked non-null; the title passes room for the structure.
  1071. unsafe { out.write(stats) };
  1072. 1
  1073. }
  1074. /// Hands title memory (standard, in 2 MiB pages) to the system. The other
  1075. /// transfers involve tools memory, which a retail console has none of.
  1076. pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
  1077. const TITLE_TO_SYSTEM: u32 = 0;
  1078. tracing::info!(kind, size, "XMemTransferMemory");
  1079. if size == 0 {
  1080. return 1;
  1081. }
  1082. let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
  1083. return 0;
  1084. };
  1085. let standard = victory_gpu::console::current().title_memory().1;
  1086. let moved = kind == TITLE_TO_SYSTEM
  1087. && TRANSFERRED
  1088. .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
  1089. t.checked_add(size).filter(|&t| t <= standard)
  1090. })
  1091. .is_ok();
  1092. moved.into()
  1093. }
  1094. pub(crate) fn module() -> HleModule {
  1095. HleModule {
  1096. name: "xmem",
  1097. dlls: &["xmem.dll"],
  1098. exports: vec![
  1099. hle_export!(XMemAlloc),
  1100. hle_export!(XMemFree),
  1101. hle_export!(XMemAllocDefault),
  1102. hle_export!(XMemFreeDefault),
  1103. hle_export!(XMemIsToolsMemAvailable),
  1104. hle_export!(XMemAllocatePhysicalPages),
  1105. hle_export!(XMemFreePhysicalPages),
  1106. hle_export!(XMemMapPhysicalPages),
  1107. hle_export!(XMemMapPhysicalPagesScatter),
  1108. hle_export!(XMemVirtualAlloc),
  1109. hle_export!(XMemVirtualQuery),
  1110. hle_export!(XMemGetWorkingSetStatistics),
  1111. hle_export!(XMemTransferMemory),
  1112. ],
  1113. }
  1114. }
  1115. #[cfg(test)]
  1116. mod tests {
  1117. use super::*;
  1118. fn query(address: *const c_void) -> BasicInformation {
  1119. // SAFETY: plain data; zero is a valid value.
  1120. let mut info: BasicInformation = unsafe { std::mem::zeroed() };
  1121. // SAFETY: a pseudo handle needs no closing.
  1122. let process = unsafe { GetCurrentProcess() };
  1123. assert_eq!(XMemVirtualQuery(process, address, &mut info), 1);
  1124. info
  1125. }
  1126. #[test]
  1127. fn alloc_honours_alignment_and_frees() {
  1128. for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] {
  1129. let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type
  1130. let p = XMemAlloc(100, attributes);
  1131. assert!(!p.is_null());
  1132. assert_eq!(p as usize % align, 0, "field {field:#x}");
  1133. // SAFETY: 100 bytes were allocated.
  1134. unsafe { p.cast::<u8>().write_bytes(0xab, 100) };
  1135. XMemFree(p, attributes);
  1136. }
  1137. let p = XMemAlloc(4096, ALLOC_32BIT);
  1138. assert!(!p.is_null() && (p as usize) < 1 << 32);
  1139. XMemFree(p, ALLOC_32BIT);
  1140. }
  1141. #[test]
  1142. fn virtual_alloc_meets_console_constraints() {
  1143. const GPU_READ_WRITE: u32 = 0x2000;
  1144. let p = XMemVirtualAlloc(
  1145. std::ptr::null_mut(),
  1146. 4 * MIB,
  1147. PAGES_2M | MEM_RESERVE | MEM_COMMIT,
  1148. GRAPHICS | 7 << 12, // 40-bit addresses
  1149. PAGE_READWRITE | GPU_READ_WRITE,
  1150. );
  1151. assert!(!p.is_null());
  1152. assert_eq!(p as usize % (2 * MIB), 0);
  1153. assert!((p as usize) < 1 << 40);
  1154. let info = query(p);
  1155. assert_eq!(info.host.State, MEM_COMMIT);
  1156. assert_eq!(info.host.Protect, PAGE_READWRITE);
  1157. assert_eq!(info.flags & GRAPHICS, GRAPHICS);
  1158. // Write-watched, for the GPU side's copies.
  1159. let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0);
  1160. // SAFETY: room for `count` addresses.
  1161. let watched = unsafe {
  1162. windows_sys::Win32::System::Memory::GetWriteWatch(
  1163. 0,
  1164. p,
  1165. 4 * MIB,
  1166. found.as_mut_ptr().cast(),
  1167. &mut count,
  1168. &mut granularity,
  1169. )
  1170. };
  1171. assert_eq!(watched, 0);
  1172. // SAFETY: our own reservation.
  1173. assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
  1174. assert_eq!(query(p).flags, 0);
  1175. // No address field: above the 32-bit range and below 2^40, where
  1176. // the console keeps it.
  1177. let p = XMemVirtualAlloc(
  1178. std::ptr::null_mut(),
  1179. 16 << 30,
  1180. MEM_RESERVE,
  1181. GRAPHICS,
  1182. PAGE_NOACCESS,
  1183. );
  1184. assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}");
  1185. assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}");
  1186. // SAFETY: our own reservation.
  1187. assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
  1188. }
  1189. #[test]
  1190. fn transfers_shrink_the_title_budget() {
  1191. let mut before = WorkingSet::default();
  1192. assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1);
  1193. assert!(before.title_used > 0);
  1194. assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1);
  1195. assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory");
  1196. let standard = victory_gpu::console::current().title_memory().1;
  1197. assert_eq!(XMemTransferMemory(0, standard), 0, "over budget");
  1198. let mut after = WorkingSet::default();
  1199. XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
  1200. assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
  1201. }
  1202. #[test]
  1203. fn statistics_have_the_console_layout() {
  1204. assert_eq!(size_of::<WorkingSet>(), 0x50);
  1205. assert_eq!(size_of::<BasicInformation>(), 0x40);
  1206. assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
  1207. }
  1208. #[test]
  1209. fn commit_limit_report_includes_request_and_system_commit() {
  1210. let error = std::io::Error::from_raw_os_error(ERROR_COMMITMENT_LIMIT as i32);
  1211. let info = PERFORMANCE_INFORMATION {
  1212. CommitTotal: 512,
  1213. CommitLimit: 768,
  1214. PageSize: 4096,
  1215. ..Default::default()
  1216. };
  1217. let report = commit_limit_message(4 * MIB, &error, Some(&info));
  1218. assert!(report.contains("4194304 bytes"));
  1219. assert!(report.contains("2 MiB of 3 MiB in use"));
  1220. let fallback = commit_limit_message(4 * MIB, &error, None);
  1221. for report in [&report, &fallback] {
  1222. assert!(report.contains("os error 1455"));
  1223. assert!(report.contains("Windows paging file size"));
  1224. }
  1225. assert!(!fallback.contains("System commit:"));
  1226. }
  1227. #[test]
  1228. fn physical_pages_map_alias_and_unmap() {
  1229. let mut pages = [0usize; 3];
  1230. let mut n = 3;
  1231. assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
  1232. assert_eq!(n, 3);
  1233. // Packed into 21 bits as `number >> 4`, as the title keeps them.
  1234. for p in pages {
  1235. assert_eq!((p >> 4 & 0x1f_ffff) << 4, p);
  1236. }
  1237. // Reservations of 64 KiB pages, as titles make them for mapping.
  1238. let reserve = || {
  1239. XMemVirtualAlloc(
  1240. std::ptr::null_mut(),
  1241. 3 * PAGE,
  1242. MEM_RESERVE | PAGES_64K,
  1243. 0,
  1244. PAGE_READWRITE,
  1245. )
  1246. };
  1247. let (a, b) = (reserve(), reserve());
  1248. assert!(!a.is_null() && !b.is_null());
  1249. let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE);
  1250. assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
  1251. // The same page at a second address shows the same bytes.
  1252. assert_eq!(
  1253. XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()),
  1254. at(b, 1)
  1255. );
  1256. // SAFETY: both pages are mapped read-write.
  1257. unsafe {
  1258. at(a, 2).cast::<u8>().write(7);
  1259. assert_eq!(at(b, 1).cast::<u8>().read(), 7);
  1260. a.cast::<u8>().write(1);
  1261. }
  1262. // Writes into pages (DirectStorage's) show through their views.
  1263. assert!(write_physical(&pages[2..], 1, &[9]));
  1264. // SAFETY: mapped read-write.
  1265. assert_eq!(unsafe { at(b, 1).cast::<u8>().add(1).read() }, 9);
  1266. // Unmapping the middle page keeps its neighbours.
  1267. assert_eq!(
  1268. XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()),
  1269. at(a, 1)
  1270. );
  1271. assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
  1272. assert_eq!(query(a).host.State, MEM_COMMIT);
  1273. assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT);
  1274. // SAFETY: still mapped.
  1275. assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 7);
  1276. // A scattered page lands in the hole.
  1277. let addresses = [at(a, 1)];
  1278. assert_eq!(
  1279. XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()),
  1280. 1
  1281. );
  1282. // SAFETY: page 0 is now mapped at both `a` and `a + PAGE`.
  1283. assert_eq!(unsafe { at(a, 1).cast::<u8>().read() }, 1);
  1284. // Page number 0 unmaps.
  1285. assert_eq!(
  1286. XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()),
  1287. 1
  1288. );
  1289. assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
  1290. // The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`.
  1291. assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64));
  1292. // SAFETY: mapped read-write.
  1293. assert_eq!(unsafe { b.cast::<u8>().read() }, 7);
  1294. assert!(map_alias(b as u64, 0, PAGE as u64));
  1295. assert_eq!(query(b).host.State, MEM_RESERVE);
  1296. assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64));
  1297. assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
  1298. assert_eq!(XMemIsToolsMemAvailable(), 0);
  1299. }
  1300. /// A thread that reads a mapped page in place, as the GPU side reads a
  1301. /// texture, never meets the moment in which the runtime has taken the
  1302. /// page's view away to map it again: mapping the same pages at the same
  1303. /// address unmaps the view and maps a new one, and without the lock the
  1304. /// reader faults on a page "reserved, never committed" (the crashes of
  1305. /// runs 71 and 74).
  1306. #[test]
  1307. fn a_read_in_place_never_meets_the_gap_of_a_remapping() {
  1308. use std::sync::atomic::{AtomicBool, Ordering};
  1309. let mut pages = [0usize; 3];
  1310. let mut n = 3;
  1311. assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
  1312. let a = XMemVirtualAlloc(
  1313. std::ptr::null_mut(),
  1314. 3 * PAGE,
  1315. MEM_RESERVE | PAGES_64K,
  1316. 0,
  1317. PAGE_READWRITE,
  1318. );
  1319. assert!(!a.is_null());
  1320. assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
  1321. // SAFETY: mapped read-write.
  1322. unsafe { a.cast::<u8>().write(1) };
  1323. let first = a as usize;
  1324. let stop = std::sync::Arc::new(AtomicBool::new(false));
  1325. let reader = {
  1326. let stop = stop.clone();
  1327. std::thread::spawn(move || {
  1328. let mut reads = 0u64;
  1329. while !stop.load(Ordering::Relaxed) {
  1330. let _reading = victory_gpu::title_memory_reading();
  1331. // SAFETY: the page is mapped whenever no change of
  1332. // mapping is under way, and none is while `_reading`
  1333. // is held.
  1334. assert_eq!(unsafe { (first as *const u8).read_volatile() }, 1);
  1335. reads += 1;
  1336. }
  1337. reads
  1338. })
  1339. };
  1340. for _ in 0..2000 {
  1341. // The same pages at the same address: the view goes and comes
  1342. // back, with the same bytes.
  1343. assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
  1344. }
  1345. stop.store(true, Ordering::Relaxed);
  1346. assert!(reader.join().expect("the reader never faulted") > 0);
  1347. assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a);
  1348. assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
  1349. }
  1350. #[test]
  1351. fn mapping_no_pages_changes_nothing() {
  1352. let pages = allocate(2);
  1353. let a = XMemVirtualAlloc(
  1354. std::ptr::null_mut(),
  1355. 2 * PAGE,
  1356. MEM_RESERVE | PAGES_64K,
  1357. 0,
  1358. PAGE_READWRITE,
  1359. );
  1360. assert!(!a.is_null());
  1361. assert_eq!(XMemMapPhysicalPages(a, 2, pages.as_ptr()), a);
  1362. // SAFETY: both pages are mapped read-write.
  1363. unsafe { a.cast::<u8>().write(5) };
  1364. let second = a.wrapping_byte_add(PAGE);
  1365. // A count of 0 at the start of a view, inside it and past it: with
  1366. // pages, without (an unmap), and as the GPU's page-mapping copy.
  1367. for at in [a, second, a.wrapping_byte_add(2 * PAGE)] {
  1368. assert_eq!(XMemMapPhysicalPages(at, 0, pages.as_ptr()), at);
  1369. assert_eq!(XMemMapPhysicalPages(at, 0, std::ptr::null()), at);
  1370. assert!(map_alias(at as u64, a as u64, 0));
  1371. assert!(map_alias(at as u64, 0, 0));
  1372. }
  1373. // The view is still the one view it was.
  1374. let view = physical().views.get(&(a as usize)).map(|v| v.0);
  1375. assert_eq!(view, Some(2 * PAGE));
  1376. assert_eq!(query(a).host.State, MEM_COMMIT);
  1377. assert_eq!(query(second).host.State, MEM_COMMIT);
  1378. // SAFETY: still mapped.
  1379. assert_eq!(unsafe { a.cast::<u8>().read() }, 5);
  1380. // A count of 1 still unmaps that page alone.
  1381. assert_eq!(XMemMapPhysicalPages(second, 1, std::ptr::null()), second);
  1382. assert_eq!(query(second).host.State, MEM_RESERVE);
  1383. assert_eq!(query(a).host.State, MEM_COMMIT);
  1384. assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a);
  1385. assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1);
  1386. }
  1387. /// `n` pages of one new allocation.
  1388. fn allocate(n: usize) -> Vec<usize> {
  1389. let (mut pages, mut given) = (vec![0; n], n);
  1390. assert_eq!(
  1391. XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()),
  1392. 1
  1393. );
  1394. assert_eq!(given, n);
  1395. pages
  1396. }
  1397. /// The bytes of one page, through a view of our own.
  1398. fn page_bytes(page: usize) -> Vec<u8> {
  1399. let slice = physical().pages.get(&page).cloned().expect("known page");
  1400. View::map(&slice, 1).expect("mapped").bytes().to_vec()
  1401. }
  1402. #[test]
  1403. fn runs_group_consecutive_pages_of_one_allocation() {
  1404. let (a, b) = (allocate(3), allocate(1));
  1405. let lengths = |pages: &[usize], offset, len| {
  1406. runs(pages, offset, len).map(|r| r.iter().map(|&(_, n)| n).collect::<Vec<_>>())
  1407. };
  1408. assert_eq!(lengths(&a, 0, 3 * PAGE), Some(vec![3]));
  1409. // Only the pages the bytes reach.
  1410. assert_eq!(lengths(&a, PAGE + 5, 10), Some(vec![1]));
  1411. assert_eq!(lengths(&a, PAGE - 1, 2), Some(vec![2]));
  1412. assert_eq!(lengths(&a, 0, 0), Some(vec![]));
  1413. // Out of order, or across allocations: one run each.
  1414. assert_eq!(
  1415. lengths(&[a[0], a[2], a[1]], 0, 3 * PAGE),
  1416. Some(vec![1, 1, 1])
  1417. );
  1418. assert_eq!(lengths(&[a[1], a[2], b[0]], 0, 3 * PAGE), Some(vec![2, 1]));
  1419. // A slice that follows on in another section starts a run.
  1420. assert_eq!(lengths(&[b[0], a[1]], 0, 2 * PAGE), Some(vec![1, 1]));
  1421. // Too few pages for the bytes, or an unknown one.
  1422. assert_eq!(lengths(&a, 0, 3 * PAGE + 1), None);
  1423. assert_eq!(lengths(&[a[0], 0x10], 0, 2 * PAGE), None);
  1424. assert_eq!(lengths(&a, usize::MAX, 2), None);
  1425. assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1);
  1426. assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
  1427. }
  1428. #[test]
  1429. fn writes_cross_runs_and_allocations() {
  1430. let (a, b) = (allocate(2), allocate(1));
  1431. let pages = [a[0], a[1], b[0]];
  1432. let data: Vec<u8> = (0..2 * PAGE + 64).map(|i| (i * 7 % 251) as u8).collect();
  1433. let offset = PAGE - 32;
  1434. // Past the third page: the second run is too short.
  1435. assert!(!write_physical(&pages, offset, &data));
  1436. assert!(write_physical(&pages, offset, &data[..2 * PAGE]));
  1437. let seen: Vec<u8> = pages.iter().flat_map(|&p| page_bytes(p)).collect();
  1438. assert!(seen[..offset].iter().all(|&b| b == 0), "before the offset");
  1439. assert_eq!(seen[offset..offset + 2 * PAGE], data[..2 * PAGE]);
  1440. assert!(seen[offset + 2 * PAGE..].iter().all(|&b| b == 0), "after");
  1441. assert!(
  1442. !write_physical(&[a[0], 0x10], 0, &data[..PAGE + 1]),
  1443. "unknown page"
  1444. );
  1445. assert_eq!(XMemFreePhysicalPages(2, a.as_ptr()), 1);
  1446. assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
  1447. }
  1448. #[test]
  1449. fn page_windows_cover_one_run_in_place() {
  1450. let (a, b) = (allocate(3), allocate(1));
  1451. let mut window = page_window(&a, PAGE + 3, PAGE).expect("one run");
  1452. assert_eq!(window.bytes().len(), PAGE);
  1453. window.bytes().fill(0x5a);
  1454. drop(window);
  1455. let (second, third) = (page_bytes(a[1]), page_bytes(a[2]));
  1456. assert!(second[..3].iter().all(|&b| b == 0));
  1457. assert!(second[3..].iter().all(|&b| b == 0x5a));
  1458. assert!(third[..3].iter().all(|&b| b == 0x5a));
  1459. assert!(third[3..].iter().all(|&b| b == 0));
  1460. // Several runs, or an unknown page: no window.
  1461. assert!(page_window(&[a[0], b[0]], 0, PAGE + 1).is_none());
  1462. assert!(page_window(&[a[1], a[0]], 0, PAGE + 1).is_none());
  1463. assert!(page_window(&[0x10], 0, 1).is_none());
  1464. // One page of several is still one run.
  1465. assert!(page_window(&[a[0], b[0]], 0, PAGE).is_some());
  1466. assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1);
  1467. assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
  1468. }
  1469. }