diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:09:14 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:09:14 -0500 |
| commit | 6fdeadfe509f37203317a967bf28e57fc75676b2 (patch) | |
| tree | c4d837eca0be726489f24e01fbbe14c6d5d420f4 /runtime/shims/xmem.cpp | |
| parent | f2268abeadb9c57f675c43805a622d5e43628739 (diff) | |
| parent | 1d89b20c5f26f1078b50fef7e2c9cd5fbe2372d6 (diff) | |
Merge main with #984 into RT-QUEUE31 (#968)
Merges the local m984-on-main (1d89b20c5f26f1078b50fef7e2c9cd5fbe2372d6), main with #984
merged, into #968's head f2268abea.
Conflicts and their resolutions:
- runtime/shims/xmem.h: both sides appended to the end of rt::xmem. Kept
geometry_aliases and transfer_physical from #984 and appended #968's
CopyPageMappingsFn typedef and the inline copy_page_mappings_fn after them.
- runtime/shims/xmem.cpp: copy_page_mappings and the self-registering
g_copy_page_mappings_set stay right after XMemMapPhysicalPagesScatter,
followed by #984's shadows_write_watch. One-line port: #984's g_mapped stores
the page number itself (HostUnorderedMap<uintptr_t, uint64_t>), so
`it->second.page` becomes `it->second`.
- runtime/shims/d3d12_xs_device.cpp:
- includes: #968's "xmem.h" beside "d3d12_trace.h", then #984's includes;
- constants: #984's block kept, kQueueCopyPageMappingsBatchX = 31 added after
kQueueExecuteCommandListsX and its static_assert;
- the slot-31 section (ConsolePageRange/Batch, copy_console_page_range,
queue_copy_page_mappings) goes after #984's queue_execute_command_lists and
before the "PresentX is at queue slot 30" comment;
- child_slot: #984's queue block kept; the slot-31 dispatch (beyond the PC
table and with xmem's hook set) goes just before the qroutes lookup, ahead
of the presentation routes and the console-only S_OK tail. Newer-layout
PresentX is 32, so 31 does not clash.
- runtime/test/xs_proxy_mock_test.cpp:
- includes: "../shims/xmem.h" beside #984's d3d12_xs_frame_events.h;
- #984's descriptor-heap and later checks kept, check_queue_copy_page_mappings
after them. Without xmem the merged proxy answers slot 31 with the
console-only S_OK, so that check's `== E_NOTIMPL` becomes `== S_OK` (and its
summary line says so);
- main: `|| check_queue_copy_page_mappings()` appended after
check_presentation_wiring().
runtime/test/xmem_test.cpp merged without conflict: test_copy_page_mappings runs
after test_physical_pages.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/shims/xmem.cpp')
| -rw-r--r-- | runtime/shims/xmem.cpp | 473 |
1 files changed, 410 insertions, 63 deletions
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 8eb5d7304..fe8641964 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp | |||
| @@ -18,9 +18,12 @@ | |||
| 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> |
| 23 | #include <cerrno> | ||
| 22 | #include <cstdint> | 24 | #include <cstdint> |
| 23 | #include <cstdio> | 25 | #include <cstdio> |
| 26 | #include <cstdlib> | ||
| 24 | #include <cstring> | 27 | #include <cstring> |
| 25 | #include <iterator> | 28 | #include <iterator> |
| 26 | #include <limits> | 29 | #include <limits> |
| @@ -36,6 +39,10 @@ | |||
| 36 | #include "shims.h" | 39 | #include "shims.h" |
| 37 | #include "startup_trace.h" | 40 | #include "startup_trace.h" |
| 38 | #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" | ||
| 39 | 46 | ||
| 40 | namespace { | 47 | namespace { |
| 41 | 48 | ||
| @@ -67,14 +74,29 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo | |||
| 67 | 74 | ||
| 68 | void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); } | 75 | void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); } |
| 69 | 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. | ||
| 79 | void* 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 | |||
| 86 | void 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 | |||
| 70 | void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { | 92 | void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { |
| 71 | note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); | 93 | note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); |
| 72 | return allocate_block(size); | 94 | return title_block(size); |
| 73 | } | 95 | } |
| 74 | 96 | ||
| 75 | void __stdcall XMemFree(void* p, uint64_t attributes) { | 97 | void __stdcall XMemFree(void* p, uint64_t attributes) { |
| 76 | note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); | 98 | note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); |
| 77 | _aligned_free(p); | 99 | free_title_block(p); |
| 78 | } | 100 | } |
| 79 | 101 | ||
| 80 | // 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 |
| @@ -83,12 +105,12 @@ void __stdcall XMemFree(void* p, uint64_t attributes) { | |||
| 83 | // released by either free. | 105 | // released by either free. |
| 84 | void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { | 106 | void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { |
| 85 | note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); | 107 | note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); |
| 86 | return allocate_block(size); | 108 | return title_block(size); |
| 87 | } | 109 | } |
| 88 | 110 | ||
| 89 | void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { | 111 | void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { |
| 90 | note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); | 112 | note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); |
| 91 | _aligned_free(p); | 113 | free_title_block(p); |
| 92 | } | 114 | } |
| 93 | 115 | ||
| 94 | // 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 |
| @@ -159,6 +181,19 @@ BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) { | |||
| 159 | if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { | 181 | if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { |
| 160 | total_memory = ms.ullTotalPhys; | 182 | total_memory = ms.ullTotalPhys; |
| 161 | } | 183 | } |
| 184 | // Optional override (matching XSystemGetAppMemoryUsageLimit) so memory-constrained hosts can cap title pools. | ||
| 185 | char env[32]{}; | ||
| 186 | const DWORD env_n = GetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", env, sizeof(env)); | ||
| 187 | if (env_n > 0 && env_n < sizeof(env) && env[0] != '-' && env[0] != '+') { | ||
| 188 | errno = 0; | ||
| 189 | char* end = nullptr; | ||
| 190 | unsigned long long mib = std::strtoull(env, &end, 10); | ||
| 191 | if (errno == 0 && end != env && *end == '\0' && mib > 0) { | ||
| 192 | if (mib < 2048ULL) mib = 2048ULL; | ||
| 193 | if (mib > 65536ULL) mib = 65536ULL; | ||
| 194 | total_memory = static_cast<uint64_t>(mib) * 1024ULL * 1024ULL; | ||
| 195 | } | ||
| 196 | } | ||
| 162 | 197 | ||
| 163 | uint8_t* bytes = static_cast<uint8_t*>(stats); | 198 | uint8_t* bytes = static_cast<uint8_t*>(stats); |
| 164 | std::memset(bytes, 0, 16); | 199 | std::memset(bytes, 0, 16); |
| @@ -266,13 +301,25 @@ std::map<uintptr_t, Window> g_windows; // base -> window | |||
| 266 | std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing | 301 | std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing |
| 267 | std::vector<uint64_t> g_free_slots; | 302 | std::vector<uint64_t> g_free_slots; |
| 268 | uint64_t g_next_slot = 1; | 303 | uint64_t g_next_slot = 1; |
| 269 | struct MappedPage { | 304 | // A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run |
| 270 | 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 |
| 271 | std::shared_ptr<Section> section; | 306 | // number of views, and the retail title maps about 100,000 pages in one call. |
| 272 | uint64_t offset; | 307 | struct 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; | ||
| 273 | }; | 312 | }; |
| 274 | 313 | leonida::host_heap::map<uintptr_t, View> g_views; // view base -> view; host_heap: see g_fault_lock | |
| 275 | std::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. | ||
| 276 | SRWLOCK g_fault_lock = SRWLOCK_INIT; | 323 | SRWLOCK g_fault_lock = SRWLOCK_INIT; |
| 277 | 324 | ||
| 278 | struct FaultLockExclusive { | 325 | struct FaultLockExclusive { |
| @@ -287,10 +334,41 @@ struct FaultLockShared { | |||
| 287 | ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } | 334 | ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } |
| 288 | FaultLockShared(const FaultLockShared&) = delete; | 335 | FaultLockShared(const FaultLockShared&) = delete; |
| 289 | FaultLockShared& operator=(const FaultLockShared&) = delete; | 336 | FaultLockShared& operator=(const FaultLockShared&) = delete; |
| 337 | |||
| 290 | }; | 338 | }; |
| 291 | 339 | ||
| 292 | // 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. |
| 293 | // kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. | 341 | template <class K, class V> |
| 342 | using HostUnorderedMap = | ||
| 343 | std::unordered_map<K, V, std::hash<K>, std::equal_to<K>, leonida::host_heap::Allocator<std::pair<const K, V>>>; | ||
| 344 | using AddressSet = std::set<uintptr_t, std::less<uintptr_t>, leonida::host_heap::Allocator<uintptr_t>>; | ||
| 345 | HostUnorderedMap<uintptr_t, uint64_t> g_mapped; // mapped 64 KiB address -> page number | ||
| 346 | HostUnorderedMap<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). | ||
| 351 | void 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. | ||
| 294 | void record_window(void* base, SIZE_T size, DWORD protect) { | 372 | void record_window(void* base, SIZE_T size, DWORD protect) { |
| 295 | const uintptr_t start = reinterpret_cast<uintptr_t>(base); | 373 | const uintptr_t start = reinterpret_cast<uintptr_t>(base); |
| 296 | const uintptr_t end = start + size; | 374 | const uintptr_t end = start + size; |
| @@ -322,7 +400,9 @@ bool isolate_placeholder(void* address, SIZE_T size) { | |||
| 322 | return false; | 400 | return false; |
| 323 | } | 401 | } |
| 324 | if (info.AllocationBase == address && info.RegionSize == size) return true; | 402 | if (info.AllocationBase == address && info.RegionSize == size) return true; |
| 325 | 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; | ||
| 326 | } | 406 | } |
| 327 | 407 | ||
| 328 | PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { | 408 | PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { |
| @@ -339,6 +419,43 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { | |||
| 339 | PAGE_NOACCESS, parameter_count ? ¶meter : nullptr, parameter_count); | 419 | PAGE_NOACCESS, parameter_count ? ¶meter : nullptr, parameter_count); |
| 340 | } | 420 | } |
| 341 | 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). | ||
| 428 | template <class Allocate> | ||
| 429 | void* 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). | ||
| 448 | void 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 | |||
| 342 | // 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 |
| 343 | // 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 |
| 344 | // 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 |
| @@ -346,8 +463,39 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { | |||
| 346 | // 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 |
| 347 | // 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 |
| 348 | // VirtualAlloc2. | 465 | // VirtualAlloc2. |
| 466 | void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect); | ||
| 467 | |||
| 349 | void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { | 468 | void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { |
| 350 | 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 | |||
| 498 | void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { | ||
| 351 | if (size == 0) { | 499 | if (size == 0) { |
| 352 | SetLastError(ERROR_INVALID_PARAMETER); | 500 | SetLastError(ERROR_INVALID_PARAMETER); |
| 353 | return nullptr; | 501 | return nullptr; |
| @@ -445,25 +593,96 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, | |||
| 445 | MEM_EXTENDED_PARAMETER parameter{}; | 593 | MEM_EXTENDED_PARAMETER parameter{}; |
| 446 | parameter.Type = MemExtendedParameterAddressRequirements; | 594 | parameter.Type = MemExtendedParameterAddressRequirements; |
| 447 | parameter.Pointer = &requirements; | 595 | parameter.Pointer = &requirements; |
| 448 | 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) { |
| 449 | ¶meter, 1); | 597 | return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, type, host_prot, ¶meter, 1); |
| 598 | }); | ||
| 450 | } | 599 | } |
| 451 | 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); }); | ||
| 452 | } | 602 | } |
| 453 | 603 | ||
| 454 | // 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 |
| 455 | bool 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 |
| 456 | 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 |
| 457 | 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. |
| 458 | if (it == g_mapped.end()) return true; | 608 | constexpr uint64_t kMaxViewPages = 1024; // 64 MiB |
| 459 | if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(address), | 609 | |
| 460 | MEM_PRESERVE_PLACEHOLDER)) { | 610 | |
| 461 | return false; | 611 | bool 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; | ||
| 462 | } | 634 | } |
| 463 | g_mapped.erase(it); | ||
| 464 | return true; | 635 | return true; |
| 465 | } | 636 | } |
| 466 | 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. | ||
| 643 | bool 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 | } | ||
| 680 | } | ||
| 681 | return true; | ||
| 682 | } | ||
| 683 | |||
| 684 | bool unmap_page(uintptr_t address) { return unmap_range(address, address + kPhysicalPageSize); } | ||
| 685 | |||
| 467 | // 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 |
| 468 | // mapped there. The caller has found the window. | 687 | // mapped there. The caller has found the window. |
| 469 | bool map_page(uintptr_t address, uint64_t page, DWORD protect) { | 688 | bool map_page(uintptr_t address, uint64_t page, DWORD protect) { |
| @@ -474,22 +693,23 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { | |||
| 474 | SetLastError(ERROR_INVALID_PARAMETER); | 693 | SetLastError(ERROR_INVALID_PARAMETER); |
| 475 | return false; | 694 | return false; |
| 476 | } | 695 | } |
| 477 | void* const target = reinterpret_cast<void*>(address); | 696 | { |
| 478 | if (!isolate_placeholder(target, kPhysicalPageSize)) return false; | 697 | const FaultLockExclusive lock; |
| 479 | const FaultLockExclusive lock; | 698 | if (!map_view(address, View{1, it->second.section, it->second.offset, protect})) return false; |
| 480 | void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, | 699 | } |
| 481 | it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, | 700 | g_mapped[address] = page; |
| 482 | protect, nullptr, 0); | 701 | note_mapping(page, address, true); |
| 483 | if (!view) return false; | ||
| 484 | g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; | ||
| 485 | return true; | 702 | return true; |
| 486 | } | 703 | } |
| 487 | 704 | ||
| 488 | enum class PageCommit { not_ours, committed_before, committed_now, failed }; | 705 | enum class PageCommit { not_ours, committed_before, committed_now, failed }; |
| 489 | 706 | ||
| 490 | PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { | 707 | PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { |
| 491 | const auto it = g_mapped.find(address); | 708 | auto it = g_views.upper_bound(address); |
| 492 | 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; | ||
| 493 | MEMORY_BASIC_INFORMATION info{}; | 713 | MEMORY_BASIC_INFORMATION info{}; |
| 494 | 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) { |
| 495 | return PageCommit::not_ours; | 715 | return PageCommit::not_ours; |
| @@ -498,9 +718,11 @@ PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& prot | |||
| 498 | protect = info.Protect; | 718 | protect = info.Protect; |
| 499 | return PageCommit::committed_before; | 719 | return PageCommit::committed_before; |
| 500 | } | 720 | } |
| 501 | 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; |
| 502 | return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now | 722 | if (!VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return PageCommit::failed; |
| 503 | : 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; | ||
| 504 | } | 726 | } |
| 505 | 727 | ||
| 506 | bool access_allowed(DWORD protect, ULONG_PTR access) { | 728 | bool access_allowed(DWORD protect, ULONG_PTR access) { |
| @@ -617,7 +839,8 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, | |||
| 617 | *page_count = 0; | 839 | *page_count = 0; |
| 618 | return FALSE; | 840 | return FALSE; |
| 619 | } | 841 | } |
| 620 | 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); | ||
| 621 | if (!section->scratch) { | 844 | if (!section->scratch) { |
| 622 | *page_count = 0; | 845 | *page_count = 0; |
| 623 | return FALSE; | 846 | return FALSE; |
| @@ -650,12 +873,14 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra | |||
| 650 | for (uint64_t i = 0; i < page_count; ++i) { | 873 | for (uint64_t i = 0; i < page_count; ++i) { |
| 651 | const auto it = g_pages.find(page_array[i]); | 874 | const auto it = g_pages.find(page_array[i]); |
| 652 | if (it == g_pages.end()) { | 875 | if (it == g_pages.end()) { |
| 876 | if (i != 0) leonida::title_memory_map::changed(); | ||
| 653 | SetLastError(ERROR_INVALID_PARAMETER); | 877 | SetLastError(ERROR_INVALID_PARAMETER); |
| 654 | return FALSE; | 878 | return FALSE; |
| 655 | } | 879 | } |
| 656 | g_pages.erase(it); | 880 | g_pages.erase(it); |
| 657 | g_free_slots.push_back(page_array[i] / kFramesPerPage); | 881 | g_free_slots.push_back(page_array[i] / kFramesPerPage); |
| 658 | } | 882 | } |
| 883 | if (page_count != 0) leonida::title_memory_map::changed(); | ||
| 659 | return TRUE; | 884 | return TRUE; |
| 660 | } | 885 | } |
| 661 | 886 | ||
| @@ -664,8 +889,9 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra | |||
| 664 | // 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 |
| 665 | // 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. |
| 666 | // | 891 | // |
| 667 | // 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 |
| 668 | // 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. | ||
| 669 | void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { | 895 | void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { |
| 670 | const uintptr_t start = reinterpret_cast<uintptr_t>(address); | 896 | const uintptr_t start = reinterpret_cast<uintptr_t>(address); |
| 671 | 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 || |
| @@ -678,20 +904,46 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint | |||
| 678 | return nullptr; | 904 | return nullptr; |
| 679 | } | 905 | } |
| 680 | const std::lock_guard lock(g_phys_mutex); | 906 | const std::lock_guard lock(g_phys_mutex); |
| 681 | if (!page_array) { | 907 | const uintptr_t end = start + page_count * kPhysicalPageSize; |
| 682 | for (uint64_t i = 0; i < page_count; ++i) { | 908 | if (!page_array) return unmap_range(start, end) ? address : nullptr; |
| 683 | if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr; | ||
| 684 | } | ||
| 685 | return address; | ||
| 686 | } | ||
| 687 | const Window* const window = find_window(start, page_count * kPhysicalPageSize); | 909 | const Window* const window = find_window(start, page_count * kPhysicalPageSize); |
| 688 | if (!window) { | 910 | if (!window) { |
| 689 | SetLastError(ERROR_INVALID_ADDRESS); | 911 | SetLastError(ERROR_INVALID_ADDRESS); |
| 690 | return nullptr; | 912 | return nullptr; |
| 691 | } | 913 | } |
| 692 | const DWORD protect = view_protect(*window); | 914 | const DWORD protect = view_protect(*window); |
| 693 | for (uint64_t i = 0; i < page_count; ++i) { | 915 | if (!unmap_range(start, end)) return nullptr; |
| 694 | 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; | ||
| 695 | } | 947 | } |
| 696 | return address; | 948 | return address; |
| 697 | } | 949 | } |
| @@ -763,7 +1015,7 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b | |||
| 763 | std::vector<uint64_t> found(static_cast<size_t>(pages), 0); | 1015 | std::vector<uint64_t> found(static_cast<size_t>(pages), 0); |
| 764 | for (uint64_t i = 0; i < pages; ++i) { | 1016 | for (uint64_t i = 0; i < pages; ++i) { |
| 765 | const auto it = g_mapped.find(from + (repeat_first ? 0 : i) * kPhysicalPageSize); | 1017 | const auto it = g_mapped.find(from + (repeat_first ? 0 : i) * kPhysicalPageSize); |
| 766 | if (it != g_mapped.end()) found[static_cast<size_t>(i)] = it->second.page; | 1018 | if (it != g_mapped.end()) found[static_cast<size_t>(i)] = it->second; |
| 767 | } | 1019 | } |
| 768 | const DWORD protect = view_protect(*window); | 1020 | const DWORD protect = view_protect(*window); |
| 769 | for (uint64_t i = 0; i < pages; ++i) { | 1021 | for (uint64_t i = 0; i < pages; ++i) { |
| @@ -773,12 +1025,24 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b | |||
| 773 | } | 1025 | } |
| 774 | [[maybe_unused]] const bool g_copy_page_mappings_set =(rt::xmem::copy_page_mappings_fn = ©_page_mappings, true); | 1026 | [[maybe_unused]] const bool g_copy_page_mappings_set =(rt::xmem::copy_page_mappings_fn = ©_page_mappings, true); |
| 775 | 1027 | ||
| 1028 | // The title's write watching, on reservations it made with MEM_WRITE_WATCH. One xmem write-watched for the shadows | ||
| 1029 | // (reserve_watched) is refused as the host refuses a region that is not write-watched ((UINT)-1, | ||
| 1030 | // ERROR_INVALID_PARAMETER), as the console would: it isn't write-watched there, and a reset here would clear the bits | ||
| 1031 | // the shadows ask about. | ||
| 1032 | bool shadows_write_watch(const void* base_address) { | ||
| 1033 | if (!leonida::title_write_watch::contains(reinterpret_cast<uintptr_t>(base_address))) return false; | ||
| 1034 | SetLastError(ERROR_INVALID_PARAMETER); | ||
| 1035 | return true; | ||
| 1036 | } | ||
| 1037 | |||
| 776 | UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, | 1038 | UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, |
| 777 | ULONG* granularity) { | 1039 | ULONG* granularity) { |
| 1040 | if (shadows_write_watch(base_address)) return UINT(-1); | ||
| 778 | return GetWriteWatch(flags, base_address, region_size, addresses, count, granularity); | 1041 | return GetWriteWatch(flags, base_address, region_size, addresses, count, granularity); |
| 779 | } | 1042 | } |
| 780 | 1043 | ||
| 781 | UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) { | 1044 | UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) { |
| 1045 | if (shadows_write_watch(base_address)) return UINT(-1); | ||
| 782 | return ResetWriteWatch(base_address, region_size); | 1046 | return ResetWriteWatch(base_address, region_size); |
| 783 | } | 1047 | } |
| 784 | 1048 | ||
| @@ -838,14 +1102,56 @@ BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) { | |||
| 838 | constexpr DWORD kMemGraphics = 0x10000000; | 1102 | constexpr DWORD kMemGraphics = 0x10000000; |
| 839 | constexpr DWORD kMemTitle = 0x40000000; | 1103 | constexpr DWORD kMemTitle = 0x40000000; |
| 840 | 1104 | ||
| 1105 | // A new reservation is write-watched for the D3D12 layer's shadows (reserve_watched). | ||
| 841 | LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { | 1106 | LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { |
| 842 | return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); | 1107 | const DWORD type = allocation_type & ~(kMemGraphics | kMemTitle); |
| 1108 | const DWORD host_prot = host_protect(protect); | ||
| 1109 | LPVOID result = | ||
| 1110 | reserve_watched(type, address, size, [&](DWORD t) { return VirtualAlloc(address, size, t, host_prot); }); | ||
| 1111 | if (result) { | ||
| 1112 | leonida::title_memory_map::changed(); | ||
| 1113 | leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(result), size); | ||
| 1114 | note_unwatched_change(address, size, type, false); | ||
| 1115 | if (type & MEM_RESERVE) { | ||
| 1116 | const auto from = reinterpret_cast<uintptr_t>(result); | ||
| 1117 | leonida::geometry_writes::notify(from, from + size, leonida::geometry_writes::Event::replaced); | ||
| 1118 | } | ||
| 1119 | } | ||
| 1120 | return result; | ||
| 1121 | } | ||
| 1122 | |||
| 1123 | BOOL WINAPI TitleVirtualFree(LPVOID address, SIZE_T size, DWORD free_type) { | ||
| 1124 | const BOOL result = VirtualFree(address, size, free_type); | ||
| 1125 | if (result) leonida::title_memory_map::changed(); | ||
| 1126 | if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true); | ||
| 1127 | if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER)) | ||
| 1128 | leonida::title_write_watch::remove(reinterpret_cast<uintptr_t>(address)); | ||
| 1129 | return result; | ||
| 1130 | } | ||
| 1131 | |||
| 1132 | BOOL WINAPI TitleVirtualProtect(LPVOID address, SIZE_T size, DWORD protect, PDWORD old) { | ||
| 1133 | const BOOL result = VirtualProtect(address, size, protect, old); | ||
| 1134 | if (result) { | ||
| 1135 | leonida::title_memory_map::changed(); | ||
| 1136 | const auto start = reinterpret_cast<uintptr_t>(address); | ||
| 1137 | leonida::geometry_writes::notify(start, start + size, leonida::geometry_writes::Event::replaced); | ||
| 1138 | } | ||
| 1139 | return result; | ||
| 843 | } | 1140 | } |
| 844 | 1141 | ||
| 845 | } // namespace | 1142 | } // namespace |
| 846 | 1143 | ||
| 847 | namespace rt::xmem { | 1144 | namespace rt::xmem { |
| 848 | 1145 | ||
| 1146 | void geometry_aliases(std::uintptr_t va, std::vector<std::uintptr_t>& addresses) { | ||
| 1147 | std::lock_guard lock(g_phys_mutex); | ||
| 1148 | const auto mapped = g_mapped.find(va); | ||
| 1149 | if (mapped == g_mapped.end()) return; | ||
| 1150 | const auto peers = g_page_addresses.find(mapped->second); | ||
| 1151 | if (peers != g_page_addresses.end()) | ||
| 1152 | for (auto other : peers->second) if (other != va) addresses.push_back(other); | ||
| 1153 | } | ||
| 1154 | |||
| 849 | bool commit_physical_range(const void* address, size_t size) { | 1155 | bool commit_physical_range(const void* address, size_t size) { |
| 850 | if (size == 0) return true; | 1156 | if (size == 0) return true; |
| 851 | const uintptr_t start = reinterpret_cast<uintptr_t>(address); | 1157 | const uintptr_t start = reinterpret_cast<uintptr_t>(address); |
| @@ -865,13 +1171,12 @@ bool commit_physical_range(const void* address, size_t size) { | |||
| 865 | return true; | 1171 | return true; |
| 866 | } | 1172 | } |
| 867 | 1173 | ||
| 868 | bool commit_physical_pages(const uint64_t* page_array, size_t count) { | 1174 | static bool commit_pages_locked(const uint64_t* page_array, size_t count) { |
| 869 | if (count == 0) return true; | 1175 | if (count == 0) return true; |
| 870 | if (!page_array) { | 1176 | if (!page_array) { |
| 871 | SetLastError(ERROR_INVALID_PARAMETER); | 1177 | SetLastError(ERROR_INVALID_PARAMETER); |
| 872 | return false; | 1178 | return false; |
| 873 | } | 1179 | } |
| 874 | const std::lock_guard lock(g_phys_mutex); | ||
| 875 | size_t first = 0; | 1180 | size_t first = 0; |
| 876 | while (first < count) { | 1181 | while (first < count) { |
| 877 | const auto it = g_pages.find(page_array[first]); | 1182 | const auto it = g_pages.find(page_array[first]); |
| @@ -890,26 +1195,68 @@ bool commit_physical_pages(const uint64_t* page_array, size_t count) { | |||
| 890 | } | 1195 | } |
| 891 | void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset; | 1196 | void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset; |
| 892 | if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; | 1197 | if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; |
| 1198 | leonida::title_memory_map::changed(); | ||
| 893 | first = last; | 1199 | first = last; |
| 894 | } | 1200 | } |
| 895 | return true; | 1201 | return true; |
| 896 | } | 1202 | } |
| 897 | 1203 | ||
| 1204 | bool commit_physical_pages(const uint64_t* page_array, size_t count) { | ||
| 1205 | const std::lock_guard lock(g_phys_mutex); | ||
| 1206 | return commit_pages_locked(page_array, count); | ||
| 1207 | } | ||
| 1208 | |||
| 1209 | bool transfer_physical(std::span<const uint64_t> pages, uint16_t offset, std::span<uint8_t> staging, bool write) { | ||
| 1210 | if (staging.empty()) return true; | ||
| 1211 | if (pages.size() != 1 + (staging.size() - 1 + offset) / kPhysicalPageSize) { | ||
| 1212 | SetLastError(ERROR_INVALID_PARAMETER); | ||
| 1213 | return false; | ||
| 1214 | } | ||
| 1215 | const std::lock_guard lock(g_phys_mutex); | ||
| 1216 | if (!commit_pages_locked(pages.data(), pages.size())) return false; | ||
| 1217 | for (const auto page : pages) { | ||
| 1218 | const auto& backing = g_pages.at(page); | ||
| 1219 | auto* ptr = static_cast<uint8_t*>(backing.section->scratch) + backing.offset + offset; | ||
| 1220 | const size_t bytes = (std::min)(staging.size(), size_t(kPhysicalPageSize - offset)); | ||
| 1221 | if (write) { | ||
| 1222 | std::memcpy(ptr, staging.data(), bytes); | ||
| 1223 | if (auto mapped = g_page_addresses.find(page); mapped != g_page_addresses.end()) { | ||
| 1224 | for (uintptr_t address : mapped->second) { | ||
| 1225 | leonida::geometry_writes::notify(address + offset, address + offset + bytes, leonida::geometry_writes::Event::write); | ||
| 1226 | leonida::title_texel_writes::note(reinterpret_cast<void*>(address + offset), bytes); | ||
| 1227 | if (leonida::dstorage::trace_enabled()) | ||
| 1228 | std::fprintf(stderr, "[rt] ds-scatter cpu=%llx bytes=%zu page=%llu\n", | ||
| 1229 | static_cast<unsigned long long>(address + offset), bytes, | ||
| 1230 | static_cast<unsigned long long>(page)); | ||
| 1231 | } | ||
| 1232 | } | ||
| 1233 | } else { | ||
| 1234 | std::memcpy(staging.data(), ptr, bytes); | ||
| 1235 | } | ||
| 1236 | staging = staging.subspan(bytes); | ||
| 1237 | offset = 0; | ||
| 1238 | } | ||
| 1239 | return true; | ||
| 1240 | } | ||
| 1241 | |||
| 898 | } | 1242 | } |
| 899 | 1243 | ||
| 900 | #define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast<void*>(&TitleVirtualAlloc)} | 1244 | #define TITLE_VIRTUAL_MEMORY(dll) \ |
| 1245 | {dll, "VirtualAlloc", reinterpret_cast<void*>(&TitleVirtualAlloc)}, \ | ||
| 1246 | {dll, "VirtualFree", reinterpret_cast<void*>(&TitleVirtualFree)}, \ | ||
| 1247 | {dll, "VirtualProtect", reinterpret_cast<void*>(&TitleVirtualProtect)} | ||
| 901 | 1248 | ||
| 902 | // The classic libraries and the memory api sets a title's imports name. | 1249 | // The classic libraries and the memory api sets a title's imports name. |
| 903 | SHIM_TABLE(title_memory, | 1250 | SHIM_TABLE(title_memory, |
| 904 | TITLE_VIRTUAL_ALLOC("kernel32.dll"), | 1251 | TITLE_VIRTUAL_MEMORY("kernel32.dll"), |
| 905 | TITLE_VIRTUAL_ALLOC("kernelbase.dll"), | 1252 | TITLE_VIRTUAL_MEMORY("kernelbase.dll"), |
| 906 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-0.dll"), | 1253 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-0.dll"), |
| 907 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-1.dll"), | 1254 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-1.dll"), |
| 908 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-2.dll"), | 1255 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-2.dll"), |
| 909 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-3.dll"), | 1256 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-3.dll"), |
| 910 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-4.dll"), | 1257 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-4.dll"), |
| 911 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-5.dll"), | 1258 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-5.dll"), |
| 912 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-6.dll"), | 1259 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-6.dll"), |
| 913 | ); | 1260 | ); |
| 914 | 1261 | ||
| 915 | SHIM_TABLE(xmem, | 1262 | SHIM_TABLE(xmem, |