upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/xmem.cpp
diff options
context:
space:
mode:
authoraslan2142 <jan.trencansky@protonmail.com>2026-11-25 02:37:19 +0100
committerGitHub <noreply@github.com>2026-11-25 02:37:19 +0100
commit18a22c1aefa227fd2eda047bab3385147d569f9d (patch)
tree74ad707a670f980da61b5b9e0bc9241dfd6ef181 /runtime/shims/xmem.cpp
parent5a5df8e0b6bff458814c934e18f4216e69c40d36 (diff)
parent71a783e56fb6eb591849b5c9fb6618ed3af3f595 (diff)
Merge pull request #984 from Moriz82/integration/proton-story-load
[integration] Linux/Proton and native Windows: boot through the story load (RT-PROTON-STORY-LOAD)
Diffstat (limited to 'runtime/shims/xmem.cpp')
-rw-r--r--runtime/shims/xmem.cpp456
1 files changed, 394 insertions, 62 deletions
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index e5c5c4469..82d8142d0 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -18,6 +18,7 @@
18#include <malloc.h> 18#include <malloc.h>
19#include <psapi.h> 19#include <psapi.h>
20 20
21#include <algorithm>
21#include <atomic> 22#include <atomic>
22#include <cerrno> 23#include <cerrno>
23#include <cstdint> 24#include <cstdint>
@@ -38,6 +39,10 @@
38#include "shims.h" 39#include "shims.h"
39#include "startup_trace.h" 40#include "startup_trace.h"
40#include "xmem.h" 41#include "xmem.h"
42#include "../src/dstorage_trace.h"
43#include "../src/title_page_watch.h"
44#include "../src/title_geometry_watch.h"
45#include "../src/title_va_alias.h"
41 46
42namespace { 47namespace {
43 48
@@ -69,14 +74,29 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo
69 74
70void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); } 75void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); }
71 76
77// Every block and range the title gets here is recorded as the title's memory (src/title_va_alias.h): a shader
78// address into it can be given a GPU copy, and an address anywhere else cannot.
79void* title_block(size_t size) {
80 void* p = allocate_block(size);
81 if (p) leonida::title_memory_map::changed();
82 leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(p), size ? size : 1);
83 return p;
84}
85
86void free_title_block(void* p) {
87 if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast<uintptr_t>(p));
88 _aligned_free(p);
89 if (p) leonida::title_memory_map::changed();
90}
91
72void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { 92void* __stdcall XMemAlloc(size_t size, uint64_t attributes) {
73 note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); 93 note_attributes("XMemAlloc", attributes, size, _ReturnAddress());
74 return allocate_block(size); 94 return title_block(size);
75} 95}
76 96
77void __stdcall XMemFree(void* p, uint64_t attributes) { 97void __stdcall XMemFree(void* p, uint64_t attributes) {
78 note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); 98 note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress());
79 _aligned_free(p); 99 free_title_block(p);
80} 100}
81 101
82// XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks 102// XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks
@@ -85,12 +105,12 @@ void __stdcall XMemFree(void* p, uint64_t attributes) {
85// released by either free. 105// released by either free.
86void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { 106void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) {
87 note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); 107 note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress());
88 return allocate_block(size); 108 return title_block(size);
89} 109}
90 110
91void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { 111void __stdcall XMemFreeDefault(void* p, uint64_t attributes) {
92 note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); 112 note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress());
93 _aligned_free(p); 113 free_title_block(p);
94} 114}
95 115
96// BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach 116// BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach
@@ -281,13 +301,25 @@ std::map<uintptr_t, Window> g_windows; // base -> window
281std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing 301std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing
282std::vector<uint64_t> g_free_slots; 302std::vector<uint64_t> g_free_slots;
283uint64_t g_next_slot = 1; 303uint64_t g_next_slot = 1;
284struct MappedPage { 304// A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run
285 uint64_t page; 305// rather than per page: under Wine each view costs a placeholder split and a section map whose time grows with the
286 std::shared_ptr<Section> section; 306// number of views, and the retail title maps about 100,000 pages in one call.
287 uint64_t offset; 307struct View {
308 uint64_t count;
309 std::shared_ptr<Section> section; // kept for remapping part of the run after its pages are freed
310 uint64_t offset; // section offset of the first page
311 DWORD protect;
288}; 312};
289 313leonida::host_heap::map<uintptr_t, View> g_views; // view base -> view; host_heap: see g_fault_lock
290std::unordered_map<uintptr_t, MappedPage> g_mapped; 314
315// The views (g_views) as the fault handler reads them, which is all it reads: physical_page_fault takes it shared at
316// every access violation in the process, xmem's own or not, and so does commit_physical_range. A title thread can
317// take an access violation while it holds the process heap's lock (XMemAlloc is _aligned_malloc, so HeapAlloc and
318// HeapFree write block headers on the title's pages: a page waiting for its first touch, or one a D3D12 shadow
319// guards), and then waits here. So a thread that holds it exclusively must never wait for the process heap: it would
320// wait for the faulting thread, which waits for it. Everything allocated or freed under it comes from
321// leonida::host_heap (g_views, g_mapped, g_page_addresses, the sections, title_page_aliases), nothing under it logs,
322// and nothing under it reads title memory, which could fault into the handler on the same thread.
291SRWLOCK g_fault_lock = SRWLOCK_INIT; 323SRWLOCK g_fault_lock = SRWLOCK_INIT;
292 324
293struct FaultLockExclusive { 325struct FaultLockExclusive {
@@ -302,10 +334,41 @@ struct FaultLockShared {
302 ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } 334 ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); }
303 FaultLockShared(const FaultLockShared&) = delete; 335 FaultLockShared(const FaultLockShared&) = delete;
304 FaultLockShared& operator=(const FaultLockShared&) = delete; 336 FaultLockShared& operator=(const FaultLockShared&) = delete;
337
305}; 338};
306 339
307// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with 340// With g_phys_mutex held; changed under g_fault_lock too (unmap_range), so they allocate from host_heap.
308// kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. 341template <class K, class V>
342using HostUnorderedMap =
343 std::unordered_map<K, V, std::hash<K>, std::equal_to<K>, leonida::host_heap::Allocator<std::pair<const K, V>>>;
344using AddressSet = std::set<uintptr_t, std::less<uintptr_t>, leonida::host_heap::Allocator<uintptr_t>>;
345HostUnorderedMap<uintptr_t, uint64_t> g_mapped; // mapped 64 KiB address -> page number
346HostUnorderedMap<uint64_t, AddressSet> g_page_addresses; // page number -> the addresses it is mapped at
347
348// With g_phys_mutex held. Keeps leonida::title_page_aliases in step: a page mapped at two or more addresses is
349// aliased at each of them (the D3D12 layer's slot-133 shadows copy those pages at every submission instead of
350// waiting for a write fault, which a write through another address doesn't raise).
351void note_mapping(uint64_t page, uintptr_t address, bool mapped) {
352 auto& addresses = g_page_addresses[page];
353 if (mapped) {
354 addresses.insert(address);
355 } else {
356 addresses.erase(address);
357 leonida::title_page_aliases::set(address, false);
358 }
359 using namespace leonida::geometry_writes;
360 if (state().count.load(std::memory_order_acquire)) {
361 notify(address, address + kPhysicalPageSize, Event::mapping);
362 for (auto other : addresses)
363 if (other != address) notify(other, other + kPhysicalPageSize, Event::mapping);
364 }
365 const bool aliased = addresses.size() > 1;
366 for (const uintptr_t at : addresses) leonida::title_page_aliases::set(at, aliased);
367 if (addresses.empty()) g_page_addresses.erase(page);
368}
369
370// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions before
371// the host could hand the addresses out again.
309void record_window(void* base, SIZE_T size, DWORD protect) { 372void record_window(void* base, SIZE_T size, DWORD protect) {
310 const uintptr_t start = reinterpret_cast<uintptr_t>(base); 373 const uintptr_t start = reinterpret_cast<uintptr_t>(base);
311 const uintptr_t end = start + size; 374 const uintptr_t end = start + size;
@@ -337,7 +400,9 @@ bool isolate_placeholder(void* address, SIZE_T size) {
337 return false; 400 return false;
338 } 401 }
339 if (info.AllocationBase == address && info.RegionSize == size) return true; 402 if (info.AllocationBase == address && info.RegionSize == size) return true;
340 return VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != FALSE; 403 if (!VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) return false;
404 leonida::title_memory_map::changed();
405 return true;
341} 406}
342 407
343PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { 408PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) {
@@ -354,6 +419,43 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) {
354 PAGE_NOACCESS, parameter_count ? &parameter : nullptr, parameter_count); 419 PAGE_NOACCESS, parameter_count ? &parameter : nullptr, parameter_count);
355} 420}
356 421
422// A new ordinary reservation of the title's (MEM_RESERVE, not a placeholder, not physical, not large pages) is made
423// with MEM_WRITE_WATCH and recorded (leonida::title_write_watch): the D3D12 layer's shadows of these pages then ask the
424// kernel which pages were written instead of making them read-only and taking a fault at the title's first write.
425// `allocate(type)` makes the call. A host that refuses the flag gets the call without it, and the pages are guarded
426// as before; so are they with LEONIDA_WRITE_WATCH=0. A reservation the title asked to be write-watched itself is not
427// recorded: its bits are the title's (XMemGetWriteWatch).
428template <class Allocate>
429void* reserve_watched(DWORD type, const void* address, SIZE_T size, Allocate&& allocate) {
430 constexpr DWORD kNotWatchable = MEM_WRITE_WATCH | MEM_PHYSICAL | MEM_LARGE_PAGES | MEM_RESERVE_PLACEHOLDER |
431 MEM_REPLACE_PLACEHOLDER | MEM_RESET | MEM_RESET_UNDO;
432 // A commit at no given address reserves too.
433 const bool reserves = (type & MEM_RESERVE) || (!address && (type & MEM_COMMIT));
434 const bool watch = reserves && !(type & kNotWatchable) && leonida::title_write_watch::enabled();
435 void* result = allocate(watch ? type | MEM_RESERVE | MEM_WRITE_WATCH : type);
436 if (!watch) return result;
437 if (!result) return allocate(type);
438 // The reservation is [result, end of the requested range): VirtualAlloc rounds a given address down to 64 KiB.
439 const uintptr_t base = reinterpret_cast<uintptr_t>(result);
440 const uintptr_t end = (address ? reinterpret_cast<uintptr_t>(address) : base) + size;
441 leonida::title_write_watch::add(base, end - base);
442 return result;
443}
444
445// After a successful call that changes pages of an existing reservation without a write the kernel would see (a
446// commit, which may bring back decommitted pages as zeros; MEM_RESET; a decommit with `decommit`): if it is
447// write-watched, the shadows take [address, address + size) as written (size 0: to the reservation's end).
448void note_unwatched_change(const void* address, SIZE_T size, DWORD type, bool decommit) {
449 if (!address || !(decommit || (type & (MEM_COMMIT | MEM_RESET | MEM_RESET_UNDO))) || (type & MEM_RESERVE)) return;
450 const auto from = reinterpret_cast<uintptr_t>(address);
451 const uintptr_t to = size ? from + size : leonida::title_write_watch::end_of(from);
452 if (to > from) {
453 leonida::title_write_watch::mark(from, to);
454 leonida::geometry_writes::notify(from, to, decommit ? leonida::geometry_writes::Event::replaced
455 : leonida::geometry_writes::Event::mapping);
456 }
457}
458
357// PVOID XMemVirtualAlloc(address, size, allocationType, attributes, protect). All 23 calls of the measured title pass a 459// PVOID XMemVirtualAlloc(address, size, allocationType, attributes, protect). All 23 calls of the measured title pass a
358// nonzero attribute word; its bits are not decoded and nothing on the host depends on them, so it is accepted and only 460// nonzero attribute word; its bits are not decoded and nothing on the host depends on them, so it is accepted and only
359// recorded (xmem_attributes). Its types cover committed 2 MiB and 64 KiB pages, reserve-only 64 KiB windows for physical pages, one 461// recorded (xmem_attributes). Its types cover committed 2 MiB and 64 KiB pages, reserve-only 64 KiB windows for physical pages, one
@@ -361,8 +463,39 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) {
361// XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay 463// XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay
362// 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through 464// 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through
363// VirtualAlloc2. 465// VirtualAlloc2.
466void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect);
467
364void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { 468void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) {
365 note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress()); 469 note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress());
470 void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect);
471 // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which
472 // the copy also checks.
473 if (result) {
474 leonida::title_memory_map::changed();
475 leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(result), size);
476 note_unwatched_change(address, size, allocation_type, false);
477 if (allocation_type & MEM_RESERVE) {
478 const auto from = reinterpret_cast<uintptr_t>(result);
479 leonida::geometry_writes::notify(from, from + size, leonida::geometry_writes::Event::replaced);
480 }
481 }
482 // A reservation: a GPU-only one (no CPU access, PAGE_GRAPHICS_* bits) is paired with the CPU-mappable one of the
483 // same size made just before it (src/title_page_watch.h, title_gpu_views).
484 const DWORD host_type = allocation_type & kXmemHostAllocationTypeMask;
485 if (result && host_type && !(host_type & MEM_COMMIT)) {
486 const bool gpu_only = (protect & kPageGraphicsMask) && host_protect(protect) == PAGE_NOACCESS;
487 if (leonida::title_gpu_views::note_reservation(reinterpret_cast<uintptr_t>(result), size, gpu_only))
488 std::fprintf(stderr, "[rt] xmem: GPU-only view %p (%llu MiB, protect 0x%lx) reads at the CPU view %p\n",
489 result, static_cast<unsigned long long>(size >> 20), static_cast<unsigned long>(protect),
490 reinterpret_cast<void*>(leonida::title_gpu_views::to_cpu(reinterpret_cast<uintptr_t>(result))));
491 else if (gpu_only && size >= (64u << 20))
492 std::fprintf(stderr, "[rt] xmem: GPU-only reservation %p (%llu MiB, protect 0x%lx) has no CPU view\n", result,
493 static_cast<unsigned long long>(size >> 20), static_cast<unsigned long>(protect));
494 }
495 return result;
496}
497
498void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) {
366 if (size == 0) { 499 if (size == 0) {
367 SetLastError(ERROR_INVALID_PARAMETER); 500 SetLastError(ERROR_INVALID_PARAMETER);
368 return nullptr; 501 return nullptr;
@@ -460,25 +593,96 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
460 MEM_EXTENDED_PARAMETER parameter{}; 593 MEM_EXTENDED_PARAMETER parameter{};
461 parameter.Type = MemExtendedParameterAddressRequirements; 594 parameter.Type = MemExtendedParameterAddressRequirements;
462 parameter.Pointer = &requirements; 595 parameter.Pointer = &requirements;
463 return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, host_type | MEM_RESERVE, host_prot, 596 return reserve_watched(host_type | MEM_RESERVE, nullptr, size, [&](DWORD type) {
464 &parameter, 1); 597 return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, type, host_prot, &parameter, 1);
598 });
465 } 599 }
466 return VirtualAlloc(address, size, host_type, host_prot); 600 return reserve_watched(host_type, address, size,
601 [&](DWORD type) { return VirtualAlloc(address, size, type, host_prot); });
467} 602}
468 603
469// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. 604// With g_phys_mutex held. Maps `view` at the 64 KiB-aligned `address`, which holds no mapped page. MEM_REPLACE_PLACEHOLDER
470bool unmap_page(uintptr_t address) { 605// needs the view to fill one placeholder exactly, and earlier partial unmaps can leave several host placeholders in one
471 const FaultLockExclusive lock; 606// run, so the run is mapped as one view per placeholder it spans. Views are capped at kMaxViewPages so that unmapping a
472 const auto it = g_mapped.find(address); 607// page inside a long run only remaps the rest of one capped view, not the whole run.
473 if (it == g_mapped.end()) return true; 608constexpr uint64_t kMaxViewPages = 1024; // 64 MiB
474 if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(address), 609
475 MEM_PRESERVE_PLACEHOLDER)) { 610
476 return false; 611bool map_view(uintptr_t address, const View& view) {
612 for (uint64_t mapped = 0; mapped < view.count;) {
613 const uintptr_t base = address + mapped * kPhysicalPageSize;
614 void* const target = reinterpret_cast<void*>(base);
615 MEMORY_BASIC_INFORMATION info{};
616 if (!VirtualQuery(target, &info, sizeof(info)) || info.State != MEM_RESERVE ||
617 info.RegionSize < kPhysicalPageSize) {
618 SetLastError(ERROR_INVALID_ADDRESS);
619 return false;
620 }
621 const uint64_t available = info.RegionSize / kPhysicalPageSize;
622 const uint64_t remaining = view.count - mapped;
623 const uint64_t count = (std::min)({available, remaining, kMaxViewPages});
624 const SIZE_T size = static_cast<SIZE_T>(count * kPhysicalPageSize);
625 const uint64_t offset = view.offset + mapped * kPhysicalPageSize;
626 if (!isolate_placeholder(target, size)) return false;
627 if (!placeholder_api().map_view3(view.section->handle, GetCurrentProcess(), target, offset, size,
628 MEM_REPLACE_PLACEHOLDER, view.protect, nullptr, 0)) {
629 return false;
630 }
631 leonida::title_memory_map::changed();
632 g_views.emplace(base, View{count, view.section, offset, view.protect});
633 mapped += count;
634 }
635 return true;
636}
637
638// With g_phys_mutex held. Unmaps every page in [start, end); the addresses become placeholders again. A view that
639// reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so neighbours keep
640// their pages.
641// There is no rollback: if mapping a remainder again fails, those neighbouring pages stay unmapped and the caller only
642// sees the failure.
643bool unmap_range(uintptr_t start, uintptr_t end) {
644 const FaultLockExclusive lock; // faults on neighbouring pages wait through the split and remap
645 auto it = g_views.upper_bound(start);
646 if (it != g_views.begin()) {
647 const auto prev = std::prev(it);
648 if (prev->first + prev->second.count * kPhysicalPageSize > start) it = prev;
649 }
650 while (it != g_views.end() && it->first < end) {
651 const uintptr_t base = it->first;
652 const View view = it->second;
653 const uintptr_t view_end = base + view.count * kPhysicalPageSize;
654 if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(base),
655 MEM_PRESERVE_PLACEHOLDER)) {
656 return false;
657 }
658 leonida::title_memory_map::changed();
659 leonida::geometry_writes::notify(base, view_end, leonida::geometry_writes::Event::replaced);
660 it = g_views.erase(it);
661 // The pages of [start, end) this view held are unmapped now; the ones outside it are mapped again below.
662 for (uintptr_t at = (std::max)(base, start); at < (std::min)(view_end, end); at += kPhysicalPageSize) {
663 if (const auto mapped = g_mapped.find(at); mapped != g_mapped.end()) {
664 note_mapping(mapped->second, at, false);
665 g_mapped.erase(mapped);
666 }
667 }
668 if (base < start) {
669 View left = view;
670 left.count = (start - base) / kPhysicalPageSize;
671 if (!map_view(base, left)) return false;
672 }
673 if (view_end > end) {
674 const uint64_t skipped = (end - base) / kPhysicalPageSize;
675 View right = view;
676 right.count = view.count - skipped;
677 right.offset += skipped * kPhysicalPageSize;
678 return map_view(end, right); // the last view the range touches
679 }
477 } 680 }
478 g_mapped.erase(it);
479 return true; 681 return true;
480} 682}
481 683
684bool unmap_page(uintptr_t address) { return unmap_range(address, address + kPhysicalPageSize); }
685
482// With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was 686// With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was
483// mapped there. The caller has found the window. 687// mapped there. The caller has found the window.
484bool map_page(uintptr_t address, uint64_t page, DWORD protect) { 688bool map_page(uintptr_t address, uint64_t page, DWORD protect) {
@@ -489,22 +693,23 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) {
489 SetLastError(ERROR_INVALID_PARAMETER); 693 SetLastError(ERROR_INVALID_PARAMETER);
490 return false; 694 return false;
491 } 695 }
492 void* const target = reinterpret_cast<void*>(address); 696 {
493 if (!isolate_placeholder(target, kPhysicalPageSize)) return false; 697 const FaultLockExclusive lock;
494 const FaultLockExclusive lock; 698 if (!map_view(address, View{1, it->second.section, it->second.offset, protect})) return false;
495 void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, 699 }
496 it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, 700 g_mapped[address] = page;
497 protect, nullptr, 0); 701 note_mapping(page, address, true);
498 if (!view) return false;
499 g_mapped[address] = MappedPage{page, it->second.section, it->second.offset};
500 return true; 702 return true;
501} 703}
502 704
503enum class PageCommit { not_ours, committed_before, committed_now, failed }; 705enum class PageCommit { not_ours, committed_before, committed_now, failed };
504 706
505PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { 707PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) {
506 const auto it = g_mapped.find(address); 708 auto it = g_views.upper_bound(address);
507 if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; 709 if (it == g_views.begin()) return PageCommit::not_ours;
710 --it;
711 const uintptr_t within = address - it->first;
712 if (within / kPhysicalPageSize >= it->second.count || !it->second.section->scratch) return PageCommit::not_ours;
508 MEMORY_BASIC_INFORMATION info{}; 713 MEMORY_BASIC_INFORMATION info{};
509 if (!VirtualQuery(reinterpret_cast<void*>(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { 714 if (!VirtualQuery(reinterpret_cast<void*>(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) {
510 return PageCommit::not_ours; 715 return PageCommit::not_ours;
@@ -513,9 +718,11 @@ PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& prot
513 protect = info.Protect; 718 protect = info.Protect;
514 return PageCommit::committed_before; 719 return PageCommit::committed_before;
515 } 720 }
516 void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset; 721 void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset + within;
517 return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now 722 if (!VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return PageCommit::failed;
518 : PageCommit::failed; 723 leonida::geometry_writes::notify(address, address + kPhysicalPageSize, leonida::geometry_writes::Event::mapping);
724 leonida::title_memory_map::changed();
725 return PageCommit::committed_now;
519} 726}
520 727
521bool access_allowed(DWORD protect, ULONG_PTR access) { 728bool access_allowed(DWORD protect, ULONG_PTR access) {
@@ -632,7 +839,8 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count,
632 *page_count = 0; 839 *page_count = 0;
633 return FALSE; 840 return FALSE;
634 } 841 }
635 const auto section = std::make_shared<Section>(handle); 842 // From host_heap: the unmap that drops the last reference frees it under g_fault_lock.
843 const auto section = std::allocate_shared<Section>(leonida::host_heap::Allocator<Section>{}, handle);
636 if (!section->scratch) { 844 if (!section->scratch) {
637 *page_count = 0; 845 *page_count = 0;
638 return FALSE; 846 return FALSE;
@@ -665,12 +873,14 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra
665 for (uint64_t i = 0; i < page_count; ++i) { 873 for (uint64_t i = 0; i < page_count; ++i) {
666 const auto it = g_pages.find(page_array[i]); 874 const auto it = g_pages.find(page_array[i]);
667 if (it == g_pages.end()) { 875 if (it == g_pages.end()) {
876 if (i != 0) leonida::title_memory_map::changed();
668 SetLastError(ERROR_INVALID_PARAMETER); 877 SetLastError(ERROR_INVALID_PARAMETER);
669 return FALSE; 878 return FALSE;
670 } 879 }
671 g_pages.erase(it); 880 g_pages.erase(it);
672 g_free_slots.push_back(page_array[i] / kFramesPerPage); 881 g_free_slots.push_back(page_array[i] / kFramesPerPage);
673 } 882 }
883 if (page_count != 0) leonida::title_memory_map::changed();
674 return TRUE; 884 return TRUE;
675} 885}
676 886
@@ -679,8 +889,9 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra
679// or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on 889// or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on
680// success. A page number of 0 in the array unmaps that one page. 890// success. A page number of 0 in the array unmaps that one page.
681// 891//
682// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later 892// Consecutive pages of one allocation are mapped as one view (MapViewOfFile3 into a placeholder of their size); a
683// without touching its neighbours. A failure part-way leaves the pages before it mapped. 893// page remapped or unmapped later splits its view, and its neighbours stay mapped. The range is unmapped first, so a
894// page number that is not a live page fails with the pages before it mapped and the rest of the range unmapped.
684void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { 895void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) {
685 const uintptr_t start = reinterpret_cast<uintptr_t>(address); 896 const uintptr_t start = reinterpret_cast<uintptr_t>(address);
686 if (!aligned_page_address(start) || page_count > (std::numeric_limits<uintptr_t>::max)() / kPhysicalPageSize || 897 if (!aligned_page_address(start) || page_count > (std::numeric_limits<uintptr_t>::max)() / kPhysicalPageSize ||
@@ -693,20 +904,46 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint
693 return nullptr; 904 return nullptr;
694 } 905 }
695 const std::lock_guard lock(g_phys_mutex); 906 const std::lock_guard lock(g_phys_mutex);
696 if (!page_array) { 907 const uintptr_t end = start + page_count * kPhysicalPageSize;
697 for (uint64_t i = 0; i < page_count; ++i) { 908 if (!page_array) return unmap_range(start, end) ? address : nullptr;
698 if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr;
699 }
700 return address;
701 }
702 const Window* const window = find_window(start, page_count * kPhysicalPageSize); 909 const Window* const window = find_window(start, page_count * kPhysicalPageSize);
703 if (!window) { 910 if (!window) {
704 SetLastError(ERROR_INVALID_ADDRESS); 911 SetLastError(ERROR_INVALID_ADDRESS);
705 return nullptr; 912 return nullptr;
706 } 913 }
707 const DWORD protect = view_protect(*window); 914 const DWORD protect = view_protect(*window);
708 for (uint64_t i = 0; i < page_count; ++i) { 915 if (!unmap_range(start, end)) return nullptr;
709 if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr; 916 for (uint64_t i = 0; i < page_count;) {
917 if (page_array[i] == 0) {
918 ++i;
919 continue;
920 }
921 const auto it = g_pages.find(page_array[i]);
922 if (it == g_pages.end()) {
923 SetLastError(ERROR_INVALID_PARAMETER);
924 return nullptr;
925 }
926 View view{1, it->second.section, it->second.offset, protect};
927 while (i + view.count < page_count) {
928 const auto next = g_pages.find(page_array[i + view.count]);
929 if (next == g_pages.end() || next->second.section != view.section ||
930 next->second.offset != view.offset + view.count * kPhysicalPageSize) {
931 break;
932 }
933 ++view.count;
934 }
935 {
936 const FaultLockExclusive view_lock;
937 if (!map_view(start + i * kPhysicalPageSize, view)) return nullptr;
938 }
939 // After the fault lock: page_array is the title's memory, and a read of it that faults would wait for the
940 // lock on this thread. g_mapped and the aliases are g_phys_mutex's; the fault handler reads neither.
941 for (uint64_t k = 0; k < view.count; ++k) {
942 const uintptr_t at = start + (i + k) * kPhysicalPageSize;
943 g_mapped[at] = page_array[i + k];
944 note_mapping(page_array[i + k], at, true);
945 }
946 i += view.count;
710 } 947 }
711 return address; 948 return address;
712} 949}
@@ -746,12 +983,24 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co
746 return TRUE; 983 return TRUE;
747} 984}
748 985
986// The title's write watching, on reservations it made with MEM_WRITE_WATCH. One xmem write-watched for the shadows
987// (reserve_watched) is refused as the host refuses a region that is not write-watched ((UINT)-1,
988// ERROR_INVALID_PARAMETER), as the console would: it isn't write-watched there, and a reset here would clear the bits
989// the shadows ask about.
990bool shadows_write_watch(const void* base_address) {
991 if (!leonida::title_write_watch::contains(reinterpret_cast<uintptr_t>(base_address))) return false;
992 SetLastError(ERROR_INVALID_PARAMETER);
993 return true;
994}
995
749UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, 996UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count,
750 ULONG* granularity) { 997 ULONG* granularity) {
998 if (shadows_write_watch(base_address)) return UINT(-1);
751 return GetWriteWatch(flags, base_address, region_size, addresses, count, granularity); 999 return GetWriteWatch(flags, base_address, region_size, addresses, count, granularity);
752} 1000}
753 1001
754UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) { 1002UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) {
1003 if (shadows_write_watch(base_address)) return UINT(-1);
755 return ResetWriteWatch(base_address, region_size); 1004 return ResetWriteWatch(base_address, region_size);
756} 1005}
757 1006
@@ -811,14 +1060,56 @@ BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) {
811constexpr DWORD kMemGraphics = 0x10000000; 1060constexpr DWORD kMemGraphics = 0x10000000;
812constexpr DWORD kMemTitle = 0x40000000; 1061constexpr DWORD kMemTitle = 0x40000000;
813 1062
1063// A new reservation is write-watched for the D3D12 layer's shadows (reserve_watched).
814LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { 1064LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) {
815 return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); 1065 const DWORD type = allocation_type & ~(kMemGraphics | kMemTitle);
1066 const DWORD host_prot = host_protect(protect);
1067 LPVOID result =
1068 reserve_watched(type, address, size, [&](DWORD t) { return VirtualAlloc(address, size, t, host_prot); });
1069 if (result) {
1070 leonida::title_memory_map::changed();
1071 leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(result), size);
1072 note_unwatched_change(address, size, type, false);
1073 if (type & MEM_RESERVE) {
1074 const auto from = reinterpret_cast<uintptr_t>(result);
1075 leonida::geometry_writes::notify(from, from + size, leonida::geometry_writes::Event::replaced);
1076 }
1077 }
1078 return result;
1079}
1080
1081BOOL WINAPI TitleVirtualFree(LPVOID address, SIZE_T size, DWORD free_type) {
1082 const BOOL result = VirtualFree(address, size, free_type);
1083 if (result) leonida::title_memory_map::changed();
1084 if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true);
1085 if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER))
1086 leonida::title_write_watch::remove(reinterpret_cast<uintptr_t>(address));
1087 return result;
1088}
1089
1090BOOL WINAPI TitleVirtualProtect(LPVOID address, SIZE_T size, DWORD protect, PDWORD old) {
1091 const BOOL result = VirtualProtect(address, size, protect, old);
1092 if (result) {
1093 leonida::title_memory_map::changed();
1094 const auto start = reinterpret_cast<uintptr_t>(address);
1095 leonida::geometry_writes::notify(start, start + size, leonida::geometry_writes::Event::replaced);
1096 }
1097 return result;
816} 1098}
817 1099
818} // namespace 1100} // namespace
819 1101
820namespace rt::xmem { 1102namespace rt::xmem {
821 1103
1104void geometry_aliases(std::uintptr_t va, std::vector<std::uintptr_t>& addresses) {
1105 std::lock_guard lock(g_phys_mutex);
1106 const auto mapped = g_mapped.find(va);
1107 if (mapped == g_mapped.end()) return;
1108 const auto peers = g_page_addresses.find(mapped->second);
1109 if (peers != g_page_addresses.end())
1110 for (auto other : peers->second) if (other != va) addresses.push_back(other);
1111}
1112
822bool commit_physical_range(const void* address, size_t size) { 1113bool commit_physical_range(const void* address, size_t size) {
823 if (size == 0) return true; 1114 if (size == 0) return true;
824 const uintptr_t start = reinterpret_cast<uintptr_t>(address); 1115 const uintptr_t start = reinterpret_cast<uintptr_t>(address);
@@ -838,13 +1129,12 @@ bool commit_physical_range(const void* address, size_t size) {
838 return true; 1129 return true;
839} 1130}
840 1131
841bool commit_physical_pages(const uint64_t* page_array, size_t count) { 1132static bool commit_pages_locked(const uint64_t* page_array, size_t count) {
842 if (count == 0) return true; 1133 if (count == 0) return true;
843 if (!page_array) { 1134 if (!page_array) {
844 SetLastError(ERROR_INVALID_PARAMETER); 1135 SetLastError(ERROR_INVALID_PARAMETER);
845 return false; 1136 return false;
846 } 1137 }
847 const std::lock_guard lock(g_phys_mutex);
848 size_t first = 0; 1138 size_t first = 0;
849 while (first < count) { 1139 while (first < count) {
850 const auto it = g_pages.find(page_array[first]); 1140 const auto it = g_pages.find(page_array[first]);
@@ -863,26 +1153,68 @@ bool commit_physical_pages(const uint64_t* page_array, size_t count) {
863 } 1153 }
864 void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset; 1154 void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset;
865 if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; 1155 if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false;
1156 leonida::title_memory_map::changed();
866 first = last; 1157 first = last;
867 } 1158 }
868 return true; 1159 return true;
869} 1160}
870 1161
1162bool commit_physical_pages(const uint64_t* page_array, size_t count) {
1163 const std::lock_guard lock(g_phys_mutex);
1164 return commit_pages_locked(page_array, count);
1165}
1166
1167bool transfer_physical(std::span<const uint64_t> pages, uint16_t offset, std::span<uint8_t> staging, bool write) {
1168 if (staging.empty()) return true;
1169 if (pages.size() != 1 + (staging.size() - 1 + offset) / kPhysicalPageSize) {
1170 SetLastError(ERROR_INVALID_PARAMETER);
1171 return false;
1172 }
1173 const std::lock_guard lock(g_phys_mutex);
1174 if (!commit_pages_locked(pages.data(), pages.size())) return false;
1175 for (const auto page : pages) {
1176 const auto& backing = g_pages.at(page);
1177 auto* ptr = static_cast<uint8_t*>(backing.section->scratch) + backing.offset + offset;
1178 const size_t bytes = (std::min)(staging.size(), size_t(kPhysicalPageSize - offset));
1179 if (write) {
1180 std::memcpy(ptr, staging.data(), bytes);
1181 if (auto mapped = g_page_addresses.find(page); mapped != g_page_addresses.end()) {
1182 for (uintptr_t address : mapped->second) {
1183 leonida::geometry_writes::notify(address + offset, address + offset + bytes, leonida::geometry_writes::Event::write);
1184 leonida::title_texel_writes::note(reinterpret_cast<void*>(address + offset), bytes);
1185 if (leonida::dstorage::trace_enabled())
1186 std::fprintf(stderr, "[rt] ds-scatter cpu=%llx bytes=%zu page=%llu\n",
1187 static_cast<unsigned long long>(address + offset), bytes,
1188 static_cast<unsigned long long>(page));
1189 }
1190 }
1191 } else {
1192 std::memcpy(staging.data(), ptr, bytes);
1193 }
1194 staging = staging.subspan(bytes);
1195 offset = 0;
1196 }
1197 return true;
1198}
1199
871} 1200}
872 1201
873#define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast<void*>(&TitleVirtualAlloc)} 1202#define TITLE_VIRTUAL_MEMORY(dll) \
1203 {dll, "VirtualAlloc", reinterpret_cast<void*>(&TitleVirtualAlloc)}, \
1204 {dll, "VirtualFree", reinterpret_cast<void*>(&TitleVirtualFree)}, \
1205 {dll, "VirtualProtect", reinterpret_cast<void*>(&TitleVirtualProtect)}
874 1206
875// The classic libraries and the memory api sets a title's imports name. 1207// The classic libraries and the memory api sets a title's imports name.
876SHIM_TABLE(title_memory, 1208SHIM_TABLE(title_memory,
877 TITLE_VIRTUAL_ALLOC("kernel32.dll"), 1209 TITLE_VIRTUAL_MEMORY("kernel32.dll"),
878 TITLE_VIRTUAL_ALLOC("kernelbase.dll"), 1210 TITLE_VIRTUAL_MEMORY("kernelbase.dll"),
879 TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-0.dll"), 1211 TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-0.dll"),
880 TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-1.dll"), 1212 TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-1.dll"),
881 TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-2.dll"), 1213 TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-2.dll"),
882 TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-3.dll"), 1214 TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-3.dll"),
883 TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-4.dll"), 1215 TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-4.dll"),
884 TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-5.dll"), 1216 TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-5.dll"),
885 TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-6.dll"), 1217 TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-6.dll"),
886); 1218);
887 1219
888SHIM_TABLE(xmem, 1220SHIM_TABLE(xmem,