xmem.rs 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433
  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, RwLock, RwLockReadGuard, RwLockWriteGuard};
  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 at.is_null() {
  148. let error = std::io::Error::last_os_error();
  149. if kind & MEM_COMMIT != 0 {
  150. commit_refused(size, "virtual memory", error);
  151. } else {
  152. tracing::warn!(
  153. size,
  154. kind = format_args!("{kind:#x}"),
  155. flags = format_args!("{flags:#x}"),
  156. %error,
  157. "XMemVirtualAlloc refused"
  158. );
  159. }
  160. }
  161. if base.is_null() {
  162. tracing::debug!(
  163. size,
  164. kind = format_args!("{kind:#x}"),
  165. flags = format_args!("{flags:#x}"),
  166. at = format_args!("{at:p}"),
  167. "XMemVirtualAlloc"
  168. );
  169. }
  170. if !at.is_null() && !placeholder {
  171. victory_gpu::title_memory_allocated(at as usize, size);
  172. }
  173. at
  174. }
  175. /// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
  176. /// same), then the XMem flags and tag.
  177. #[repr(C)]
  178. pub struct BasicInformation {
  179. host: MEMORY_BASIC_INFORMATION,
  180. flags: u64,
  181. tag_code: u32,
  182. tag: [u8; 4],
  183. }
  184. // shortcut: every committed page reports graphics memory and no tag, since
  185. // all of it is GPU-reachable here (the title's BVH builder, the
  186. // only caller, wants graphics memory); remember the flags of
  187. // `XMemVirtualAlloc` regions if a title tells CPU-only memory apart.
  188. pub extern "system" fn XMemVirtualQuery(
  189. process: HANDLE,
  190. address: *const c_void,
  191. out: *mut BasicInformation,
  192. ) -> BOOL {
  193. let size = size_of::<MEMORY_BASIC_INFORMATION>();
  194. // SAFETY: the title passes room for the whole structure; the host
  195. // fails on a null one.
  196. unsafe {
  197. if VirtualQueryEx(process, address, out.cast(), size) == 0 {
  198. return 0;
  199. }
  200. let info = &mut *out;
  201. info.flags = if info.host.State == MEM_COMMIT {
  202. GRAPHICS
  203. } else {
  204. 0
  205. };
  206. info.tag_code = 0;
  207. info.tag = [0; 4];
  208. }
  209. 1
  210. }
  211. // `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up
  212. // from 2), then the memory type, then bit 33: a 32-bit address.
  213. const ALIGNMENT_SHIFT: u64 = 24;
  214. const ALLOC_32BIT: u64 = 1 << 33;
  215. /// Our block header: the block's size and alignment, just below the
  216. /// pointer handed out.
  217. const HEADER: usize = 2 * size_of::<usize>();
  218. fn layout(size: usize, attributes: u64) -> Option<Layout> {
  219. // An alignment of at least 16 leaves room for the header.
  220. let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4);
  221. Layout::from_size_align(size.checked_add(align)?, align).ok()
  222. }
  223. type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
  224. type FreeRoutine = extern "system" fn(*mut c_void, u64);
  225. /// The allocation and free routines the title's exe exports as
  226. /// `__XMemAllocationHooks__` (the title does): `XMemAlloc` and
  227. /// `XMemFree` call them, for the title's own calls and its middleware's;
  228. /// the `…Default` exports do not.
  229. fn hooks() -> [usize; 2] {
  230. static AT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
  231. let at = match AT.get() {
  232. Some(&at) => at,
  233. // Looked up once the title is mapped, which is before it runs.
  234. None => match crate::runtime::main_image() {
  235. Some(base) => *AT.get_or_init(|| {
  236. use windows_sys::Win32::System::LibraryLoader::GetProcAddress;
  237. // SAFETY: a mapped image and a NUL-terminated name.
  238. let at = unsafe {
  239. GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast())
  240. }
  241. .map_or(0, |f| f as usize);
  242. tracing::info!(found = at != 0, "xmem allocation hooks");
  243. at
  244. }),
  245. None => 0,
  246. },
  247. };
  248. if at == 0 {
  249. return [0; 2];
  250. }
  251. // SAFETY: the export is two routine pointers.
  252. unsafe { (at as *const [usize; 2]).read() }
  253. }
  254. /// The title's general allocator, for middleware too: its hook if it has
  255. /// one, else [`XMemAllocDefault`].
  256. pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
  257. match hooks()[0] {
  258. 0 => XMemAllocDefault(size, attributes),
  259. hook => {
  260. // SAFETY: the title's own routine of this type.
  261. let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) };
  262. alloc(size, attributes)
  263. }
  264. }
  265. }
  266. /// See [`XMemAlloc`].
  267. pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
  268. match hooks()[1] {
  269. 0 => XMemFreeDefault(address, attributes),
  270. hook => {
  271. // SAFETY: the title's own routine of this type.
  272. let free: FreeRoutine = unsafe { std::mem::transmute(hook) };
  273. free(address, attributes)
  274. }
  275. }
  276. }
  277. /// The system allocator behind [`XMemAlloc`].
  278. pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void {
  279. if attributes & ALLOC_32BIT != 0 {
  280. return XMemVirtualAlloc(
  281. std::ptr::null_mut(),
  282. size,
  283. MEM_RESERVE | MEM_COMMIT,
  284. GRAPHICS | ADDRESS_32BIT,
  285. PAGE_READWRITE,
  286. );
  287. }
  288. let Some(layout) = layout(size, attributes) else {
  289. return std::ptr::null_mut();
  290. };
  291. // shortcut: the host heap's addresses lie above 2^40, unlike the
  292. // console's; nothing seen builds ray-tracing structures in this memory
  293. // (the title uses its GPU heap). Sub-allocate from a
  294. // reservation below 2^40 if one does.
  295. // SAFETY: the layout has a non-zero size.
  296. let block = unsafe { alloc(layout) };
  297. if block.is_null() {
  298. tracing::warn!(size, "XMemAllocDefault: the host heap is out of memory");
  299. return block.cast();
  300. }
  301. // SAFETY: the block holds the alignment (at least the header) and then
  302. // `size` bytes.
  303. unsafe {
  304. let user = block.add(layout.align());
  305. user.sub(HEADER)
  306. .cast::<[usize; 2]>()
  307. .write([layout.size(), layout.align()]);
  308. user.cast()
  309. }
  310. }
  311. /// Frees what [`XMemAllocDefault`] returned, given the same attributes.
  312. pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
  313. if address.is_null() {
  314. return;
  315. }
  316. // SAFETY: the address came from `XMemAlloc` with these attributes: a
  317. // whole reservation, or a header-prefixed block.
  318. unsafe {
  319. if attributes & ALLOC_32BIT != 0 {
  320. VirtualFree(address, 0, MEM_RELEASE);
  321. return;
  322. }
  323. let user = address.cast::<u8>();
  324. let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read();
  325. dealloc(
  326. user.sub(align),
  327. Layout::from_size_align_unchecked(size, align),
  328. );
  329. }
  330. }
  331. /// A retail console has no tools memory.
  332. pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL {
  333. 0
  334. }
  335. // Physical pages: on the console, 64 KiB frames a title maps into its own
  336. // reservations, at more than one address if it likes. Here each allocation
  337. // is a pagefile-backed section, its pages are 64 KiB slices of it, and a
  338. // mapping is a view of consecutive slices in place of a host placeholder.
  339. const PAGE: usize = 64 << 10;
  340. struct Section {
  341. handle: HANDLE,
  342. pages: usize,
  343. /// A view of the whole section, kept ([`Section::window`]); 0 if the
  344. /// host gave none.
  345. window: std::sync::OnceLock<usize>,
  346. /// A bit per page: committed, as far as [`Section::window`] asked.
  347. committed: Box<[std::sync::atomic::AtomicU64]>,
  348. }
  349. impl Section {
  350. /// Where bytes of `n` pages from page `index` on can be written,
  351. /// whether or not the pages are mapped anywhere, committed.
  352. ///
  353. /// Every DirectStorage write mapped a view of its pages, committed it,
  354. /// faulted each of its 4 KiB pages in and unmapped it again, all of it
  355. /// under the process's one address-space lock, with 24 workers, the
  356. /// title's own mapping calls (about 100,000 views of one page) and our
  357. /// guards asking for the same lock. One view of the section, kept,
  358. /// costs that once per page.
  359. /// `VICTORY_SECTION_WINDOW=0`: a view for each write, as before.
  360. fn window(&self, index: usize, n: usize) -> Option<usize> {
  361. use std::sync::atomic::Ordering;
  362. use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile};
  363. static ON: LazyLock<bool> =
  364. LazyLock::new(|| std::env::var_os("VICTORY_SECTION_WINDOW").is_none_or(|v| v != "0"));
  365. if !*ON || index + n > self.pages {
  366. return None;
  367. }
  368. let base = *self.window.get_or_init(|| {
  369. // SAFETY: the whole of a section we own.
  370. unsafe { MapViewOfFile(self.handle, FILE_MAP_WRITE, 0, 0, self.pages * PAGE) }.Value as usize
  371. });
  372. if base == 0 {
  373. return None;
  374. }
  375. let missing = |page: usize| self.committed[page / 64].load(Ordering::Acquire) >> (page % 64) & 1 == 0;
  376. let mut page = index;
  377. while page < index + n {
  378. if !missing(page) {
  379. page += 1;
  380. continue;
  381. }
  382. let run = (page..index + n).take_while(|&p| missing(p)).count();
  383. if run == 0 {
  384. continue; // another worker committed it meanwhile
  385. }
  386. if !commit(base + page * PAGE, run * PAGE) {
  387. return None;
  388. }
  389. for p in page..page + run {
  390. self.committed[p / 64].fetch_or(1 << (p % 64), Ordering::AcqRel);
  391. }
  392. page += run;
  393. }
  394. Some(base + index * PAGE)
  395. }
  396. }
  397. impl Section {
  398. /// Commits the pages from `index` on that a view at `base` shows, unless
  399. /// all of them are ([`lean`]): committed for one view is for all.
  400. fn commit_shown(&self, index: usize, base: usize, len: usize) -> bool {
  401. use std::sync::atomic::Ordering;
  402. let pages = index..(index + len / PAGE).min(self.pages);
  403. let bit = |p: usize| (&self.committed[p / 64], 1 << (p % 64));
  404. let done = || {
  405. pages.clone().all(|p| {
  406. let (word, bit) = bit(p);
  407. word.load(Ordering::Acquire) & bit != 0
  408. })
  409. };
  410. if lean() && done() {
  411. return true;
  412. }
  413. if !counted(Call::Commit, || commit(base, len)) {
  414. return false;
  415. }
  416. for p in pages {
  417. let (word, bit) = bit(p);
  418. word.fetch_or(bit, Ordering::AcqRel);
  419. }
  420. true
  421. }
  422. }
  423. // SAFETY: a section handle may be used from any thread.
  424. unsafe impl Send for Section {}
  425. // SAFETY: as above.
  426. unsafe impl Sync for Section {}
  427. impl Drop for Section {
  428. fn drop(&mut self) {
  429. use windows_sys::Win32::System::Memory::UnmapViewOfFile;
  430. if let Some(&base) = self.window.get()
  431. && base != 0
  432. {
  433. // SAFETY: our view; whoever writes through it holds the section.
  434. unsafe {
  435. UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
  436. Value: base as *mut c_void,
  437. })
  438. };
  439. }
  440. victory_gpu::title_memory_section_gone(self.handle as usize);
  441. // SAFETY: our handle; views keep the section alive on their own.
  442. unsafe { CloseHandle(self.handle) };
  443. }
  444. }
  445. /// Where a page lives, or what a view starts with: a section and a page
  446. /// index in it.
  447. #[derive(Clone)]
  448. struct Slice {
  449. section: Arc<Section>,
  450. index: usize,
  451. }
  452. #[derive(Default)]
  453. struct Physical {
  454. /// Mapped views by address: their length and what they show.
  455. views: BTreeMap<usize, (usize, Slice)>,
  456. /// Placeholders that are some view's own, left by its unmapping: address
  457. /// and length. The title may have joined one with others since.
  458. holes: HashMap<usize, usize>,
  459. }
  460. impl Physical {
  461. /// What the page at `at` shows.
  462. fn slice_at(&self, at: usize) -> Option<Slice> {
  463. self.views
  464. .range(..=at)
  465. .next_back()
  466. .filter(|(base, (size, _))| at < *base + size)
  467. .map(|(base, (_, s))| Slice {
  468. index: s.index + (at - base) / PAGE,
  469. section: s.section.clone(),
  470. })
  471. }
  472. }
  473. /// The title's pages by number.
  474. struct Pages {
  475. next_page: usize,
  476. pages: HashMap<usize, Slice>,
  477. }
  478. /// Where the title sees its pages: [`Physical::views`] the other way.
  479. /// Locked apart from them, and only for a moment ([`PAGES`]).
  480. #[derive(Default)]
  481. struct Shown {
  482. /// The addresses that show a page, by the page's section and index.
  483. /// Views of more than [`SHORT`] pages are in `long`.
  484. pages: HashMap<(usize, usize), Vec<usize>>,
  485. /// Address, bytes, section, first page.
  486. long: Vec<(usize, usize, usize, usize)>,
  487. }
  488. /// Pages of a view noted page by page in [`Shown::pages`].
  489. const SHORT: usize = 64;
  490. /// Taken after [`PHYSICAL`] where both are.
  491. static SHOWN: LazyLock<RwLock<Shown>> = LazyLock::new(Default::default);
  492. fn shown_mut() -> RwLockWriteGuard<'static, Shown> {
  493. SHOWN.write().unwrap_or_else(|e| e.into_inner())
  494. }
  495. impl Shown {
  496. fn note(&mut self, base: usize, len: usize, slice: &Slice) {
  497. let section = Arc::as_ptr(&slice.section) as usize;
  498. if len / PAGE > SHORT {
  499. self.long.push((base, len, section, slice.index));
  500. return;
  501. }
  502. for k in 0..len / PAGE {
  503. self.pages.entry((section, slice.index + k)).or_default().push(base + k * PAGE);
  504. }
  505. }
  506. fn forget(&mut self, base: usize, len: usize, slice: &Slice) {
  507. if len / PAGE > SHORT {
  508. self.long.retain(|view| view.0 != base);
  509. return;
  510. }
  511. let section = Arc::as_ptr(&slice.section) as usize;
  512. for k in 0..len / PAGE {
  513. let key = (section, slice.index + k);
  514. if let Some(at) = self.pages.get_mut(&key) {
  515. at.retain(|&at| at != base + k * PAGE);
  516. if at.is_empty() {
  517. self.pages.remove(&key);
  518. }
  519. }
  520. }
  521. }
  522. /// Where the title sees the page at `slice`: addresses and bytes.
  523. fn at(&self, slice: &Slice) -> Vec<(usize, usize)> {
  524. let section = Arc::as_ptr(&slice.section) as usize;
  525. let mut out: Vec<(usize, usize)> =
  526. self.pages.get(&(section, slice.index)).into_iter().flatten().map(|&at| (at, PAGE)).collect();
  527. for &(base, len, of, index) in &self.long {
  528. if of == section && (index..index + len / PAGE).contains(&slice.index) {
  529. out.push((base + (slice.index - index) * PAGE, PAGE));
  530. }
  531. }
  532. out
  533. }
  534. }
  535. /// See [`pages_written`].
  536. pub(crate) fn stream_notice() -> bool {
  537. static ON: LazyLock<bool> =
  538. LazyLock::new(|| std::env::var_os("VICTORY_STREAM_NOTICE").is_none_or(|v| v != "0"));
  539. *ON
  540. }
  541. /// The views, changed by the title's mapping calls; held for as long as
  542. /// those take (the host maps, commits and unmaps under it).
  543. static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(Default::default);
  544. fn physical() -> MutexGuard<'static, Physical> {
  545. PHYSICAL.lock().unwrap_or_else(|e| e.into_inner())
  546. }
  547. /// The title's pages. Apart from the views: DirectStorage looks pages up at
  548. /// every request, from 24 workers, and used to wait there for the title's
  549. /// mapping calls (12,000 waits of 1 to 170 ms in a load of 90 s). Written
  550. /// only where the title allocates or frees pages. Taken after [`PHYSICAL`]
  551. /// where both are.
  552. static PAGES: LazyLock<RwLock<Pages>> = LazyLock::new(|| {
  553. RwLock::new(Pages {
  554. // Page numbers are opaque to titles; 0 stays unused.
  555. next_page: 0x10_0000,
  556. pages: HashMap::new(),
  557. })
  558. });
  559. fn page_table() -> RwLockReadGuard<'static, Pages> {
  560. PAGES.read().unwrap_or_else(|e| e.into_inner())
  561. }
  562. fn page_table_mut() -> RwLockWriteGuard<'static, Pages> {
  563. PAGES.write().unwrap_or_else(|e| e.into_inner())
  564. }
  565. /// `count` is in and out (pages wanted, pages given); all or nothing here.
  566. pub extern "system" fn XMemAllocatePhysicalPages(
  567. flags: u64,
  568. count: *mut usize,
  569. pages: *mut usize,
  570. ) -> BOOL {
  571. if count.is_null() || pages.is_null() {
  572. return 0;
  573. }
  574. // SAFETY: checked non-null.
  575. let n = unsafe { *count };
  576. let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else {
  577. return 0;
  578. };
  579. // A pagefile-backed section of `size` bytes, its pages committed when
  580. // first mapped or written (`commit`): the title asks for 6.1
  581. // GiB at once, which a busy host often cannot commit (error 1450).
  582. // SAFETY: plain section creation.
  583. let handle = unsafe {
  584. CreateFileMappingW(
  585. INVALID_HANDLE_VALUE,
  586. std::ptr::null(),
  587. // Under Wine a committed section is a sparse file, free until
  588. // touched, and committing a reserved one page by page costs a
  589. // wineserver request each that scans every range committed so
  590. // far: commit it whole there.
  591. PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE },
  592. (size as u64 >> 32) as u32,
  593. size as u32,
  594. std::ptr::null(),
  595. )
  596. };
  597. if handle.is_null() {
  598. let error = std::io::Error::last_os_error();
  599. tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed");
  600. // SAFETY: checked non-null.
  601. unsafe { count.write(0) };
  602. return 0;
  603. }
  604. tracing::debug!(
  605. n,
  606. flags = format_args!("{flags:#x}"),
  607. "XMemAllocatePhysicalPages"
  608. );
  609. // For the GPU side's in-place census: only a committed section can be
  610. // opened as a host heap.
  611. victory_gpu::title_memory_section(handle as usize, size as u64, on_wine());
  612. let section = Arc::new(Section {
  613. handle,
  614. pages: n,
  615. window: std::sync::OnceLock::new(),
  616. committed: (0..n.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(),
  617. });
  618. let mut table = page_table_mut();
  619. let first = table.next_page;
  620. table.next_page += n * FRAMES;
  621. for index in 0..n {
  622. let slice = Slice {
  623. section: section.clone(),
  624. index,
  625. };
  626. table.pages.insert(first + index * FRAMES, slice);
  627. }
  628. // Title memory is touched without our locks: a fault there may wait for
  629. // a mapping call, which takes them.
  630. drop(table);
  631. for index in 0..n {
  632. // SAFETY: the title passes room for `n` page numbers.
  633. unsafe { pages.add(index).write(first + index * FRAMES) };
  634. }
  635. 1
  636. }
  637. /// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of
  638. /// 16: the title keeps them as 21-bit `number >> 4` and rebuilds
  639. /// them with `<< 4` (128 GiB of pages at most).
  640. const FRAMES: usize = PAGE >> 12;
  641. /// Pages still mapped stay readable through their views until unmapped.
  642. pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL {
  643. if pages.is_null() {
  644. return 0;
  645. }
  646. // SAFETY: the title passes `n` page numbers.
  647. let numbers = unsafe { std::slice::from_raw_parts(pages, n) }.to_vec();
  648. let mut table = page_table_mut();
  649. // Dropped without the lock: the last page of a section unmaps its window.
  650. let gone: Vec<Slice> = numbers.iter().filter_map(|number| table.pages.remove(number)).collect();
  651. drop(table);
  652. drop(gone);
  653. 1
  654. }
  655. /// A view of our own on consecutive slices of one section, committed and
  656. /// writable, unmapped when dropped.
  657. struct View {
  658. at: MEMORY_MAPPED_VIEW_ADDRESS,
  659. len: usize,
  660. }
  661. impl View {
  662. /// Maps `n` slices from `slice` on.
  663. fn map(slice: &Slice, n: usize) -> Option<View> {
  664. use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile};
  665. let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE);
  666. // SAFETY: slices of a section we own; the view is ours until dropped.
  667. let at = unsafe {
  668. MapViewOfFile(
  669. slice.section.handle,
  670. FILE_MAP_WRITE,
  671. (offset >> 32) as u32,
  672. offset as u32,
  673. len,
  674. )
  675. };
  676. if at.Value.is_null() {
  677. tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not mapped for a write");
  678. return None;
  679. }
  680. let view = View { at, len };
  681. if !commit(at.Value as usize, len) {
  682. tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not committed for a write");
  683. return None;
  684. }
  685. Some(view)
  686. }
  687. fn bytes(&mut self) -> &mut [u8] {
  688. // SAFETY: the view holds `len` committed read-write bytes, ours
  689. // alone while `self` lives (other views of the slices only alias
  690. // them, as the console's do).
  691. unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) }
  692. }
  693. }
  694. impl Drop for View {
  695. fn drop(&mut self) {
  696. use windows_sys::Win32::System::Memory::UnmapViewOfFile;
  697. // SAFETY: our view.
  698. unsafe { UnmapViewOfFile(self.at) };
  699. }
  700. }
  701. /// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB
  702. /// each), as runs of consecutive slices of one section: each run's first
  703. /// slice and its length in pages. One look at the page table. `None`
  704. /// if a page is unknown or `pages` ends early.
  705. fn runs(pages: &[usize], offset: usize, len: usize) -> Option<Vec<(Slice, usize)>> {
  706. let end = offset.checked_add(len)?;
  707. let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?;
  708. let table = page_table();
  709. let mut runs: Vec<(Slice, usize)> = Vec::new();
  710. for page in pages {
  711. let Some(slice) = table.pages.get(page) else {
  712. tracing::warn!(page, offset, len, "a physical page the title does not own (any more)");
  713. return None;
  714. };
  715. match runs.last_mut() {
  716. Some((first, n))
  717. if Arc::ptr_eq(&first.section, &slice.section)
  718. && slice.index == first.index + *n =>
  719. {
  720. *n += 1;
  721. }
  722. _ => runs.push((slice.clone(), 1)),
  723. }
  724. }
  725. Some(runs)
  726. }
  727. /// Whether the title owns every page under bytes `[offset, offset + len)`.
  728. pub(crate) fn pages_known(pages: &[usize], offset: usize, len: usize) -> bool {
  729. let table = page_table();
  730. pages
  731. .get(offset / PAGE..(offset + len).div_ceil(PAGE))
  732. .is_some_and(|pages| pages.iter().all(|page| table.pages.contains_key(page)))
  733. }
  734. /// Where the title sees the pages under bytes `[offset, offset + len)` now,
  735. /// in order (for the streaming trace: whether that changed while a request
  736. /// wrote them).
  737. pub(crate) fn pages_shown(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> {
  738. let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default();
  739. let slices: Vec<Slice> = {
  740. let table = page_table();
  741. numbers.iter().filter_map(|n| table.pages.get(n)).cloned().collect()
  742. };
  743. let shown = SHOWN.read().unwrap_or_else(|e| e.into_inner());
  744. let mut at: Vec<(usize, usize)> = slices.iter().flat_map(|slice| shown.at(slice)).collect();
  745. at.sort_unstable();
  746. at
  747. }
  748. /// Copies `data` into physical pages, from `offset` bytes into the first,
  749. /// whether or not they are mapped anywhere (DirectStorage destinations).
  750. /// One view per run of consecutive pages, not one per page: each view
  751. /// costs a map, a commit and an unmap (which flushes every core's TLB).
  752. /// False if a page is unknown or the host fails.
  753. pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool {
  754. let Some(runs) = runs(pages, offset, data.len()) else {
  755. return false;
  756. };
  757. let (mut within, mut done) = (offset % PAGE, 0);
  758. for (slice, n) in &runs {
  759. let k = (n * PAGE - within).min(data.len() - done);
  760. if let Some(at) = slice.section.window(slice.index, *n) {
  761. // SAFETY: committed bytes of the section's view, which `runs`
  762. // holds; the title's other uses of them race as on the console.
  763. unsafe { std::ptr::copy_nonoverlapping(data[done..].as_ptr(), (at + within) as *mut u8, k) };
  764. } else {
  765. let Some(mut view) = View::map(slice, *n) else {
  766. return false;
  767. };
  768. view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]);
  769. }
  770. (within, done) = (0, done + k);
  771. }
  772. true
  773. }
  774. /// Bytes `[offset, offset + len)` of physical pages, writable in place
  775. /// until dropped: DirectStorage decodes into it instead of a buffer it
  776. /// would then copy.
  777. pub(crate) struct PageWindow {
  778. view: Window,
  779. within: usize,
  780. len: usize,
  781. }
  782. enum Window {
  783. /// In the section's own view, which the section holds.
  784. Kept(usize, #[expect(dead_code, reason = "held for the view")] Arc<Section>),
  785. Own(View),
  786. }
  787. impl PageWindow {
  788. pub(crate) fn bytes(&mut self) -> &mut [u8] {
  789. let (within, len) = (self.within, self.len);
  790. match &mut self.view {
  791. // SAFETY: committed bytes of the section's view, ours alone as
  792. // far as the runtime goes (other views alias them, as the
  793. // console's do).
  794. Window::Kept(at, _) => unsafe { std::slice::from_raw_parts_mut((*at + within) as *mut u8, len) },
  795. Window::Own(view) => &mut view.bytes()[within..within + len],
  796. }
  797. }
  798. }
  799. /// A window on bytes `[offset, offset + len)` of `pages` when they are
  800. /// consecutive pages of one allocation (how titles usually hand them out);
  801. /// `None` otherwise (pages of several allocations, out of order, or
  802. /// unknown, or a host failure), which `write_physical` then handles or
  803. /// reports.
  804. pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option<PageWindow> {
  805. let runs = runs(pages, offset, len)?;
  806. let [(slice, n)] = runs.as_slice() else {
  807. return None;
  808. };
  809. let view = match slice.section.window(slice.index, *n) {
  810. Some(at) => Window::Kept(at, slice.section.clone()),
  811. None => Window::Own(View::map(slice, *n)?),
  812. };
  813. Some(PageWindow {
  814. view,
  815. within: offset % PAGE,
  816. len,
  817. })
  818. }
  819. /// The title addresses that show bytes `[offset, offset + len)` of `pages`
  820. /// now, byte for byte, as runs (address, bytes) in address order: a write
  821. /// to the pages through a view of our own ([`page_window`],
  822. /// [`write_physical`]) lands there too, and nothing that watches those
  823. /// addresses sees it. Empty if no view shows them. Byte for byte, not by
  824. /// whole pages: the title packs several small textures into one page and
  825. /// fills each with a request of its own.
  826. pub(crate) fn shown_at(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> {
  827. let Some(end) = offset.checked_add(len) else {
  828. return Vec::new();
  829. };
  830. let first = offset / PAGE;
  831. let Some(touched) = pages.get(first..end.div_ceil(PAGE)) else {
  832. return Vec::new();
  833. };
  834. let slices: Vec<Option<Slice>> = {
  835. let table = page_table();
  836. touched.iter().map(|page| table.pages.get(page).cloned()).collect()
  837. };
  838. let mut pieces: Vec<(usize, usize)> = Vec::new();
  839. {
  840. let shown = SHOWN.read().unwrap_or_else(|e| e.into_inner());
  841. for (i, slice) in slices.iter().enumerate() {
  842. let Some(slice) = slice else { continue };
  843. // The bytes of this page that the write covers.
  844. let lo = if i == 0 { offset % PAGE } else { 0 };
  845. let hi = (end - (first + i) * PAGE).min(PAGE);
  846. pieces.extend(shown.at(slice).into_iter().map(|(at, _)| (at + lo, hi - lo)));
  847. }
  848. }
  849. pieces.sort_unstable();
  850. let mut runs: Vec<(usize, usize)> = Vec::new();
  851. for (at, bytes) in pieces {
  852. match runs.last_mut() {
  853. Some((start, n)) if *start + *n == at => *n += bytes,
  854. _ => runs.push((at, bytes)),
  855. }
  856. }
  857. runs
  858. }
  859. /// DirectStorage has put bytes `[offset, offset + len)` of `pages` into
  860. /// memory, through a view of our own: the GPU side is told where the title
  861. /// sees them, so that what it copied there before they arrived (a texture
  862. /// uploaded when its view was written holds whatever the pages held then)
  863. /// is copied again. Call when the bytes are there.
  864. /// `VICTORY_STREAM_NOTICE=0`: not told; what is then done is
  865. /// `VICTORY_PAGE_WRITES`' to say (`victory_gpu::title_memory_written`).
  866. pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) {
  867. if len == 0 {
  868. return;
  869. }
  870. for (at, bytes) in shown_at(pages, offset, len) {
  871. if stream_notice() {
  872. victory_gpu::kernel_will_write(at, bytes);
  873. } else {
  874. victory_gpu::title_memory_written(at, bytes, true);
  875. }
  876. }
  877. }
  878. /// What the title's mapping calls cost since the last asking, for the
  879. /// streaming log, counted only while that log is on: calls, pages,
  880. /// milliseconds in all, the longest one's and waiting for the lock; the same
  881. /// of the GPU's page-mapping copies ([`map_alias`]; calls and milliseconds);
  882. /// and by system call (unmap, split, map, commit) how many and their
  883. /// milliseconds.
  884. static MAPPING: [std::sync::atomic::AtomicU64; 15] = [const { std::sync::atomic::AtomicU64::new(0) }; 15];
  885. pub(crate) fn map_costs() -> Option<String> {
  886. let n: [u64; 15] = std::array::from_fn(|i| MAPPING[i].swap(0, Ordering::Relaxed));
  887. let time = |i: usize| matches!(i, 2 | 3 | 4 | 6 | 8 | 10 | 12 | 14);
  888. (n[0] + n[5] > 0).then(|| {
  889. let all: Vec<String> = n
  890. .iter()
  891. .enumerate()
  892. .map(|(i, &n)| if time(i) { n / 1_000_000 } else { n })
  893. .map(|n| n.to_string())
  894. .collect();
  895. all.join("\t")
  896. })
  897. }
  898. /// The system calls that change a mapping, as [`MAPPING`] counts them.
  899. #[derive(Clone, Copy)]
  900. enum Call {
  901. Unmap = 7,
  902. Split = 9,
  903. Map = 11,
  904. Commit = 13,
  905. }
  906. /// Runs `f`, a system call, and counts it while the streaming log is on.
  907. fn counted<T>(call: Call, f: impl FnOnce() -> T) -> T {
  908. if !super::dstorage::stream_log::on() {
  909. return f();
  910. }
  911. let started = std::time::Instant::now();
  912. let done = f();
  913. MAPPING[call as usize].fetch_add(1, Ordering::Relaxed);
  914. MAPPING[call as usize + 1].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
  915. done
  916. }
  917. /// Counts a mapping call when dropped.
  918. struct Costed {
  919. started: std::time::Instant,
  920. /// `None`: a copy of mappings.
  921. pages: Option<usize>,
  922. waited: u64,
  923. }
  924. impl Costed {
  925. fn begin(pages: Option<usize>) -> Option<Costed> {
  926. super::dstorage::stream_log::on().then(|| Costed { started: std::time::Instant::now(), pages, waited: 0 })
  927. }
  928. }
  929. impl Drop for Costed {
  930. fn drop(&mut self) {
  931. let ns = self.started.elapsed().as_nanos() as u64;
  932. let Some(pages) = self.pages else {
  933. MAPPING[5].fetch_add(1, Ordering::Relaxed);
  934. MAPPING[6].fetch_add(ns, Ordering::Relaxed);
  935. return;
  936. };
  937. for (i, n) in [1, pages as u64, ns].into_iter().enumerate() {
  938. MAPPING[i].fetch_add(n, Ordering::Relaxed);
  939. }
  940. MAPPING[3].fetch_max(ns, Ordering::Relaxed);
  941. MAPPING[4].fetch_add(self.waited, Ordering::Relaxed);
  942. }
  943. }
  944. /// Whether a mapping change asks the host only for what it needs: no split
  945. /// of a placeholder that is already the view's own, no commit of section
  946. /// pages that are committed (`VICTORY_MAP_LEAN=0`: both every time, as
  947. /// before).
  948. ///
  949. /// All of the title's streaming goes through one thread, which maps the
  950. /// pages of a batch and then submits it. Each call waits for the process's
  951. /// one address-space lock, behind the guards' and the driver's: 200 to 400
  952. /// us a page in the world against 10 in a menu, 2 to 4 s of every 5 s of
  953. /// that thread (runs stream-1 and -2; all six stacks taken of it in the
  954. /// opening were in these calls), so that models came as fast as their pages
  955. /// could be mapped. A page took up to four calls (unmap, split, map,
  956. /// commit), twice: the title maps a page into its pool and then has the GPU
  957. /// map it into its tiled heap.
  958. fn lean() -> bool {
  959. static ON: LazyLock<bool> = LazyLock::new(|| std::env::var_os("VICTORY_MAP_LEAN").is_none_or(|v| v != "0"));
  960. *ON
  961. }
  962. /// The title's streaming thread runs below normal priority, as do sixteen
  963. /// workers of ours when pipelines are made; on the console nothing else
  964. /// wants its core. Called where that thread maps and submits: lifts a
  965. /// thread that is below normal to above it (`VICTORY_STREAM_PRIORITY=0`:
  966. /// left as the title set it).
  967. pub(crate) fn lift_thread() {
  968. use windows_sys::Win32::System::Threading::{
  969. GetCurrentThread, GetThreadPriority, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
  970. };
  971. static ON: LazyLock<bool> =
  972. LazyLock::new(|| std::env::var_os("VICTORY_STREAM_PRIORITY").is_none_or(|v| v != "0"));
  973. if !*ON {
  974. return;
  975. }
  976. // SAFETY: plain calls on this thread.
  977. unsafe {
  978. let thread = GetCurrentThread();
  979. if matches!(GetThreadPriority(thread), -2..0) {
  980. SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL);
  981. }
  982. }
  983. }
  984. /// Maps `n` pages at `address`, in place of what is mapped there; null
  985. /// `pages` unmaps. Returns `address`, or null if a page or the host fails.
  986. pub extern "system" fn XMemMapPhysicalPages(
  987. address: *mut c_void,
  988. n: usize,
  989. pages: *const usize,
  990. ) -> *mut c_void {
  991. let base = address as usize;
  992. // Read before any lock is taken: a fault in title memory may wait for
  993. // the mapping call that holds them.
  994. // SAFETY: the title passes `n` page numbers, or null.
  995. let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec());
  996. let mut costed = Costed::begin(Some(n));
  997. let mut physical = physical();
  998. if let Some(costed) = &mut costed {
  999. costed.waited = costed.started.elapsed().as_nanos() as u64;
  1000. }
  1001. // Until the pages are mapped again: `unmap` takes whole views away and
  1002. // maps what stays of them again, and a mapped view is a reservation
  1003. // until it is committed. A read of title memory in place must not fall
  1004. // into that gap (`victory_gpu::title_memory_remapping`).
  1005. let _changing = victory_gpu::title_memory_remapping();
  1006. unmap(&mut physical, base, n * PAGE);
  1007. let Some(pages) = pages else {
  1008. return address;
  1009. };
  1010. let slices: Vec<Option<Slice>> = {
  1011. let table = page_table();
  1012. pages.iter().map(|page| table.pages.get(page).cloned()).collect()
  1013. };
  1014. let mut i = 0;
  1015. while i < n {
  1016. let Some(first) = slices[i].clone() else {
  1017. tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page");
  1018. return std::ptr::null_mut();
  1019. };
  1020. // One view per run of consecutive slices of one section.
  1021. let run = 1 + slices[i + 1..]
  1022. .iter()
  1023. .zip(1..)
  1024. .take_while(|&(slice, k)| {
  1025. slice.as_ref().is_some_and(|s| {
  1026. Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k
  1027. })
  1028. })
  1029. .count();
  1030. if !map(&mut physical, base + i * PAGE, run * PAGE, first) {
  1031. return std::ptr::null_mut();
  1032. }
  1033. i += run;
  1034. }
  1035. address
  1036. }
  1037. /// One page at each address; null `pages`, or a page number 0, unmaps
  1038. /// (the title passes 0 for addresses to clear).
  1039. pub extern "system" fn XMemMapPhysicalPagesScatter(
  1040. addresses: *const *mut c_void,
  1041. n: usize,
  1042. pages: *const usize,
  1043. ) -> BOOL {
  1044. if addresses.is_null() {
  1045. return 0;
  1046. }
  1047. lift_thread();
  1048. if side_by_side() > 1 && n > 1 {
  1049. // Read before any lock is taken, as in `XMemMapPhysicalPages`.
  1050. let wanted: Vec<(usize, usize)> = (0..n)
  1051. // SAFETY: the title passes `n` addresses and, unless null, `n` pages.
  1052. .map(|i| unsafe { (*addresses.add(i) as usize, if pages.is_null() { 0 } else { *pages.add(i) }) })
  1053. .collect();
  1054. if wanted.iter().all(|w| w.0 % PAGE == 0) {
  1055. return scatter(&wanted).into();
  1056. }
  1057. }
  1058. for i in 0..n {
  1059. // SAFETY: the title passes `n` addresses and, unless null, `n` pages.
  1060. let (address, page) = unsafe {
  1061. (
  1062. *addresses.add(i),
  1063. if pages.is_null() || *pages.add(i) == 0 {
  1064. std::ptr::null()
  1065. } else {
  1066. pages.add(i)
  1067. },
  1068. )
  1069. };
  1070. if XMemMapPhysicalPages(address, 1, page).is_null() {
  1071. return 0;
  1072. }
  1073. }
  1074. 1
  1075. }
  1076. /// Maps the physical pages shown at `[from, from + len)` at `to` as well,
  1077. /// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping
  1078. /// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`):
  1079. /// the title maps pages into a pool view, then has the GPU map them into its tiled
  1080. /// heap. Page by page; false if a source page is not mapped physical memory.
  1081. pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
  1082. let (to, from, len) = (to as usize, from as usize, len as usize);
  1083. let _costed = Costed::begin(None);
  1084. let mut physical = physical();
  1085. // As in `XMemMapPhysicalPages`: no read in place meets the gap.
  1086. let _changing = victory_gpu::title_memory_remapping();
  1087. unmap(&mut physical, to, len);
  1088. for k in (0..len).step_by(PAGE) {
  1089. if from == 0 {
  1090. break;
  1091. }
  1092. let at = from + k;
  1093. let Some(slice) = physical.slice_at(at) else {
  1094. return false;
  1095. };
  1096. if !map(&mut physical, to + k, PAGE, slice) {
  1097. return false;
  1098. }
  1099. }
  1100. true
  1101. }
  1102. /// [`map_alias`] of many ranges, in order.
  1103. pub fn map_aliases(ranges: &[(u64, u64, u64)]) -> bool {
  1104. let _costed = Costed::begin(None);
  1105. lift_thread();
  1106. if side_by_side() <= 1 {
  1107. return ranges.iter().all(|&(to, from, len)| map_alias(to, from, len));
  1108. }
  1109. // By the page: the address, and the one whose page it is to show.
  1110. let pages: Vec<(usize, Option<usize>)> = ranges
  1111. .iter()
  1112. .flat_map(|&(to, from, len)| {
  1113. (0..len as usize).step_by(PAGE).map(move |k| (to as usize + k, (from != 0).then_some(from as usize + k)))
  1114. })
  1115. .collect();
  1116. if pages.iter().any(|p| p.0 % PAGE != 0 || p.1.is_some_and(|from| from % PAGE != 0)) {
  1117. return ranges.iter().all(|&(to, from, len)| map_alias(to, from, len));
  1118. }
  1119. let mut ok = true;
  1120. let mut at = 0;
  1121. while at < pages.len() {
  1122. let mut physical = physical();
  1123. let mut ops: Vec<Op> = Vec::new();
  1124. let mut touched = std::collections::HashSet::new();
  1125. for &(to, from) in &pages[at..] {
  1126. // A page the group changes already, or one it would be mapped
  1127. // from: after it.
  1128. if ops.len() == GROUP || touched.contains(&to) || from.is_some_and(|from| touched.contains(&from)) {
  1129. break;
  1130. }
  1131. let slice = from.map(|from| physical.slice_at(from));
  1132. ok &= !matches!(slice, Some(None));
  1133. touched.insert(to);
  1134. ops.push(Op::new(to, slice.flatten()));
  1135. at += 1;
  1136. }
  1137. let _changing = victory_gpu::title_memory_remapping();
  1138. ok &= change(&mut physical, ops);
  1139. }
  1140. ok
  1141. }
  1142. /// Maps (page number not 0) or unmaps each address; false if a page is not
  1143. /// the title's or the host refuses one.
  1144. fn scatter(wanted: &[(usize, usize)]) -> bool {
  1145. let mut ok = true;
  1146. let mut at = 0;
  1147. while at < wanted.len() {
  1148. let mut costed = Costed::begin(None);
  1149. let mut ops: Vec<Op> = Vec::new();
  1150. let mut physical = physical();
  1151. if let Some(costed) = &mut costed {
  1152. costed.waited = costed.started.elapsed().as_nanos() as u64;
  1153. }
  1154. {
  1155. let table = page_table();
  1156. let mut touched = std::collections::HashSet::new();
  1157. for &(to, page) in &wanted[at..] {
  1158. if ops.len() == GROUP || !touched.insert(to) {
  1159. break;
  1160. }
  1161. let slice = table.pages.get(&page).cloned();
  1162. if page != 0 && slice.is_none() {
  1163. tracing::warn!(page, "XMemMapPhysicalPagesScatter: unknown page");
  1164. ok = false;
  1165. }
  1166. ops.push(Op::new(to, slice));
  1167. at += 1;
  1168. }
  1169. }
  1170. if let Some(costed) = &mut costed {
  1171. costed.pages = Some(ops.len());
  1172. }
  1173. let _changing = victory_gpu::title_memory_remapping();
  1174. ok &= change(&mut physical, ops);
  1175. }
  1176. ok
  1177. }
  1178. /// Pages changed under the locks at once.
  1179. const GROUP: usize = 64;
  1180. /// How many threads map a group of pages side by side (`VICTORY_MAP_THREADS`;
  1181. /// 1: the caller alone, a page after the other, as before).
  1182. ///
  1183. /// Mapping and unmapping a view wait for a lock that every protection change
  1184. /// of a view takes too, and our guards make 100,000 of those a second, from
  1185. /// many threads, in the world: 0.2 to 4 ms a page. One thread stands in that
  1186. /// queue once at a time. In a bench (60,000 views, five threads changing
  1187. /// protections) one thread mapped 1,500 pages a second, eight 30,000.
  1188. fn side_by_side() -> usize {
  1189. static THREADS: LazyLock<usize> = LazyLock::new(|| {
  1190. std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32)
  1191. });
  1192. *THREADS
  1193. }
  1194. /// A page of address space to unmap and, with a slice, map anew.
  1195. struct Op {
  1196. at: usize,
  1197. slice: Option<Slice>,
  1198. /// A view of this page alone is there, to be unmapped.
  1199. had: bool,
  1200. /// The placeholder is the page's own (or will be, after the unmapping).
  1201. own: bool,
  1202. }
  1203. impl Op {
  1204. fn new(at: usize, slice: Option<Slice>) -> Op {
  1205. Op { at, slice, had: false, own: false }
  1206. }
  1207. /// The system calls; whether the host did as asked.
  1208. fn run(&self) -> bool {
  1209. if self.had {
  1210. // SAFETY: a view we mapped; it becomes a placeholder again.
  1211. let gone = counted(Call::Unmap, || unsafe {
  1212. UnmapViewOfFile2(
  1213. GetCurrentProcess(),
  1214. MEMORY_MAPPED_VIEW_ADDRESS { Value: self.at as *mut c_void },
  1215. MEM_PRESERVE_PLACEHOLDER,
  1216. )
  1217. });
  1218. if gone == 0 {
  1219. return false;
  1220. }
  1221. }
  1222. let Some(slice) = &self.slice else {
  1223. return true;
  1224. };
  1225. show(self.at, PAGE, slice, self.own)
  1226. }
  1227. }
  1228. /// Does `ops`, each of another page, side by side: first what is noted of
  1229. /// the pages goes, then the system calls, then what is there now is noted.
  1230. /// With [`PHYSICAL`] and the change of mapping (`title_memory_remapping`)
  1231. /// held.
  1232. fn change(physical: &mut Physical, mut ops: Vec<Op>) -> bool {
  1233. for op in &mut ops {
  1234. let there = physical
  1235. .views
  1236. .range(..=op.at)
  1237. .next_back()
  1238. .filter(|(base, view)| op.at < **base + view.0)
  1239. .map(|(base, view)| (*base, view.0));
  1240. match there {
  1241. Some((base, PAGE)) if base == op.at => {
  1242. if let Some((size, slice)) = physical.views.remove(&op.at) {
  1243. shown_mut().forget(op.at, size, &slice);
  1244. }
  1245. victory_gpu::title_memory_unmapping(op.at, PAGE);
  1246. physical.holes.remove(&op.at);
  1247. (op.had, op.own) = (true, lean());
  1248. }
  1249. // Part of a larger view.
  1250. Some(_) => {
  1251. unmap(physical, op.at, PAGE);
  1252. }
  1253. None => {}
  1254. }
  1255. if op.had {
  1256. continue;
  1257. }
  1258. op.own = physical.holes.remove(&op.at) == Some(PAGE) && lean();
  1259. if op.slice.is_some() && !op.own {
  1260. // Cut out of a larger placeholder here, not side by side: a
  1261. // thread that maps a piece while others cut the same one can
  1262. // fail.
  1263. split(op.at, PAGE);
  1264. op.own = true;
  1265. }
  1266. }
  1267. let done = pool::all(ops);
  1268. let mut ok = true;
  1269. for (op, done) in done {
  1270. match op.slice {
  1271. Some(slice) if done => {
  1272. // As in `map`.
  1273. shown_mut().note(op.at, PAGE, &slice);
  1274. victory_gpu::title_memory_remapped(op.at, PAGE);
  1275. victory_gpu::title_memory_view(op.at, PAGE, slice.section.handle as usize, (slice.index * PAGE) as u64);
  1276. physical.views.insert(op.at, (PAGE, slice));
  1277. }
  1278. None if op.had && done => {
  1279. physical.holes.insert(op.at, PAGE);
  1280. }
  1281. _ => ok &= done,
  1282. }
  1283. }
  1284. ok
  1285. }
  1286. /// The threads that do the system calls of [`change`].
  1287. mod pool {
  1288. use std::collections::VecDeque;
  1289. use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
  1290. use std::sync::{Arc, Condvar, Mutex, OnceLock};
  1291. use super::{Op, side_by_side};
  1292. struct Batch {
  1293. ops: Vec<(Op, AtomicBool)>,
  1294. next: AtomicUsize,
  1295. /// Ops not done yet.
  1296. left: AtomicUsize,
  1297. over: (Mutex<bool>, Condvar),
  1298. }
  1299. impl Batch {
  1300. /// Does ops until none is left to begin.
  1301. fn work(&self) {
  1302. loop {
  1303. let i = self.next.fetch_add(1, Ordering::Relaxed);
  1304. let Some((op, done)) = self.ops.get(i) else {
  1305. return;
  1306. };
  1307. done.store(op.run(), Ordering::Release);
  1308. if self.left.fetch_sub(1, Ordering::AcqRel) == 1 {
  1309. *self.over.0.lock().unwrap_or_else(|e| e.into_inner()) = true;
  1310. self.over.1.notify_all();
  1311. }
  1312. }
  1313. }
  1314. }
  1315. struct Pool {
  1316. batches: Mutex<VecDeque<Arc<Batch>>>,
  1317. more: Condvar,
  1318. }
  1319. fn pool() -> &'static Pool {
  1320. static POOL: OnceLock<Pool> = OnceLock::new();
  1321. static STARTED: std::sync::Once = std::sync::Once::new();
  1322. let pool = POOL.get_or_init(|| Pool { batches: Mutex::default(), more: Condvar::new() });
  1323. STARTED.call_once(|| {
  1324. let started = (1..side_by_side())
  1325. .filter(|i| std::thread::Builder::new().name(format!("mapping {i}")).spawn(|| serve(pool)).is_ok())
  1326. .count();
  1327. tracing::info!(started, "threads that map pages side by side (VICTORY_MAP_THREADS=1: none)");
  1328. });
  1329. pool
  1330. }
  1331. fn serve(pool: &Pool) {
  1332. use windows_sys::Win32::System::Threading::{
  1333. GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
  1334. };
  1335. // SAFETY: a plain call on our own thread.
  1336. unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) };
  1337. let mut batches = pool.batches.lock().unwrap_or_else(|e| e.into_inner());
  1338. loop {
  1339. let Some(batch) = batches.front().cloned() else {
  1340. batches = pool.more.wait(batches).unwrap_or_else(|e| e.into_inner());
  1341. continue;
  1342. };
  1343. if batch.next.load(Ordering::Relaxed) >= batch.ops.len() {
  1344. // All begun: nobody needs to see it any more.
  1345. if batches.front().is_some_and(|b| Arc::ptr_eq(b, &batch)) {
  1346. batches.pop_front();
  1347. }
  1348. continue;
  1349. }
  1350. drop(batches);
  1351. batch.work();
  1352. batches = pool.batches.lock().unwrap_or_else(|e| e.into_inner());
  1353. }
  1354. }
  1355. /// Runs `ops`; each with whether the host did it.
  1356. pub(super) fn all(ops: Vec<Op>) -> Vec<(Op, bool)> {
  1357. // Waking the others takes longer than a few quick calls.
  1358. if ops.len() < 3 {
  1359. return ops
  1360. .into_iter()
  1361. .map(|op| {
  1362. let done = op.run();
  1363. (op, done)
  1364. })
  1365. .collect();
  1366. }
  1367. let n = ops.len();
  1368. let batch = Arc::new(Batch {
  1369. ops: ops.into_iter().map(|op| (op, AtomicBool::new(false))).collect(),
  1370. next: AtomicUsize::new(0),
  1371. left: AtomicUsize::new(n),
  1372. over: Default::default(),
  1373. });
  1374. let pool = pool();
  1375. pool.batches.lock().unwrap_or_else(|e| e.into_inner()).push_back(batch.clone());
  1376. if n > side_by_side() {
  1377. pool.more.notify_all();
  1378. } else {
  1379. (1..n).for_each(|_| pool.more.notify_one());
  1380. }
  1381. batch.work();
  1382. let mut over = batch.over.0.lock().unwrap_or_else(|e| e.into_inner());
  1383. while !*over {
  1384. over = batch.over.1.wait(over).unwrap_or_else(|e| e.into_inner());
  1385. }
  1386. drop(over);
  1387. // No worker changes it any more (one may still hold it for a moment).
  1388. batch
  1389. .ops
  1390. .iter()
  1391. .map(|(op, done)| {
  1392. let op = Op { at: op.at, slice: op.slice.clone(), had: op.had, own: op.own };
  1393. (op, done.load(Ordering::Acquire))
  1394. })
  1395. .collect()
  1396. }
  1397. }
  1398. /// Maps `slice` and the slices after it over `[base, base + len)`, which
  1399. /// must lie in one placeholder.
  1400. fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
  1401. let own = physical.holes.remove(&base) == Some(len) && lean();
  1402. if !show(base, len, &slice, own) {
  1403. return false;
  1404. }
  1405. // Noted before the GPU side is told: bytes DirectStorage put in earlier,
  1406. // without notice at these addresses ([`pages_written`]), are there by
  1407. // the time the copies of them go.
  1408. shown_mut().note(base, len, &slice);
  1409. // New contents, read-write: the GPU side's copies no longer guard it.
  1410. victory_gpu::title_memory_remapped(base, len);
  1411. // What the range shows now, for the GPU side's in-place census.
  1412. victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64);
  1413. physical.views.insert(base, (len, slice));
  1414. true
  1415. }
  1416. /// Cuts `[base, base + len)` out of the placeholder it is in (which fails
  1417. /// harmlessly when the range is the whole placeholder).
  1418. fn split(base: usize, len: usize) {
  1419. // SAFETY: acts only on a placeholder.
  1420. counted(Call::Split, || unsafe {
  1421. VirtualFree(
  1422. base as *mut c_void,
  1423. len,
  1424. MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
  1425. )
  1426. });
  1427. }
  1428. /// The system calls of [`map`]; `own`: the placeholder at `base` is `len`
  1429. /// long already.
  1430. fn show(base: usize, len: usize, slice: &Slice, own: bool) -> bool {
  1431. let map_view = || {
  1432. // SAFETY: maps the section over a placeholder; acts only on one.
  1433. counted(Call::Map, || unsafe {
  1434. MapViewOfFile3(
  1435. slice.section.handle,
  1436. GetCurrentProcess(),
  1437. base as *const c_void,
  1438. (slice.index * PAGE) as u64,
  1439. len,
  1440. MEM_REPLACE_PLACEHOLDER,
  1441. PAGE_READWRITE,
  1442. std::ptr::null_mut(),
  1443. 0,
  1444. )
  1445. })
  1446. };
  1447. let mut view = if own { map_view() } else { MEMORY_MAPPED_VIEW_ADDRESS { Value: std::ptr::null_mut() } };
  1448. if view.Value as usize != base {
  1449. split(base, len);
  1450. view = map_view();
  1451. }
  1452. if view.Value as usize != base {
  1453. tracing::warn!(
  1454. address = format_args!("{base:#x}"),
  1455. len,
  1456. error = %std::io::Error::last_os_error(),
  1457. "mapping physical pages failed (not a placeholder?)"
  1458. );
  1459. return false;
  1460. }
  1461. if !slice.section.commit_shown(slice.index, base, len) {
  1462. // SAFETY: the view just mapped, back to a placeholder.
  1463. unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
  1464. return false;
  1465. }
  1466. true
  1467. }
  1468. /// Commits the section pages a view shows (once per page, whichever view).
  1469. fn commit(base: usize, len: usize) -> bool {
  1470. if on_wine() {
  1471. return true; // sections are committed whole there
  1472. }
  1473. // SAFETY: `[base, base + len)` is a view of a reserved section.
  1474. if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() {
  1475. return true;
  1476. }
  1477. commit_refused(len, "physical pages", std::io::Error::last_os_error());
  1478. false
  1479. }
  1480. /// Reports memory the host would not give: at the Windows commit limit to
  1481. /// `crashes.log`, since the title usually faults soon after on the null it
  1482. /// gets; otherwise as a warning.
  1483. fn commit_refused(len: usize, what: &str, error: std::io::Error) {
  1484. if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) {
  1485. let mut info = PERFORMANCE_INFORMATION {
  1486. cb: size_of::<PERFORMANCE_INFORMATION>() as u32,
  1487. ..Default::default()
  1488. };
  1489. // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION.
  1490. let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0;
  1491. victory_loader::log_crash(&commit_limit_message(
  1492. len,
  1493. what,
  1494. &error,
  1495. queried.then_some(&info),
  1496. ));
  1497. } else {
  1498. tracing::warn!(len, %error, "committing {what} failed");
  1499. }
  1500. }
  1501. fn commit_limit_message(
  1502. len: usize,
  1503. what: &str,
  1504. error: &std::io::Error,
  1505. info: Option<&PERFORMANCE_INFORMATION>,
  1506. ) -> String {
  1507. let mut message = format!(
  1508. "VIctory: Windows commit limit reached while committing {len} bytes of {what}: {error}.\n"
  1509. );
  1510. if let Some(info) = info {
  1511. use std::fmt::Write;
  1512. let committed = info.CommitTotal * info.PageSize / MIB;
  1513. let limit = info.CommitLimit * info.PageSize / MIB;
  1514. let _ = writeln!(
  1515. message,
  1516. "System commit: {committed} MiB of {limit} MiB in use."
  1517. );
  1518. }
  1519. message.push_str(
  1520. "Close other applications or increase the Windows paging file size, then retry.\n",
  1521. );
  1522. message
  1523. }
  1524. /// Returns `[base, base + len)` to placeholders; views reaching past it
  1525. /// are mapped again outside it.
  1526. fn unmap(physical: &mut Physical, base: usize, len: usize) {
  1527. // No bytes: no view to return. The search below would still find the
  1528. // view holding `base` and cut it in two there, and its range of views
  1529. // starting inside would run backwards (which `BTreeMap` panics on).
  1530. if len == 0 {
  1531. return;
  1532. }
  1533. let end = base + len;
  1534. // Views do not overlap: the one holding `base`, then those starting
  1535. // inside (the GPU's page mappings make one view per page).
  1536. let first = physical
  1537. .views
  1538. .range(..=base)
  1539. .next_back()
  1540. .filter(|(at, (size, _))| *at + size > base)
  1541. .map(|(at, _)| *at);
  1542. let hit: Vec<usize> = first
  1543. .into_iter()
  1544. .chain(physical.views.range(base + 1..end).map(|(at, _)| *at))
  1545. .collect();
  1546. for at in hit {
  1547. let Some((size, slice)) = physical.views.remove(&at) else {
  1548. continue;
  1549. };
  1550. shown_mut().forget(at, size, &slice);
  1551. if at < base || at + size > end {
  1552. // Parts of it stay, and are mapped again below.
  1553. victory_gpu::title_memory_splitting(at, size);
  1554. }
  1555. victory_gpu::title_memory_unmapping(at, size);
  1556. // SAFETY: a view we mapped; it becomes a placeholder again.
  1557. let gone = counted(Call::Unmap, || unsafe {
  1558. UnmapViewOfFile2(
  1559. GetCurrentProcess(),
  1560. MEMORY_MAPPED_VIEW_ADDRESS {
  1561. Value: at as *mut c_void,
  1562. },
  1563. MEM_PRESERVE_PLACEHOLDER,
  1564. )
  1565. });
  1566. if gone != 0 && at >= base && at + size <= end {
  1567. physical.holes.insert(at, size);
  1568. }
  1569. if at < base {
  1570. map(physical, at, base - at, slice.clone());
  1571. }
  1572. if at + size > end {
  1573. let index = slice.index + (end - at) / PAGE;
  1574. map(physical, end, at + size - end, Slice { index, ..slice });
  1575. }
  1576. }
  1577. }
  1578. /// The oldest layout we know; newer titles pass other flag values (Minecraft
  1579. /// 0x20000001) and read the same leading fields.
  1580. #[repr(C)]
  1581. #[derive(Debug, Default)]
  1582. pub struct WorkingSet {
  1583. pub title_limit: usize,
  1584. pub title_used: usize,
  1585. pub tools_limit: usize,
  1586. pub tools_used: usize,
  1587. pub stack_used: u32,
  1588. pub physical_pages: u32,
  1589. pub gpu_optimal_limit: usize,
  1590. pub gpu_optimal_used: usize,
  1591. pub tools_gpu_optimal_limit: usize,
  1592. pub tools_gpu_optimal_used: usize,
  1593. pub kernel_pool_used: u32,
  1594. pub kernel_pool_limit: u32,
  1595. }
  1596. /// The title's budget and our process's commit as what it uses. No tools
  1597. /// memory: a retail console.
  1598. // shortcut: all fields are filled whatever the flags ask for, and use is
  1599. // not split by bandwidth class (GPU-optimal use reads 0); track
  1600. // allocations per class if a title budgets from that field.
  1601. pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL {
  1602. if out.is_null() {
  1603. return 0;
  1604. }
  1605. let mut counters = PROCESS_MEMORY_COUNTERS {
  1606. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  1607. ..Default::default()
  1608. };
  1609. // SAFETY: our own process and a sized structure.
  1610. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
  1611. let (gpu_optimal, standard) = victory_gpu::console::current().title_memory();
  1612. let stats = WorkingSet {
  1613. title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed),
  1614. title_used: counters.PagefileUsage,
  1615. gpu_optimal_limit: gpu_optimal,
  1616. ..Default::default()
  1617. };
  1618. // What the title is told, logged at the first asking and at every
  1619. // 1,024th: "used" is all the process has committed, the layer's own
  1620. // memory and the card's included (27 GB in run 60's gameplay against a
  1621. // limit of 13.5 GB). A title that budgets its streaming from these two
  1622. // figures believes it is far over its limit.
  1623. // shortcut: the figure is not yet the title's own memory alone (its
  1624. // heaps and the pages it mapped); count those if this line shows the
  1625. // title asking.
  1626. static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1627. let asked = ASKED.fetch_add(1, Ordering::Relaxed);
  1628. if asked.is_multiple_of(1024) {
  1629. tracing::info!(
  1630. asked = asked + 1,
  1631. which = _which,
  1632. limit_mb = stats.title_limit >> 20,
  1633. used_mb = stats.title_used >> 20,
  1634. "the title asks how much memory it uses"
  1635. );
  1636. }
  1637. // SAFETY: checked non-null; the title passes room for the structure.
  1638. unsafe { out.write(stats) };
  1639. 1
  1640. }
  1641. /// Hands title memory (standard, in 2 MiB pages) to the system. The other
  1642. /// transfers involve tools memory, which a retail console has none of.
  1643. pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
  1644. const TITLE_TO_SYSTEM: u32 = 0;
  1645. tracing::info!(kind, size, "XMemTransferMemory");
  1646. if size == 0 {
  1647. return 1;
  1648. }
  1649. let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
  1650. return 0;
  1651. };
  1652. let standard = victory_gpu::console::current().title_memory().1;
  1653. let moved = kind == TITLE_TO_SYSTEM
  1654. && TRANSFERRED
  1655. .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
  1656. t.checked_add(size).filter(|&t| t <= standard)
  1657. })
  1658. .is_ok();
  1659. moved.into()
  1660. }
  1661. /// The title's own `VirtualFree`. What the GPU side noted of the memory goes
  1662. /// first: the address may be other memory's the moment it is free.
  1663. extern "system" fn title_virtual_free(address: *mut c_void, size: usize, kind: u32) -> BOOL {
  1664. const MEM_COALESCE_PLACEHOLDERS: u32 = 1;
  1665. // Splitting and joining placeholders changes nothing they show.
  1666. if kind & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS) == 0 {
  1667. victory_gpu::title_memory_freed(address as usize, size);
  1668. }
  1669. // SAFETY: the title's own arguments.
  1670. unsafe { VirtualFree(address, size, kind) }
  1671. }
  1672. pub(crate) fn module() -> HleModule {
  1673. HleModule {
  1674. name: "xmem",
  1675. dlls: &["xmem.dll", "kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-*"],
  1676. exports: vec![
  1677. crate::HleExport { name: "VirtualFree", address: title_virtual_free as *const () as usize },
  1678. hle_export!(XMemAlloc),
  1679. hle_export!(XMemFree),
  1680. hle_export!(XMemAllocDefault),
  1681. hle_export!(XMemFreeDefault),
  1682. hle_export!(XMemIsToolsMemAvailable),
  1683. hle_export!(XMemAllocatePhysicalPages),
  1684. hle_export!(XMemFreePhysicalPages),
  1685. hle_export!(XMemMapPhysicalPages),
  1686. hle_export!(XMemMapPhysicalPagesScatter),
  1687. hle_export!(XMemVirtualAlloc),
  1688. hle_export!(XMemVirtualQuery),
  1689. hle_export!(XMemGetWorkingSetStatistics),
  1690. hle_export!(XMemTransferMemory),
  1691. ],
  1692. }
  1693. }
  1694. #[cfg(test)]
  1695. mod tests {
  1696. use super::*;
  1697. fn query(address: *const c_void) -> BasicInformation {
  1698. // SAFETY: plain data; zero is a valid value.
  1699. let mut info: BasicInformation = unsafe { std::mem::zeroed() };
  1700. // SAFETY: a pseudo handle needs no closing.
  1701. let process = unsafe { GetCurrentProcess() };
  1702. assert_eq!(XMemVirtualQuery(process, address, &mut info), 1);
  1703. info
  1704. }
  1705. #[test]
  1706. fn alloc_honours_alignment_and_frees() {
  1707. for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] {
  1708. let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type
  1709. let p = XMemAlloc(100, attributes);
  1710. assert!(!p.is_null());
  1711. assert_eq!(p as usize % align, 0, "field {field:#x}");
  1712. // SAFETY: 100 bytes were allocated.
  1713. unsafe { p.cast::<u8>().write_bytes(0xab, 100) };
  1714. XMemFree(p, attributes);
  1715. }
  1716. let p = XMemAlloc(4096, ALLOC_32BIT);
  1717. assert!(!p.is_null() && (p as usize) < 1 << 32);
  1718. XMemFree(p, ALLOC_32BIT);
  1719. }
  1720. #[test]
  1721. fn virtual_alloc_meets_console_constraints() {
  1722. const GPU_READ_WRITE: u32 = 0x2000;
  1723. let p = XMemVirtualAlloc(
  1724. std::ptr::null_mut(),
  1725. 4 * MIB,
  1726. PAGES_2M | MEM_RESERVE | MEM_COMMIT,
  1727. GRAPHICS | 7 << 12, // 40-bit addresses
  1728. PAGE_READWRITE | GPU_READ_WRITE,
  1729. );
  1730. assert!(!p.is_null());
  1731. assert_eq!(p as usize % (2 * MIB), 0);
  1732. assert!((p as usize) < 1 << 40);
  1733. let info = query(p);
  1734. assert_eq!(info.host.State, MEM_COMMIT);
  1735. assert_eq!(info.host.Protect, PAGE_READWRITE);
  1736. assert_eq!(info.flags & GRAPHICS, GRAPHICS);
  1737. // Write-watched, for the GPU side's copies.
  1738. let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0);
  1739. // SAFETY: room for `count` addresses.
  1740. let watched = unsafe {
  1741. windows_sys::Win32::System::Memory::GetWriteWatch(
  1742. 0,
  1743. p,
  1744. 4 * MIB,
  1745. found.as_mut_ptr().cast(),
  1746. &mut count,
  1747. &mut granularity,
  1748. )
  1749. };
  1750. assert_eq!(watched, 0);
  1751. // SAFETY: our own reservation.
  1752. assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
  1753. assert_eq!(query(p).flags, 0);
  1754. // No address field: above the 32-bit range and below 2^40, where
  1755. // the console keeps it.
  1756. let p = XMemVirtualAlloc(
  1757. std::ptr::null_mut(),
  1758. 16 << 30,
  1759. MEM_RESERVE,
  1760. GRAPHICS,
  1761. PAGE_NOACCESS,
  1762. );
  1763. assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}");
  1764. assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}");
  1765. // SAFETY: our own reservation.
  1766. assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
  1767. }
  1768. #[test]
  1769. fn transfers_shrink_the_title_budget() {
  1770. let mut before = WorkingSet::default();
  1771. assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1);
  1772. assert!(before.title_used > 0);
  1773. assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1);
  1774. assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory");
  1775. let standard = victory_gpu::console::current().title_memory().1;
  1776. assert_eq!(XMemTransferMemory(0, standard), 0, "over budget");
  1777. let mut after = WorkingSet::default();
  1778. XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
  1779. assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
  1780. }
  1781. #[test]
  1782. fn statistics_have_the_console_layout() {
  1783. assert_eq!(size_of::<WorkingSet>(), 0x50);
  1784. assert_eq!(size_of::<BasicInformation>(), 0x40);
  1785. assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
  1786. }
  1787. #[test]
  1788. fn commit_limit_report_includes_request_and_system_commit() {
  1789. let error = std::io::Error::from_raw_os_error(ERROR_COMMITMENT_LIMIT as i32);
  1790. let info = PERFORMANCE_INFORMATION {
  1791. CommitTotal: 512,
  1792. CommitLimit: 768,
  1793. PageSize: 4096,
  1794. ..Default::default()
  1795. };
  1796. let report = commit_limit_message(4 * MIB, "physical pages", &error, Some(&info));
  1797. assert!(report.contains("4194304 bytes of physical pages"));
  1798. assert!(report.contains("2 MiB of 3 MiB in use"));
  1799. let fallback = commit_limit_message(4 * MIB, "virtual memory", &error, None);
  1800. assert!(fallback.contains("4194304 bytes of virtual memory"));
  1801. for report in [&report, &fallback] {
  1802. assert!(report.contains("os error 1455"));
  1803. assert!(report.contains("Windows paging file size"));
  1804. }
  1805. assert!(!fallback.contains("System commit:"));
  1806. }
  1807. #[test]
  1808. fn physical_pages_map_alias_and_unmap() {
  1809. let mut pages = [0usize; 3];
  1810. let mut n = 3;
  1811. assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
  1812. assert_eq!(n, 3);
  1813. // Packed into 21 bits as `number >> 4`, as the title keeps them.
  1814. for p in pages {
  1815. assert_eq!((p >> 4 & 0x1f_ffff) << 4, p);
  1816. }
  1817. // Reservations of 64 KiB pages, as titles make them for mapping.
  1818. let reserve = || {
  1819. XMemVirtualAlloc(
  1820. std::ptr::null_mut(),
  1821. 3 * PAGE,
  1822. MEM_RESERVE | PAGES_64K,
  1823. 0,
  1824. PAGE_READWRITE,
  1825. )
  1826. };
  1827. let (a, b) = (reserve(), reserve());
  1828. assert!(!a.is_null() && !b.is_null());
  1829. let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE);
  1830. assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
  1831. // The same page at a second address shows the same bytes.
  1832. assert_eq!(
  1833. XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()),
  1834. at(b, 1)
  1835. );
  1836. // SAFETY: both pages are mapped read-write.
  1837. unsafe {
  1838. at(a, 2).cast::<u8>().write(7);
  1839. assert_eq!(at(b, 1).cast::<u8>().read(), 7);
  1840. a.cast::<u8>().write(1);
  1841. }
  1842. // Writes into pages (DirectStorage's) show through their views.
  1843. assert!(write_physical(&pages[2..], 1, &[9]));
  1844. // SAFETY: mapped read-write.
  1845. assert_eq!(unsafe { at(b, 1).cast::<u8>().add(1).read() }, 9);
  1846. // Unmapping the middle page keeps its neighbours.
  1847. assert_eq!(
  1848. XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()),
  1849. at(a, 1)
  1850. );
  1851. assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
  1852. assert_eq!(query(a).host.State, MEM_COMMIT);
  1853. assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT);
  1854. // SAFETY: still mapped.
  1855. assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 7);
  1856. // A scattered page lands in the hole.
  1857. let addresses = [at(a, 1)];
  1858. assert_eq!(
  1859. XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()),
  1860. 1
  1861. );
  1862. // SAFETY: page 0 is now mapped at both `a` and `a + PAGE`.
  1863. assert_eq!(unsafe { at(a, 1).cast::<u8>().read() }, 1);
  1864. // Page number 0 unmaps.
  1865. assert_eq!(
  1866. XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()),
  1867. 1
  1868. );
  1869. assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE);
  1870. // The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`.
  1871. assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64));
  1872. // SAFETY: mapped read-write.
  1873. assert_eq!(unsafe { b.cast::<u8>().read() }, 7);
  1874. assert!(map_alias(b as u64, 0, PAGE as u64));
  1875. assert_eq!(query(b).host.State, MEM_RESERVE);
  1876. assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64));
  1877. assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
  1878. assert_eq!(XMemIsToolsMemAvailable(), 0);
  1879. }
  1880. /// A thread that reads a mapped page in place, as the GPU side reads a
  1881. /// texture, never meets the moment in which the runtime has taken the
  1882. /// page's view away to map it again: mapping the same pages at the same
  1883. /// address unmaps the view and maps a new one, and without the lock the
  1884. /// reader faults on a page "reserved, never committed" (the crashes of
  1885. /// runs 71 and 74).
  1886. #[test]
  1887. fn a_read_in_place_never_meets_the_gap_of_a_remapping() {
  1888. use std::sync::atomic::{AtomicBool, Ordering};
  1889. let mut pages = [0usize; 3];
  1890. let mut n = 3;
  1891. assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
  1892. let a = XMemVirtualAlloc(
  1893. std::ptr::null_mut(),
  1894. 3 * PAGE,
  1895. MEM_RESERVE | PAGES_64K,
  1896. 0,
  1897. PAGE_READWRITE,
  1898. );
  1899. assert!(!a.is_null());
  1900. assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
  1901. // SAFETY: mapped read-write.
  1902. unsafe { a.cast::<u8>().write(1) };
  1903. let first = a as usize;
  1904. let stop = std::sync::Arc::new(AtomicBool::new(false));
  1905. let reader = {
  1906. let stop = stop.clone();
  1907. std::thread::spawn(move || {
  1908. let mut reads = 0u64;
  1909. // (Once at least: the mapping thread may be done before this
  1910. // one's first turn.)
  1911. while reads == 0 || !stop.load(Ordering::Relaxed) {
  1912. let _reading = victory_gpu::title_memory_reading();
  1913. // SAFETY: the page is mapped whenever no change of
  1914. // mapping is under way, and none is while `_reading`
  1915. // is held.
  1916. assert_eq!(unsafe { (first as *const u8).read_volatile() }, 1);
  1917. reads += 1;
  1918. }
  1919. reads
  1920. })
  1921. };
  1922. for _ in 0..2000 {
  1923. // The same pages at the same address: the view goes and comes
  1924. // back, with the same bytes.
  1925. assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
  1926. }
  1927. stop.store(true, Ordering::Relaxed);
  1928. assert!(reader.join().expect("the reader never faulted") > 0);
  1929. assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a);
  1930. assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
  1931. }
  1932. /// A title thread that reads and writes a page of a view while other
  1933. /// pages of the view are unmapped and mapped again, as the console lets
  1934. /// it: the page was never given up.
  1935. #[test]
  1936. fn a_title_thread_goes_on_using_the_rest_of_a_view() {
  1937. use std::sync::atomic::{AtomicBool, Ordering};
  1938. let pages = allocate(4);
  1939. for _ in 0..200 {
  1940. // A new reservation each time: the pieces of a view cut up stay
  1941. // cut up.
  1942. let a = XMemVirtualAlloc(
  1943. std::ptr::null_mut(),
  1944. 4 * PAGE,
  1945. MEM_RESERVE | PAGES_64K,
  1946. 0,
  1947. PAGE_READWRITE,
  1948. );
  1949. assert!(!a.is_null());
  1950. assert_eq!(XMemMapPhysicalPages(a, 4, pages.as_ptr()), a);
  1951. let (first, stop) = (a as usize, AtomicBool::new(false));
  1952. // SAFETY: mapped read-write.
  1953. unsafe { (first as *mut u64).write_volatile(0) };
  1954. std::thread::scope(|s| {
  1955. let title = s.spawn(|| {
  1956. let mut n = 0u64;
  1957. // SAFETY (the block): the first page is the title's all
  1958. // the time; a fault would end the process.
  1959. unsafe {
  1960. while !stop.load(Ordering::Relaxed) {
  1961. assert_eq!((first as *const u64).read_volatile(), n);
  1962. n += 1;
  1963. (first as *mut u64).write_volatile(n);
  1964. }
  1965. }
  1966. n
  1967. });
  1968. // SAFETY: as above.
  1969. while !title.is_finished() && unsafe { (first as *const u64).read_volatile() } < 100 {}
  1970. for page in [3, 2, 1] {
  1971. let at = a.wrapping_byte_add(page * PAGE);
  1972. assert_eq!(XMemMapPhysicalPages(at, 1, std::ptr::null()), at);
  1973. assert_eq!(XMemMapPhysicalPages(at, 1, pages[page..].as_ptr()), at);
  1974. }
  1975. stop.store(true, Ordering::Relaxed);
  1976. assert!(title.join().expect("the title's thread never faulted") > 0);
  1977. });
  1978. assert_eq!(XMemMapPhysicalPages(a, 4, std::ptr::null()), a);
  1979. }
  1980. assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1);
  1981. }
  1982. /// Many pages in one call: mapped, moved over each other's addresses,
  1983. /// given twice in one list, copied by the GPU's mappings and unmapped.
  1984. #[test]
  1985. fn a_scatter_of_many_pages_is_what_one_after_the_other_is() {
  1986. const N: usize = 200;
  1987. let pages = allocate(N);
  1988. let a = XMemVirtualAlloc(std::ptr::null_mut(), 2 * N * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE) as usize;
  1989. let at = |k: usize| (a + k * PAGE) as *mut c_void;
  1990. let first = |k: usize| at(k).cast::<u64>();
  1991. for round in 0..4_usize {
  1992. // Every address shows another page each round.
  1993. let to: Vec<*mut c_void> = (0..N).map(|i| at((i + 7 * round) % N)).collect();
  1994. assert_eq!(XMemMapPhysicalPagesScatter(to.as_ptr(), N, pages.as_ptr()), 1);
  1995. for i in 0..N {
  1996. // SAFETY: mapped read-write.
  1997. unsafe {
  1998. if round > 0 {
  1999. assert_eq!(first((i + 7 * round) % N).read(), (1000 * (round - 1) + i) as u64);
  2000. }
  2001. first((i + 7 * round) % N).write((1000 * round + i) as u64);
  2002. }
  2003. }
  2004. }
  2005. // The GPU's copies of the mappings, in ranges and one by one; a page
  2006. // mapped from one the same call has mapped shows the same.
  2007. let half = (N / 2 * PAGE) as u64;
  2008. let (from, to) = (a as u64, at(N) as u64);
  2009. assert!(map_aliases(&[(to, from, half), (to + half, to, half)]));
  2010. for k in 0..N / 2 {
  2011. // SAFETY: mapped read-write.
  2012. unsafe {
  2013. assert_eq!(first(N + k).read(), first(k).read());
  2014. assert_eq!(first(N + N / 2 + k).read(), first(k).read());
  2015. first(N + k).write(5);
  2016. assert_eq!(first(k).read(), 5);
  2017. }
  2018. }
  2019. // An address twice: the last one counts; page 0 unmaps.
  2020. let to = [at(0), at(1), at(0), at(2), at(3), at(0)];
  2021. let what = [pages[5], pages[6], 0, 0, pages[7], pages[8]];
  2022. assert_eq!(XMemMapPhysicalPagesScatter(to.as_ptr(), 6, what.as_ptr()), 1);
  2023. assert_eq!(query(at(2)).host.State, MEM_RESERVE);
  2024. // SAFETY: mapped read-write; the same page at both.
  2025. unsafe {
  2026. first(0).write(77);
  2027. assert_eq!(XMemMapPhysicalPagesScatter([at(2), at(4), at(6)].as_ptr(), 3, [pages[8]; 3].as_ptr()), 1);
  2028. assert_eq!((first(2).read(), first(4).read(), first(6).read()), (77, 77, 77));
  2029. }
  2030. // A page the title does not own.
  2031. assert_eq!(XMemMapPhysicalPagesScatter([at(0), at(1)].as_ptr(), 2, [pages[0], 1].as_ptr()), 0);
  2032. // All gone, also parts of a larger view.
  2033. assert_eq!(XMemMapPhysicalPages(at(0), 4, std::ptr::null()), at(0));
  2034. // SAFETY: placeholders of ours, nothing mapped in them.
  2035. unsafe { VirtualFree(at(0), 4 * PAGE, MEM_RELEASE | 1 /* MEM_COALESCE_PLACEHOLDERS */) };
  2036. assert_eq!(XMemMapPhysicalPages(at(0), 4, pages.as_ptr()), at(0));
  2037. assert!(map_aliases(&[(a as u64, 0, (2 * N * PAGE) as u64)]));
  2038. assert!((0..2 * N).all(|k| query(at(k)).host.State == MEM_RESERVE));
  2039. assert!(physical().views.range(a..a + 2 * N * PAGE).next().is_none());
  2040. assert_eq!(XMemFreePhysicalPages(N, pages.as_ptr()), 1);
  2041. }
  2042. /// Pages keep what they hold however often they are mapped, moved and
  2043. /// unmapped without a commit or a split of their own.
  2044. #[test]
  2045. fn pages_mapped_again_hold_what_they_held() {
  2046. let pages = allocate(3);
  2047. let a = XMemVirtualAlloc(std::ptr::null_mut(), 8 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE);
  2048. assert!(!a.is_null());
  2049. let at = |k: usize| a.wrapping_byte_add(k * PAGE);
  2050. for round in 0..6_usize {
  2051. for (k, page) in pages.iter().enumerate() {
  2052. let to = at((round + 2 * k) % 8);
  2053. assert_eq!(XMemMapPhysicalPages(to, 1, page), to);
  2054. let first = to.cast::<u64>();
  2055. // SAFETY: mapped read-write; the far end of the page too.
  2056. unsafe {
  2057. if round > 0 {
  2058. assert_eq!(first.read(), (round * 16 + k - 16) as u64);
  2059. assert_eq!(first.add(PAGE / 8 - 1).read(), k as u64);
  2060. }
  2061. first.write((round * 16 + k) as u64);
  2062. first.add(PAGE / 8 - 1).write(k as u64);
  2063. }
  2064. }
  2065. for k in 0..pages.len() {
  2066. let to = at((round + 2 * k) % 8);
  2067. assert_eq!(XMemMapPhysicalPages(to, 1, std::ptr::null()), to);
  2068. assert_eq!(query(to).host.State, MEM_RESERVE);
  2069. }
  2070. // The title joins what it unmapped: the next view splits it anew.
  2071. if round == 3 {
  2072. // SAFETY: placeholders of ours, nothing mapped in them.
  2073. unsafe {
  2074. VirtualFree(a, 8 * PAGE, MEM_RELEASE | 1 /* MEM_COALESCE_PLACEHOLDERS */)
  2075. };
  2076. }
  2077. }
  2078. assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
  2079. }
  2080. #[test]
  2081. fn mapping_no_pages_changes_nothing() {
  2082. let pages = allocate(2);
  2083. let a = XMemVirtualAlloc(
  2084. std::ptr::null_mut(),
  2085. 2 * PAGE,
  2086. MEM_RESERVE | PAGES_64K,
  2087. 0,
  2088. PAGE_READWRITE,
  2089. );
  2090. assert!(!a.is_null());
  2091. assert_eq!(XMemMapPhysicalPages(a, 2, pages.as_ptr()), a);
  2092. // SAFETY: both pages are mapped read-write.
  2093. unsafe { a.cast::<u8>().write(5) };
  2094. let second = a.wrapping_byte_add(PAGE);
  2095. // A count of 0 at the start of a view, inside it and past it: with
  2096. // pages, without (an unmap), and as the GPU's page-mapping copy.
  2097. for at in [a, second, a.wrapping_byte_add(2 * PAGE)] {
  2098. assert_eq!(XMemMapPhysicalPages(at, 0, pages.as_ptr()), at);
  2099. assert_eq!(XMemMapPhysicalPages(at, 0, std::ptr::null()), at);
  2100. assert!(map_alias(at as u64, a as u64, 0));
  2101. assert!(map_alias(at as u64, 0, 0));
  2102. }
  2103. // The view is still the one view it was.
  2104. let view = physical().views.get(&(a as usize)).map(|v| v.0);
  2105. assert_eq!(view, Some(2 * PAGE));
  2106. assert_eq!(query(a).host.State, MEM_COMMIT);
  2107. assert_eq!(query(second).host.State, MEM_COMMIT);
  2108. // SAFETY: still mapped.
  2109. assert_eq!(unsafe { a.cast::<u8>().read() }, 5);
  2110. // A count of 1 still unmaps that page alone.
  2111. assert_eq!(XMemMapPhysicalPages(second, 1, std::ptr::null()), second);
  2112. assert_eq!(query(second).host.State, MEM_RESERVE);
  2113. assert_eq!(query(a).host.State, MEM_COMMIT);
  2114. assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a);
  2115. assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1);
  2116. }
  2117. /// What a title that maps and unmaps pages all the time costs the
  2118. /// workers that write others: 24 threads look pages up, fill one and
  2119. /// tell of it, as a request does, while one maps.
  2120. /// `cargo test --release -p victory-hle --lib map_bench -- --ignored --nocapture`
  2121. #[test]
  2122. #[ignore = "a benchmark"]
  2123. fn map_bench() {
  2124. use std::sync::atomic::AtomicU64;
  2125. use std::time::{Duration, Instant};
  2126. let pages = allocate(1024);
  2127. let a = XMemVirtualAlloc(std::ptr::null_mut(), 1024 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE) as usize;
  2128. for mapping in [false, true] {
  2129. let (done, waited, worst, maps) =
  2130. (AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0));
  2131. let until = Instant::now() + Duration::from_secs(3);
  2132. std::thread::scope(|s| {
  2133. if mapping {
  2134. s.spawn(|| {
  2135. let at: Vec<*mut c_void> = (0..256).map(|i| (a + i * PAGE) as *mut c_void).collect();
  2136. while Instant::now() < until {
  2137. assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 256, pages.as_ptr()), 1);
  2138. assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 256, std::ptr::null()), 1);
  2139. maps.fetch_add(512, Ordering::Relaxed);
  2140. }
  2141. });
  2142. }
  2143. for t in 0..24 {
  2144. let (pages, done, waited, worst) = (&pages, &done, &waited, &worst);
  2145. s.spawn(move || {
  2146. let mut i = 256 + t * 16;
  2147. while Instant::now() < until {
  2148. let page = &pages[i..=i];
  2149. i = if i == 256 + t * 16 + 15 { 256 + t * 16 } else { i + 1 };
  2150. let began = Instant::now();
  2151. assert!(pages_known(page, 0, PAGE));
  2152. let mut window = page_window(page, 0, PAGE).unwrap();
  2153. let looked = began.elapsed();
  2154. window.bytes().fill(t as u8);
  2155. let began = Instant::now();
  2156. pages_written(page, 0, PAGE);
  2157. let took = (looked + began.elapsed()).as_nanos() as u64;
  2158. waited.fetch_add(took, Ordering::Relaxed);
  2159. worst.fetch_max(took, Ordering::Relaxed);
  2160. done.fetch_add(1, Ordering::Relaxed);
  2161. }
  2162. });
  2163. }
  2164. });
  2165. let n = done.load(Ordering::Relaxed).max(1);
  2166. println!(
  2167. "mapping {mapping}: {:.0} requests/s, {:.1} us of each on lookups and notices (worst {:.1} ms); {:.0} maps/s",
  2168. n as f64 / 3.0,
  2169. waited.load(Ordering::Relaxed) as f64 / n as f64 / 1e3,
  2170. worst.load(Ordering::Relaxed) as f64 / 1e6,
  2171. maps.load(Ordering::Relaxed) as f64 / 3.0
  2172. );
  2173. }
  2174. assert_eq!(XMemFreePhysicalPages(1024, pages.as_ptr()), 1);
  2175. }
  2176. /// `n` pages of one new allocation.
  2177. fn allocate(n: usize) -> Vec<usize> {
  2178. let (mut pages, mut given) = (vec![0; n], n);
  2179. assert_eq!(
  2180. XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()),
  2181. 1
  2182. );
  2183. assert_eq!(given, n);
  2184. pages
  2185. }
  2186. /// The bytes of one page, through a view of our own.
  2187. fn page_bytes(page: usize) -> Vec<u8> {
  2188. let slice = page_table().pages.get(&page).cloned().expect("known page");
  2189. View::map(&slice, 1).expect("mapped").bytes().to_vec()
  2190. }
  2191. #[test]
  2192. fn runs_group_consecutive_pages_of_one_allocation() {
  2193. let (a, b) = (allocate(3), allocate(1));
  2194. let lengths = |pages: &[usize], offset, len| {
  2195. runs(pages, offset, len).map(|r| r.iter().map(|&(_, n)| n).collect::<Vec<_>>())
  2196. };
  2197. assert_eq!(lengths(&a, 0, 3 * PAGE), Some(vec![3]));
  2198. // Only the pages the bytes reach.
  2199. assert_eq!(lengths(&a, PAGE + 5, 10), Some(vec![1]));
  2200. assert_eq!(lengths(&a, PAGE - 1, 2), Some(vec![2]));
  2201. assert_eq!(lengths(&a, 0, 0), Some(vec![]));
  2202. // Out of order, or across allocations: one run each.
  2203. assert_eq!(
  2204. lengths(&[a[0], a[2], a[1]], 0, 3 * PAGE),
  2205. Some(vec![1, 1, 1])
  2206. );
  2207. assert_eq!(lengths(&[a[1], a[2], b[0]], 0, 3 * PAGE), Some(vec![2, 1]));
  2208. // A slice that follows on in another section starts a run.
  2209. assert_eq!(lengths(&[b[0], a[1]], 0, 2 * PAGE), Some(vec![1, 1]));
  2210. // Too few pages for the bytes, or an unknown one.
  2211. assert_eq!(lengths(&a, 0, 3 * PAGE + 1), None);
  2212. assert_eq!(lengths(&[a[0], 0x10], 0, 2 * PAGE), None);
  2213. assert_eq!(lengths(&a, usize::MAX, 2), None);
  2214. assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1);
  2215. assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
  2216. }
  2217. #[test]
  2218. fn writes_cross_runs_and_allocations() {
  2219. let (a, b) = (allocate(2), allocate(1));
  2220. let pages = [a[0], a[1], b[0]];
  2221. let data: Vec<u8> = (0..2 * PAGE + 64).map(|i| (i * 7 % 251) as u8).collect();
  2222. let offset = PAGE - 32;
  2223. // Past the third page: the second run is too short.
  2224. assert!(!write_physical(&pages, offset, &data));
  2225. assert!(write_physical(&pages, offset, &data[..2 * PAGE]));
  2226. let seen: Vec<u8> = pages.iter().flat_map(|&p| page_bytes(p)).collect();
  2227. assert!(seen[..offset].iter().all(|&b| b == 0), "before the offset");
  2228. assert_eq!(seen[offset..offset + 2 * PAGE], data[..2 * PAGE]);
  2229. assert!(seen[offset + 2 * PAGE..].iter().all(|&b| b == 0), "after");
  2230. assert!(
  2231. !write_physical(&[a[0], 0x10], 0, &data[..PAGE + 1]),
  2232. "unknown page"
  2233. );
  2234. assert_eq!(XMemFreePhysicalPages(2, a.as_ptr()), 1);
  2235. assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
  2236. }
  2237. /// Pages say where the title has them mapped, byte for byte (after
  2238. /// fork PR #571's test; its runs are whole pages).
  2239. #[test]
  2240. fn pages_say_where_they_are_mapped() {
  2241. let pages = allocate(3);
  2242. let reserve = |n: usize| {
  2243. let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE);
  2244. assert!(!at.is_null());
  2245. at
  2246. };
  2247. // `b` keeps a page unmapped at either end, so that no run at `b`
  2248. // ever touches one at `a`, wherever the host puts the two.
  2249. let (a, b) = (reserve(3), reserve(4));
  2250. assert!(shown_at(&pages, 0, 3 * PAGE).is_empty(), "mapped nowhere");
  2251. // All three at `a`; the last two at `b`, from its second page on.
  2252. assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
  2253. let second = b.wrapping_byte_add(PAGE);
  2254. assert_eq!(XMemMapPhysicalPages(second, 2, pages[1..].as_ptr()), second);
  2255. let (a, second) = (a as usize, second as usize);
  2256. let sorted = |mut runs: Vec<(usize, usize)>| {
  2257. runs.sort_unstable();
  2258. runs
  2259. };
  2260. assert_eq!(shown_at(&pages, 0, PAGE), vec![(a, PAGE)]);
  2261. // A request for part of a page names those bytes alone.
  2262. assert_eq!(shown_at(&pages, 0x4000, 0x3000), vec![(a + 0x4000, 0x3000)]);
  2263. // Across two pages, shown at two addresses each: one run at each.
  2264. assert_eq!(
  2265. shown_at(&pages, PAGE + 1, PAGE),
  2266. sorted(vec![(a + PAGE + 1, PAGE), (second + 1, PAGE)])
  2267. );
  2268. // A page unmapped in the middle of a view: the rest still shows.
  2269. let middle = (a + PAGE) as *mut c_void;
  2270. assert_eq!(XMemMapPhysicalPages(middle, 1, std::ptr::null()), middle);
  2271. assert_eq!(
  2272. shown_at(&pages, 0, 3 * PAGE),
  2273. sorted(vec![(a, PAGE), (a + 2 * PAGE, PAGE), (second, 2 * PAGE)])
  2274. );
  2275. // Too few pages for the bytes: nothing (the write fails too).
  2276. assert!(shown_at(&pages, 0, 3 * PAGE + 1).is_empty());
  2277. for (at, n) in [(a, 3), (second, 2)] {
  2278. let at = at as *mut c_void;
  2279. assert_eq!(XMemMapPhysicalPages(at, n, std::ptr::null()), at);
  2280. }
  2281. assert!(shown_at(&pages, 0, 3 * PAGE).is_empty());
  2282. assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
  2283. }
  2284. #[test]
  2285. fn page_windows_cover_one_run_in_place() {
  2286. let (a, b) = (allocate(3), allocate(1));
  2287. let mut window = page_window(&a, PAGE + 3, PAGE).expect("one run");
  2288. assert_eq!(window.bytes().len(), PAGE);
  2289. window.bytes().fill(0x5a);
  2290. drop(window);
  2291. let (second, third) = (page_bytes(a[1]), page_bytes(a[2]));
  2292. assert!(second[..3].iter().all(|&b| b == 0));
  2293. assert!(second[3..].iter().all(|&b| b == 0x5a));
  2294. assert!(third[..3].iter().all(|&b| b == 0x5a));
  2295. assert!(third[3..].iter().all(|&b| b == 0));
  2296. // Several runs, or an unknown page: no window.
  2297. assert!(page_window(&[a[0], b[0]], 0, PAGE + 1).is_none());
  2298. assert!(page_window(&[a[1], a[0]], 0, PAGE + 1).is_none());
  2299. assert!(page_window(&[0x10], 0, 1).is_none());
  2300. // One page of several is still one run.
  2301. assert!(page_window(&[a[0], b[0]], 0, PAGE).is_some());
  2302. assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1);
  2303. assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
  2304. }
  2305. }