diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:26:00 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:26:00 -0500 |
| commit | 154e4ec034902deffa4b89b2cbca9a949f38baec (patch) | |
| tree | 1b2ef5656de42c172291bc6009efa4c510650815 /runtime/shims/xmem.cpp | |
| parent | eb6a08cd359d98b5777e70d54d0ae8a75879495a (diff) | |
| parent | 8a242efebf823aeb23c72d17c3d666daf0bbd3e2 (diff) | |
Merge the #984 result (main + RT-PROTON-STORY-LOAD) into #939
The base is 8a242efeb, the merge of main and #984. 68 files conflicted; they were resolved in seven groups by
one rule: the same change in two forms keeps the base's form, everything only #939 has is kept, and where the
two solve one problem in two ways the base's is the frame and #939's plugs into it.
A, the Xbox proxy (d3d12_xs_device.cpp/.h, d3d12_xs.cpp, d3d12_xs_pso_stream.cpp/.h, d3d12_xs_alloc_size.h,
d3d12_xs_desc_clean.h, device_proxy_test.cpp, queue_proxy_test.cpp): the base's files with #939's additions
ported in. Device slot 57 asks #939's NativeGraphicsFactory first and falls back to the base's
proxy_create_graphics_pipeline_from_native_code on E_NOTIMPL. Kept from #939: the providers (texture lease,
raw texture view, resource by address, constant view, descriptor mapping, depth-stencil UAV, texture pages),
the title-backed descriptor mirror, slot 13's feature answers, GPU labels on list slots 71/72. Dropped: #939's
duplicates of the boot ladder routes, its fallback window, its slot 133 stand-in.
A2 (xs_proxy_mock_test.cpp): the base's test with #939's slot 70 raw-buffer case; presentation cases follow
#939's rule that a device which ever had a handler has no queue fallback.
B1, the Vulkan device (d3d12_vulkan_device.cpp, d3d12_com.cpp/.h, shader_library.h, queue_families.h,
pipeline_cache_file.h, startup_trace.h): one lazy-pipeline mechanism, the base's; #939's pending_base_compile
and first_use_backend_pipelines dropped, prepare_on_bind and cold_graphics_compile kept. create_texture keeps
the base's signature; #939's deferred backing is folded into the base's placed-memory binder. #939's quad
lists as triangle indices.
B2, the D3D12 tests (d3d12_existing_heap, a8_dimensions, pipeline_cache_seed, title_va, rect_list,
shader_library, loader_tls_index0, draw, compute, xmem_placed, shader_library_corpus): the base's tests where
both carry the same case, #939's cases added (rebound tables, linear texture map, large vertex batch,
executable shaders, default A8 views).
C, the backend (vulkan_replay.h, vulkan_backend.h, vulkan_bindless.h, vulkan_scratch.h, vulkan_present.h,
rect_list_geometry.h, vk_test_device.h, vk_pipeline_check.cpp, vk_store_test.cpp, bindless_sizing_test.cpp,
replay_texture_barrier_test.cpp): the base's prepare_draw and lazy compute, its #1055 release rule and its
rectangle generator; #939's rectangle variants, GPU quad index expansion, 1D/3D and depth-stencil UAVs, the
label fence on the base's submit.
D, memory, services, presentation (xmem.cpp/.h, xg_xs.cpp, xg_xs_test.cpp, title_va_alias.h and its test,
main.cpp, frame_pacer.h, xbox_present.cpp/.h; xgameruntime_offline.cpp for one comment): the base's xmem with
#939's label hooks, file-backed sections and pin_mapped_data; both texture computers in xg_xs.cpp, the base's
answering first; --first-run-ui kept without host speech in its profile.
E, build, tools, docs (runtime/CMakeLists.txt, make_game.py, tools/rdna2spirv.py, tools/shader_disasm.py,
scripts, tests, docs; docs/README.md and tests/test_exe_shaders_stage.py beyond the conflicts): the base's
v_dot4 decode, #281's disassembler form and tests/semantic/test_fspx_dot4_op_sel_disasm.py dropped; the
base's executable-shader step with #939's cache fix; 366 registered tests.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/shims/xmem.cpp')
| -rw-r--r-- | runtime/shims/xmem.cpp | 476 |
1 files changed, 404 insertions, 72 deletions
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 52368c2d8..c0bf90503 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp | |||
| @@ -20,9 +20,12 @@ | |||
| 20 | #include <malloc.h> | 20 | #include <malloc.h> |
| 21 | #include <psapi.h> | 21 | #include <psapi.h> |
| 22 | 22 | ||
| 23 | #include <algorithm> | ||
| 23 | #include <atomic> | 24 | #include <atomic> |
| 25 | #include <cerrno> | ||
| 24 | #include <cstdint> | 26 | #include <cstdint> |
| 25 | #include <cstdio> | 27 | #include <cstdio> |
| 28 | #include <cstdlib> | ||
| 26 | #include <cstring> | 29 | #include <cstring> |
| 27 | #include <iterator> | 30 | #include <iterator> |
| 28 | #include <limits> | 31 | #include <limits> |
| @@ -38,7 +41,10 @@ | |||
| 38 | #include "shims.h" | 41 | #include "shims.h" |
| 39 | #include "startup_trace.h" | 42 | #include "startup_trace.h" |
| 40 | #include "xmem.h" | 43 | #include "xmem.h" |
| 44 | #include "../src/dstorage_trace.h" | ||
| 41 | #include "../src/gpu_label_memory.h" | 45 | #include "../src/gpu_label_memory.h" |
| 46 | #include "../src/title_page_watch.h" | ||
| 47 | #include "../src/title_geometry_watch.h" | ||
| 42 | #include "../src/title_va_alias.h" | 48 | #include "../src/title_va_alias.h" |
| 43 | 49 | ||
| 44 | namespace { | 50 | namespace { |
| @@ -81,6 +87,7 @@ void track_label_data(void* p,std::size_t bytes,bool heap) { | |||
| 81 | 87 | ||
| 82 | void* title_block(size_t size) { | 88 | void* title_block(size_t size) { |
| 83 | void* p = allocate_block(size); | 89 | void* p = allocate_block(size); |
| 90 | if (p) leonida::title_memory_map::changed(); | ||
| 84 | leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(p), size ? size : 1); | 91 | leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(p), size ? size : 1); |
| 85 | track_label_data(p,size?size:1,true); | 92 | track_label_data(p,size?size:1,true); |
| 86 | return p; | 93 | return p; |
| @@ -90,6 +97,7 @@ void free_title_block(void* p) { | |||
| 90 | if(p)leonida::label::memory().release_heap(reinterpret_cast<std::uintptr_t>(p)); | 97 | if(p)leonida::label::memory().release_heap(reinterpret_cast<std::uintptr_t>(p)); |
| 91 | if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast<uintptr_t>(p)); | 98 | if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast<uintptr_t>(p)); |
| 92 | _aligned_free(p); | 99 | _aligned_free(p); |
| 100 | if (p) leonida::title_memory_map::changed(); | ||
| 93 | } | 101 | } |
| 94 | 102 | ||
| 95 | void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { | 103 | void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { |
| @@ -184,6 +192,19 @@ BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) { | |||
| 184 | if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { | 192 | if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { |
| 185 | total_memory = ms.ullTotalPhys; | 193 | total_memory = ms.ullTotalPhys; |
| 186 | } | 194 | } |
| 195 | // Optional override (matching XSystemGetAppMemoryUsageLimit) so memory-constrained hosts can cap title pools. | ||
| 196 | char env[32]{}; | ||
| 197 | const DWORD env_n = GetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", env, sizeof(env)); | ||
| 198 | if (env_n > 0 && env_n < sizeof(env) && env[0] != '-' && env[0] != '+') { | ||
| 199 | errno = 0; | ||
| 200 | char* end = nullptr; | ||
| 201 | unsigned long long mib = std::strtoull(env, &end, 10); | ||
| 202 | if (errno == 0 && end != env && *end == '\0' && mib > 0) { | ||
| 203 | if (mib < 2048ULL) mib = 2048ULL; | ||
| 204 | if (mib > 65536ULL) mib = 65536ULL; | ||
| 205 | total_memory = static_cast<uint64_t>(mib) * 1024ULL * 1024ULL; | ||
| 206 | } | ||
| 207 | } | ||
| 187 | 208 | ||
| 188 | uint8_t* bytes = static_cast<uint8_t*>(stats); | 209 | uint8_t* bytes = static_cast<uint8_t*>(stats); |
| 189 | std::memset(bytes, 0, 16); | 210 | std::memset(bytes, 0, 16); |
| @@ -320,13 +341,25 @@ std::map<uintptr_t, Window> g_windows; // base -> window | |||
| 320 | std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing | 341 | std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing |
| 321 | std::vector<uint64_t> g_free_slots; | 342 | std::vector<uint64_t> g_free_slots; |
| 322 | uint64_t g_next_slot = 1; | 343 | uint64_t g_next_slot = 1; |
| 323 | struct MappedPage { | 344 | // A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run |
| 324 | uint64_t page; | 345 | // rather than per page: under Wine each view costs a placeholder split and a section map whose time grows with the |
| 325 | std::shared_ptr<Section> section; | 346 | // number of views, and the retail title maps about 100,000 pages in one call. |
| 326 | uint64_t offset; | 347 | struct View { |
| 348 | uint64_t count; | ||
| 349 | std::shared_ptr<Section> section; // kept for remapping part of the run after its pages are freed | ||
| 350 | uint64_t offset; // section offset of the first page | ||
| 351 | DWORD protect; | ||
| 327 | }; | 352 | }; |
| 328 | 353 | leonida::host_heap::map<uintptr_t, View> g_views; // view base -> view; host_heap: see g_fault_lock | |
| 329 | std::unordered_map<uintptr_t, MappedPage> g_mapped; | 354 | |
| 355 | // The views (g_views) as the fault handler reads them, which is all it reads: physical_page_fault takes it shared at | ||
| 356 | // every access violation in the process, xmem's own or not, and so does commit_physical_range. A title thread can | ||
| 357 | // take an access violation while it holds the process heap's lock (XMemAlloc is _aligned_malloc, so HeapAlloc and | ||
| 358 | // HeapFree write block headers on the title's pages: a page waiting for its first touch, or one a D3D12 shadow | ||
| 359 | // guards), and then waits here. So a thread that holds it exclusively must never wait for the process heap: it would | ||
| 360 | // wait for the faulting thread, which waits for it. Everything allocated or freed under it comes from | ||
| 361 | // leonida::host_heap (g_views, g_mapped, g_page_addresses, the sections, title_page_aliases), nothing under it logs, | ||
| 362 | // and nothing under it reads title memory, which could fault into the handler on the same thread. | ||
| 330 | SRWLOCK g_fault_lock = SRWLOCK_INIT; | 363 | SRWLOCK g_fault_lock = SRWLOCK_INIT; |
| 331 | 364 | ||
| 332 | struct FaultLockExclusive { | 365 | struct FaultLockExclusive { |
| @@ -341,10 +374,41 @@ struct FaultLockShared { | |||
| 341 | ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } | 374 | ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } |
| 342 | FaultLockShared(const FaultLockShared&) = delete; | 375 | FaultLockShared(const FaultLockShared&) = delete; |
| 343 | FaultLockShared& operator=(const FaultLockShared&) = delete; | 376 | FaultLockShared& operator=(const FaultLockShared&) = delete; |
| 377 | |||
| 344 | }; | 378 | }; |
| 345 | 379 | ||
| 346 | // With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with | 380 | // With g_phys_mutex held; changed under g_fault_lock too (unmap_range), so they allocate from host_heap. |
| 347 | // kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. | 381 | template <class K, class V> |
| 382 | using HostUnorderedMap = | ||
| 383 | std::unordered_map<K, V, std::hash<K>, std::equal_to<K>, leonida::host_heap::Allocator<std::pair<const K, V>>>; | ||
| 384 | using AddressSet = std::set<uintptr_t, std::less<uintptr_t>, leonida::host_heap::Allocator<uintptr_t>>; | ||
| 385 | HostUnorderedMap<uintptr_t, uint64_t> g_mapped; // mapped 64 KiB address -> page number | ||
| 386 | HostUnorderedMap<uint64_t, AddressSet> g_page_addresses; // page number -> the addresses it is mapped at | ||
| 387 | |||
| 388 | // With g_phys_mutex held. Keeps leonida::title_page_aliases in step: a page mapped at two or more addresses is | ||
| 389 | // aliased at each of them (the D3D12 layer's slot-133 shadows copy those pages at every submission instead of | ||
| 390 | // waiting for a write fault, which a write through another address doesn't raise). | ||
| 391 | void note_mapping(uint64_t page, uintptr_t address, bool mapped) { | ||
| 392 | auto& addresses = g_page_addresses[page]; | ||
| 393 | if (mapped) { | ||
| 394 | addresses.insert(address); | ||
| 395 | } else { | ||
| 396 | addresses.erase(address); | ||
| 397 | leonida::title_page_aliases::set(address, false); | ||
| 398 | } | ||
| 399 | using namespace leonida::geometry_writes; | ||
| 400 | if (state().count.load(std::memory_order_acquire)) { | ||
| 401 | notify(address, address + kPhysicalPageSize, Event::mapping); | ||
| 402 | for (auto other : addresses) | ||
| 403 | if (other != address) notify(other, other + kPhysicalPageSize, Event::mapping); | ||
| 404 | } | ||
| 405 | const bool aliased = addresses.size() > 1; | ||
| 406 | for (const uintptr_t at : addresses) leonida::title_page_aliases::set(at, aliased); | ||
| 407 | if (addresses.empty()) g_page_addresses.erase(page); | ||
| 408 | } | ||
| 409 | |||
| 410 | // With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions before | ||
| 411 | // the host could hand the addresses out again. | ||
| 348 | void record_window(void* base, SIZE_T size, DWORD protect) { | 412 | void record_window(void* base, SIZE_T size, DWORD protect) { |
| 349 | const uintptr_t start = reinterpret_cast<uintptr_t>(base); | 413 | const uintptr_t start = reinterpret_cast<uintptr_t>(base); |
| 350 | const uintptr_t end = start + size; | 414 | const uintptr_t end = start + size; |
| @@ -376,7 +440,9 @@ bool isolate_placeholder(void* address, SIZE_T size) { | |||
| 376 | return false; | 440 | return false; |
| 377 | } | 441 | } |
| 378 | if (info.AllocationBase == address && info.RegionSize == size) return true; | 442 | if (info.AllocationBase == address && info.RegionSize == size) return true; |
| 379 | return VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != FALSE; | 443 | if (!VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) return false; |
| 444 | leonida::title_memory_map::changed(); | ||
| 445 | return true; | ||
| 380 | } | 446 | } |
| 381 | 447 | ||
| 382 | PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { | 448 | PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { |
| @@ -393,6 +459,43 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { | |||
| 393 | PAGE_NOACCESS, parameter_count ? ¶meter : nullptr, parameter_count); | 459 | PAGE_NOACCESS, parameter_count ? ¶meter : nullptr, parameter_count); |
| 394 | } | 460 | } |
| 395 | 461 | ||
| 462 | // A new ordinary reservation of the title's (MEM_RESERVE, not a placeholder, not physical, not large pages) is made | ||
| 463 | // with MEM_WRITE_WATCH and recorded (leonida::title_write_watch): the D3D12 layer's shadows of these pages then ask the | ||
| 464 | // kernel which pages were written instead of making them read-only and taking a fault at the title's first write. | ||
| 465 | // `allocate(type)` makes the call. A host that refuses the flag gets the call without it, and the pages are guarded | ||
| 466 | // as before; so are they with LEONIDA_WRITE_WATCH=0. A reservation the title asked to be write-watched itself is not | ||
| 467 | // recorded: its bits are the title's (XMemGetWriteWatch). | ||
| 468 | template <class Allocate> | ||
| 469 | void* reserve_watched(DWORD type, const void* address, SIZE_T size, Allocate&& allocate) { | ||
| 470 | constexpr DWORD kNotWatchable = MEM_WRITE_WATCH | MEM_PHYSICAL | MEM_LARGE_PAGES | MEM_RESERVE_PLACEHOLDER | | ||
| 471 | MEM_REPLACE_PLACEHOLDER | MEM_RESET | MEM_RESET_UNDO; | ||
| 472 | // A commit at no given address reserves too. | ||
| 473 | const bool reserves = (type & MEM_RESERVE) || (!address && (type & MEM_COMMIT)); | ||
| 474 | const bool watch = reserves && !(type & kNotWatchable) && leonida::title_write_watch::enabled(); | ||
| 475 | void* result = allocate(watch ? type | MEM_RESERVE | MEM_WRITE_WATCH : type); | ||
| 476 | if (!watch) return result; | ||
| 477 | if (!result) return allocate(type); | ||
| 478 | // The reservation is [result, end of the requested range): VirtualAlloc rounds a given address down to 64 KiB. | ||
| 479 | const uintptr_t base = reinterpret_cast<uintptr_t>(result); | ||
| 480 | const uintptr_t end = (address ? reinterpret_cast<uintptr_t>(address) : base) + size; | ||
| 481 | leonida::title_write_watch::add(base, end - base); | ||
| 482 | return result; | ||
| 483 | } | ||
| 484 | |||
| 485 | // After a successful call that changes pages of an existing reservation without a write the kernel would see (a | ||
| 486 | // commit, which may bring back decommitted pages as zeros; MEM_RESET; a decommit with `decommit`): if it is | ||
| 487 | // write-watched, the shadows take [address, address + size) as written (size 0: to the reservation's end). | ||
| 488 | void note_unwatched_change(const void* address, SIZE_T size, DWORD type, bool decommit) { | ||
| 489 | if (!address || !(decommit || (type & (MEM_COMMIT | MEM_RESET | MEM_RESET_UNDO))) || (type & MEM_RESERVE)) return; | ||
| 490 | const auto from = reinterpret_cast<uintptr_t>(address); | ||
| 491 | const uintptr_t to = size ? from + size : leonida::title_write_watch::end_of(from); | ||
| 492 | if (to > from) { | ||
| 493 | leonida::title_write_watch::mark(from, to); | ||
| 494 | leonida::geometry_writes::notify(from, to, decommit ? leonida::geometry_writes::Event::replaced | ||
| 495 | : leonida::geometry_writes::Event::mapping); | ||
| 496 | } | ||
| 497 | } | ||
| 498 | |||
| 396 | // PVOID XMemVirtualAlloc(address, size, allocationType, attributes, protect). All 23 calls of the measured title pass a | 499 | // PVOID XMemVirtualAlloc(address, size, allocationType, attributes, protect). All 23 calls of the measured title pass a |
| 397 | // nonzero attribute word; its bits are not decoded and nothing on the host depends on them, so it is accepted and only | 500 | // nonzero attribute word; its bits are not decoded and nothing on the host depends on them, so it is accepted and only |
| 398 | // recorded (xmem_attributes). Its types cover committed 2 MiB and 64 KiB pages, reserve-only 64 KiB windows for physical pages, one | 501 | // recorded (xmem_attributes). Its types cover committed 2 MiB and 64 KiB pages, reserve-only 64 KiB windows for physical pages, one |
| @@ -407,7 +510,28 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, | |||
| 407 | void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect); | 510 | void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect); |
| 408 | // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which | 511 | // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which |
| 409 | // the copy also checks. | 512 | // the copy also checks. |
| 410 | if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(result), size); | 513 | if (result) { |
| 514 | leonida::title_memory_map::changed(); | ||
| 515 | leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(result), size); | ||
| 516 | note_unwatched_change(address, size, allocation_type, false); | ||
| 517 | if (allocation_type & MEM_RESERVE) { | ||
| 518 | const auto from = reinterpret_cast<uintptr_t>(result); | ||
| 519 | leonida::geometry_writes::notify(from, from + size, leonida::geometry_writes::Event::replaced); | ||
| 520 | } | ||
| 521 | } | ||
| 522 | // A reservation: a GPU-only one (no CPU access, PAGE_GRAPHICS_* bits) is paired with the CPU-mappable one of the | ||
| 523 | // same size made just before it (src/title_page_watch.h, title_gpu_views). | ||
| 524 | const DWORD host_type = allocation_type & kXmemHostAllocationTypeMask; | ||
| 525 | if (result && host_type && !(host_type & MEM_COMMIT)) { | ||
| 526 | const bool gpu_only = (protect & kPageGraphicsMask) && host_protect(protect) == PAGE_NOACCESS; | ||
| 527 | if (leonida::title_gpu_views::note_reservation(reinterpret_cast<uintptr_t>(result), size, gpu_only)) | ||
| 528 | std::fprintf(stderr, "[rt] xmem: GPU-only view %p (%llu MiB, protect 0x%lx) reads at the CPU view %p\n", | ||
| 529 | result, static_cast<unsigned long long>(size >> 20), static_cast<unsigned long>(protect), | ||
| 530 | reinterpret_cast<void*>(leonida::title_gpu_views::to_cpu(reinterpret_cast<uintptr_t>(result)))); | ||
| 531 | else if (gpu_only && size >= (64u << 20)) | ||
| 532 | std::fprintf(stderr, "[rt] xmem: GPU-only reservation %p (%llu MiB, protect 0x%lx) has no CPU view\n", result, | ||
| 533 | static_cast<unsigned long long>(size >> 20), static_cast<unsigned long>(protect)); | ||
| 534 | } | ||
| 411 | if(result)track_label_data(result,size,false); | 535 | if(result)track_label_data(result,size,false); |
| 412 | return result; | 536 | return result; |
| 413 | } | 537 | } |
| @@ -510,25 +634,96 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON | |||
| 510 | MEM_EXTENDED_PARAMETER parameter{}; | 634 | MEM_EXTENDED_PARAMETER parameter{}; |
| 511 | parameter.Type = MemExtendedParameterAddressRequirements; | 635 | parameter.Type = MemExtendedParameterAddressRequirements; |
| 512 | parameter.Pointer = &requirements; | 636 | parameter.Pointer = &requirements; |
| 513 | return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, host_type | MEM_RESERVE, host_prot, | 637 | return reserve_watched(host_type | MEM_RESERVE, nullptr, size, [&](DWORD type) { |
| 514 | ¶meter, 1); | 638 | return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, type, host_prot, ¶meter, 1); |
| 639 | }); | ||
| 515 | } | 640 | } |
| 516 | return VirtualAlloc(address, size, host_type, host_prot); | 641 | return reserve_watched(host_type, address, size, |
| 642 | [&](DWORD type) { return VirtualAlloc(address, size, type, host_prot); }); | ||
| 517 | } | 643 | } |
| 518 | 644 | ||
| 519 | // With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. | 645 | // With g_phys_mutex held. Maps `view` at the 64 KiB-aligned `address`, which holds no mapped page. MEM_REPLACE_PLACEHOLDER |
| 520 | bool unmap_page(uintptr_t address) { | 646 | // needs the view to fill one placeholder exactly, and earlier partial unmaps can leave several host placeholders in one |
| 521 | const FaultLockExclusive lock; | 647 | // run, so the run is mapped as one view per placeholder it spans. Views are capped at kMaxViewPages so that unmapping a |
| 522 | const auto it = g_mapped.find(address); | 648 | // page inside a long run only remaps the rest of one capped view, not the whole run. |
| 523 | if (it == g_mapped.end()) return true; | 649 | constexpr uint64_t kMaxViewPages = 1024; // 64 MiB |
| 524 | if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(address), | 650 | |
| 525 | MEM_PRESERVE_PLACEHOLDER)) { | 651 | |
| 526 | return false; | 652 | bool map_view(uintptr_t address, const View& view) { |
| 653 | for (uint64_t mapped = 0; mapped < view.count;) { | ||
| 654 | const uintptr_t base = address + mapped * kPhysicalPageSize; | ||
| 655 | void* const target = reinterpret_cast<void*>(base); | ||
| 656 | MEMORY_BASIC_INFORMATION info{}; | ||
| 657 | if (!VirtualQuery(target, &info, sizeof(info)) || info.State != MEM_RESERVE || | ||
| 658 | info.RegionSize < kPhysicalPageSize) { | ||
| 659 | SetLastError(ERROR_INVALID_ADDRESS); | ||
| 660 | return false; | ||
| 661 | } | ||
| 662 | const uint64_t available = info.RegionSize / kPhysicalPageSize; | ||
| 663 | const uint64_t remaining = view.count - mapped; | ||
| 664 | const uint64_t count = (std::min)({available, remaining, kMaxViewPages}); | ||
| 665 | const SIZE_T size = static_cast<SIZE_T>(count * kPhysicalPageSize); | ||
| 666 | const uint64_t offset = view.offset + mapped * kPhysicalPageSize; | ||
| 667 | if (!isolate_placeholder(target, size)) return false; | ||
| 668 | if (!placeholder_api().map_view3(view.section->handle, GetCurrentProcess(), target, offset, size, | ||
| 669 | MEM_REPLACE_PLACEHOLDER, view.protect, nullptr, 0)) { | ||
| 670 | return false; | ||
| 671 | } | ||
| 672 | leonida::title_memory_map::changed(); | ||
| 673 | g_views.emplace(base, View{count, view.section, offset, view.protect}); | ||
| 674 | mapped += count; | ||
| 675 | } | ||
| 676 | return true; | ||
| 677 | } | ||
| 678 | |||
| 679 | // With g_phys_mutex held. Unmaps every page in [start, end); the addresses become placeholders again. A view that | ||
| 680 | // reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so neighbours keep | ||
| 681 | // their pages. | ||
| 682 | // There is no rollback: if mapping a remainder again fails, those neighbouring pages stay unmapped and the caller only | ||
| 683 | // sees the failure. | ||
| 684 | bool unmap_range(uintptr_t start, uintptr_t end) { | ||
| 685 | const FaultLockExclusive lock; // faults on neighbouring pages wait through the split and remap | ||
| 686 | auto it = g_views.upper_bound(start); | ||
| 687 | if (it != g_views.begin()) { | ||
| 688 | const auto prev = std::prev(it); | ||
| 689 | if (prev->first + prev->second.count * kPhysicalPageSize > start) it = prev; | ||
| 690 | } | ||
| 691 | while (it != g_views.end() && it->first < end) { | ||
| 692 | const uintptr_t base = it->first; | ||
| 693 | const View view = it->second; | ||
| 694 | const uintptr_t view_end = base + view.count * kPhysicalPageSize; | ||
| 695 | if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(base), | ||
| 696 | MEM_PRESERVE_PLACEHOLDER)) { | ||
| 697 | return false; | ||
| 698 | } | ||
| 699 | leonida::title_memory_map::changed(); | ||
| 700 | leonida::geometry_writes::notify(base, view_end, leonida::geometry_writes::Event::replaced); | ||
| 701 | it = g_views.erase(it); | ||
| 702 | // The pages of [start, end) this view held are unmapped now; the ones outside it are mapped again below. | ||
| 703 | for (uintptr_t at = (std::max)(base, start); at < (std::min)(view_end, end); at += kPhysicalPageSize) { | ||
| 704 | if (const auto mapped = g_mapped.find(at); mapped != g_mapped.end()) { | ||
| 705 | note_mapping(mapped->second, at, false); | ||
| 706 | g_mapped.erase(mapped); | ||
| 707 | } | ||
| 708 | } | ||
| 709 | if (base < start) { | ||
| 710 | View left = view; | ||
| 711 | left.count = (start - base) / kPhysicalPageSize; | ||
| 712 | if (!map_view(base, left)) return false; | ||
| 713 | } | ||
| 714 | if (view_end > end) { | ||
| 715 | const uint64_t skipped = (end - base) / kPhysicalPageSize; | ||
| 716 | View right = view; | ||
| 717 | right.count = view.count - skipped; | ||
| 718 | right.offset += skipped * kPhysicalPageSize; | ||
| 719 | return map_view(end, right); // the last view the range touches | ||
| 720 | } | ||
| 527 | } | 721 | } |
| 528 | g_mapped.erase(it); | ||
| 529 | return true; | 722 | return true; |
| 530 | } | 723 | } |
| 531 | 724 | ||
| 725 | bool unmap_page(uintptr_t address) { return unmap_range(address, address + kPhysicalPageSize); } | ||
| 726 | |||
| 532 | // With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was | 727 | // With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was |
| 533 | // mapped there. The caller has found the window. | 728 | // mapped there. The caller has found the window. |
| 534 | bool map_page(uintptr_t address, uint64_t page, DWORD protect) { | 729 | bool map_page(uintptr_t address, uint64_t page, DWORD protect) { |
| @@ -539,22 +734,23 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { | |||
| 539 | SetLastError(ERROR_INVALID_PARAMETER); | 734 | SetLastError(ERROR_INVALID_PARAMETER); |
| 540 | return false; | 735 | return false; |
| 541 | } | 736 | } |
| 542 | void* const target = reinterpret_cast<void*>(address); | 737 | { |
| 543 | if (!isolate_placeholder(target, kPhysicalPageSize)) return false; | 738 | const FaultLockExclusive lock; |
| 544 | const FaultLockExclusive lock; | 739 | if (!map_view(address, View{1, it->second.section, it->second.offset, protect})) return false; |
| 545 | void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, | 740 | } |
| 546 | it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, | 741 | g_mapped[address] = page; |
| 547 | protect, nullptr, 0); | 742 | note_mapping(page, address, true); |
| 548 | if (!view) return false; | ||
| 549 | g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; | ||
| 550 | return true; | 743 | return true; |
| 551 | } | 744 | } |
| 552 | 745 | ||
| 553 | enum class PageCommit { not_ours, committed_before, committed_now, failed }; | 746 | enum class PageCommit { not_ours, committed_before, committed_now, failed }; |
| 554 | 747 | ||
| 555 | PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { | 748 | PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { |
| 556 | const auto it = g_mapped.find(address); | 749 | auto it = g_views.upper_bound(address); |
| 557 | if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; | 750 | if (it == g_views.begin()) return PageCommit::not_ours; |
| 751 | --it; | ||
| 752 | const uintptr_t within = address - it->first; | ||
| 753 | if (within / kPhysicalPageSize >= it->second.count || !it->second.section->scratch) return PageCommit::not_ours; | ||
| 558 | MEMORY_BASIC_INFORMATION info{}; | 754 | MEMORY_BASIC_INFORMATION info{}; |
| 559 | if (!VirtualQuery(reinterpret_cast<void*>(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { | 755 | if (!VirtualQuery(reinterpret_cast<void*>(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { |
| 560 | return PageCommit::not_ours; | 756 | return PageCommit::not_ours; |
| @@ -563,9 +759,11 @@ PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& prot | |||
| 563 | protect = info.Protect; | 759 | protect = info.Protect; |
| 564 | return PageCommit::committed_before; | 760 | return PageCommit::committed_before; |
| 565 | } | 761 | } |
| 566 | void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset; | 762 | void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset + within; |
| 567 | return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now | 763 | if (!VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return PageCommit::failed; |
| 568 | : PageCommit::failed; | 764 | leonida::geometry_writes::notify(address, address + kPhysicalPageSize, leonida::geometry_writes::Event::mapping); |
| 765 | leonida::title_memory_map::changed(); | ||
| 766 | return PageCommit::committed_now; | ||
| 569 | } | 767 | } |
| 570 | 768 | ||
| 571 | bool access_allowed(DWORD protect, ULONG_PTR access) { | 769 | bool access_allowed(DWORD protect, ULONG_PTR access) { |
| @@ -684,7 +882,8 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, | |||
| 684 | *page_count = 0; | 882 | *page_count = 0; |
| 685 | return FALSE; | 883 | return FALSE; |
| 686 | } | 884 | } |
| 687 | const auto section = std::make_shared<Section>(handle, use_file); | 885 | // From host_heap: the unmap that drops the last reference frees it under g_fault_lock. |
| 886 | const auto section = std::allocate_shared<Section>(leonida::host_heap::Allocator<Section>{}, handle, use_file); | ||
| 688 | if (!section->scratch) { | 887 | if (!section->scratch) { |
| 689 | *page_count = 0; | 888 | *page_count = 0; |
| 690 | return FALSE; | 889 | return FALSE; |
| @@ -717,12 +916,14 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra | |||
| 717 | for (uint64_t i = 0; i < page_count; ++i) { | 916 | for (uint64_t i = 0; i < page_count; ++i) { |
| 718 | const auto it = g_pages.find(page_array[i]); | 917 | const auto it = g_pages.find(page_array[i]); |
| 719 | if (it == g_pages.end()) { | 918 | if (it == g_pages.end()) { |
| 919 | if (i != 0) leonida::title_memory_map::changed(); | ||
| 720 | SetLastError(ERROR_INVALID_PARAMETER); | 920 | SetLastError(ERROR_INVALID_PARAMETER); |
| 721 | return FALSE; | 921 | return FALSE; |
| 722 | } | 922 | } |
| 723 | g_pages.erase(it); | 923 | g_pages.erase(it); |
| 724 | g_free_slots.push_back(page_array[i] / kFramesPerPage); | 924 | g_free_slots.push_back(page_array[i] / kFramesPerPage); |
| 725 | } | 925 | } |
| 926 | if (page_count != 0) leonida::title_memory_map::changed(); | ||
| 726 | return TRUE; | 927 | return TRUE; |
| 727 | } | 928 | } |
| 728 | 929 | ||
| @@ -731,8 +932,9 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra | |||
| 731 | // or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on | 932 | // or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on |
| 732 | // success. A page number of 0 in the array unmaps that one page. | 933 | // success. A page number of 0 in the array unmaps that one page. |
| 733 | // | 934 | // |
| 734 | // Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later | 935 | // Consecutive pages of one allocation are mapped as one view (MapViewOfFile3 into a placeholder of their size); a |
| 735 | // without touching its neighbours. A failure part-way leaves the pages before it mapped. | 936 | // page remapped or unmapped later splits its view, and its neighbours stay mapped. The range is unmapped first, so a |
| 937 | // page number that is not a live page fails with the pages before it mapped and the rest of the range unmapped. | ||
| 736 | void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { | 938 | void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { |
| 737 | const uintptr_t start = reinterpret_cast<uintptr_t>(address); | 939 | const uintptr_t start = reinterpret_cast<uintptr_t>(address); |
| 738 | if (!aligned_page_address(start) || page_count > (std::numeric_limits<uintptr_t>::max)() / kPhysicalPageSize || | 940 | if (!aligned_page_address(start) || page_count > (std::numeric_limits<uintptr_t>::max)() / kPhysicalPageSize || |
| @@ -745,20 +947,46 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint | |||
| 745 | return nullptr; | 947 | return nullptr; |
| 746 | } | 948 | } |
| 747 | const std::lock_guard lock(g_phys_mutex); | 949 | const std::lock_guard lock(g_phys_mutex); |
| 748 | if (!page_array) { | 950 | const uintptr_t end = start + page_count * kPhysicalPageSize; |
| 749 | for (uint64_t i = 0; i < page_count; ++i) { | 951 | if (!page_array) return unmap_range(start, end) ? address : nullptr; |
| 750 | if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr; | ||
| 751 | } | ||
| 752 | return address; | ||
| 753 | } | ||
| 754 | const Window* const window = find_window(start, page_count * kPhysicalPageSize); | 952 | const Window* const window = find_window(start, page_count * kPhysicalPageSize); |
| 755 | if (!window) { | 953 | if (!window) { |
| 756 | SetLastError(ERROR_INVALID_ADDRESS); | 954 | SetLastError(ERROR_INVALID_ADDRESS); |
| 757 | return nullptr; | 955 | return nullptr; |
| 758 | } | 956 | } |
| 759 | const DWORD protect = view_protect(*window); | 957 | const DWORD protect = view_protect(*window); |
| 760 | for (uint64_t i = 0; i < page_count; ++i) { | 958 | if (!unmap_range(start, end)) return nullptr; |
| 761 | if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr; | 959 | for (uint64_t i = 0; i < page_count;) { |
| 960 | if (page_array[i] == 0) { | ||
| 961 | ++i; | ||
| 962 | continue; | ||
| 963 | } | ||
| 964 | const auto it = g_pages.find(page_array[i]); | ||
| 965 | if (it == g_pages.end()) { | ||
| 966 | SetLastError(ERROR_INVALID_PARAMETER); | ||
| 967 | return nullptr; | ||
| 968 | } | ||
| 969 | View view{1, it->second.section, it->second.offset, protect}; | ||
| 970 | while (i + view.count < page_count) { | ||
| 971 | const auto next = g_pages.find(page_array[i + view.count]); | ||
| 972 | if (next == g_pages.end() || next->second.section != view.section || | ||
| 973 | next->second.offset != view.offset + view.count * kPhysicalPageSize) { | ||
| 974 | break; | ||
| 975 | } | ||
| 976 | ++view.count; | ||
| 977 | } | ||
| 978 | { | ||
| 979 | const FaultLockExclusive view_lock; | ||
| 980 | if (!map_view(start + i * kPhysicalPageSize, view)) return nullptr; | ||
| 981 | } | ||
| 982 | // After the fault lock: page_array is the title's memory, and a read of it that faults would wait for the | ||
| 983 | // lock on this thread. g_mapped and the aliases are g_phys_mutex's; the fault handler reads neither. | ||
| 984 | for (uint64_t k = 0; k < view.count; ++k) { | ||
| 985 | const uintptr_t at = start + (i + k) * kPhysicalPageSize; | ||
| 986 | g_mapped[at] = page_array[i + k]; | ||
| 987 | note_mapping(page_array[i + k], at, true); | ||
| 988 | } | ||
| 989 | i += view.count; | ||
| 762 | } | 990 | } |
| 763 | return address; | 991 | return address; |
| 764 | } | 992 | } |
| @@ -798,12 +1026,24 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co | |||
| 798 | return TRUE; | 1026 | return TRUE; |
| 799 | } | 1027 | } |
| 800 | 1028 | ||
| 1029 | // The title's write watching, on reservations it made with MEM_WRITE_WATCH. One xmem write-watched for the shadows | ||
| 1030 | // (reserve_watched) is refused as the host refuses a region that is not write-watched ((UINT)-1, | ||
| 1031 | // ERROR_INVALID_PARAMETER), as the console would: it isn't write-watched there, and a reset here would clear the bits | ||
| 1032 | // the shadows ask about. | ||
| 1033 | bool shadows_write_watch(const void* base_address) { | ||
| 1034 | if (!leonida::title_write_watch::contains(reinterpret_cast<uintptr_t>(base_address))) return false; | ||
| 1035 | SetLastError(ERROR_INVALID_PARAMETER); | ||
| 1036 | return true; | ||
| 1037 | } | ||
| 1038 | |||
| 801 | UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, | 1039 | UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, |
| 802 | ULONG* granularity) { | 1040 | ULONG* granularity) { |
| 1041 | if (shadows_write_watch(base_address)) return UINT(-1); | ||
| 803 | return GetWriteWatch(flags, base_address, region_size, addresses, count, granularity); | 1042 | return GetWriteWatch(flags, base_address, region_size, addresses, count, granularity); |
| 804 | } | 1043 | } |
| 805 | 1044 | ||
| 806 | UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) { | 1045 | UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) { |
| 1046 | if (shadows_write_watch(base_address)) return UINT(-1); | ||
| 807 | return ResetWriteWatch(base_address, region_size); | 1047 | return ResetWriteWatch(base_address, region_size); |
| 808 | } | 1048 | } |
| 809 | 1049 | ||
| @@ -863,12 +1103,38 @@ BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) { | |||
| 863 | constexpr DWORD kMemGraphics = 0x10000000; | 1103 | constexpr DWORD kMemGraphics = 0x10000000; |
| 864 | constexpr DWORD kMemTitle = 0x40000000; | 1104 | constexpr DWORD kMemTitle = 0x40000000; |
| 865 | 1105 | ||
| 866 | BOOL WINAPI TitleVirtualFree(LPVOID address,SIZE_T size,DWORD flags) { | 1106 | // A new reservation is write-watched for the D3D12 layer's shadows (reserve_watched). |
| 1107 | LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { | ||
| 1108 | const DWORD type = allocation_type & ~(kMemGraphics | kMemTitle); | ||
| 1109 | const DWORD host_prot = host_protect(protect); | ||
| 1110 | LPVOID result = | ||
| 1111 | reserve_watched(type, address, size, [&](DWORD t) { return VirtualAlloc(address, size, t, host_prot); }); | ||
| 1112 | if (result) { | ||
| 1113 | leonida::title_memory_map::changed(); | ||
| 1114 | leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(result), size); | ||
| 1115 | note_unwatched_change(address, size, type, false); | ||
| 1116 | if (type & MEM_RESERVE) { | ||
| 1117 | const auto from = reinterpret_cast<uintptr_t>(result); | ||
| 1118 | leonida::geometry_writes::notify(from, from + size, leonida::geometry_writes::Event::replaced); | ||
| 1119 | } | ||
| 1120 | } | ||
| 1121 | if(result)track_label_data(result,size,false); | ||
| 1122 | return result; | ||
| 1123 | } | ||
| 1124 | |||
| 1125 | // The pages are freed with the GPU label regions locked (src/gpu_label_memory.h), so a completed label is never | ||
| 1126 | // stored into pages that are going away. | ||
| 1127 | BOOL WINAPI TitleVirtualFree(LPVOID address, SIZE_T size, DWORD free_type) { | ||
| 867 | DWORD saved=0; | 1128 | DWORD saved=0; |
| 868 | const bool ok=leonida::label::memory().release_pages(reinterpret_cast<std::uintptr_t>(address),size,(flags&MEM_RELEASE)!=0,[&]{ | 1129 | const bool result=leonida::label::memory().release_pages(reinterpret_cast<std::uintptr_t>(address),size,(free_type&MEM_RELEASE)!=0,[&]{ |
| 869 | const BOOL r=::VirtualFree(address,size,flags);saved=GetLastError();return !!r; | 1130 | const BOOL r=::VirtualFree(address,size,free_type);saved=GetLastError();return !!r; |
| 870 | }); | 1131 | }); |
| 871 | SetLastError(saved);return ok?TRUE:FALSE; | 1132 | if (result) leonida::title_memory_map::changed(); |
| 1133 | if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true); | ||
| 1134 | if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER)) | ||
| 1135 | leonida::title_write_watch::remove(reinterpret_cast<uintptr_t>(address)); | ||
| 1136 | SetLastError(saved); | ||
| 1137 | return result ? TRUE : FALSE; | ||
| 872 | } | 1138 | } |
| 873 | BOOL WINAPI TitleVirtualFreeEx(HANDLE process,LPVOID address,SIZE_T size,DWORD flags) { | 1139 | BOOL WINAPI TitleVirtualFreeEx(HANDLE process,LPVOID address,SIZE_T size,DWORD flags) { |
| 874 | if(GetProcessId(process)!=GetCurrentProcessId())return ::VirtualFreeEx(process,address,size,flags); | 1140 | if(GetProcessId(process)!=GetCurrentProcessId())return ::VirtualFreeEx(process,address,size,flags); |
| @@ -879,10 +1145,13 @@ BOOL WINAPI TitleVirtualFreeEx(HANDLE process,LPVOID address,SIZE_T size,DWORD f | |||
| 879 | SetLastError(saved);return ok?TRUE:FALSE; | 1145 | SetLastError(saved);return ok?TRUE:FALSE; |
| 880 | } | 1146 | } |
| 881 | 1147 | ||
| 882 | LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { | 1148 | BOOL WINAPI TitleVirtualProtect(LPVOID address, SIZE_T size, DWORD protect, PDWORD old) { |
| 883 | LPVOID result = VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); | 1149 | const BOOL result = VirtualProtect(address, size, protect, old); |
| 884 | if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast<uintptr_t>(result), size); | 1150 | if (result) { |
| 885 | if(result)track_label_data(result,size,false); | 1151 | leonida::title_memory_map::changed(); |
| 1152 | const auto start = reinterpret_cast<uintptr_t>(address); | ||
| 1153 | leonida::geometry_writes::notify(start, start + size, leonida::geometry_writes::Event::replaced); | ||
| 1154 | } | ||
| 886 | return result; | 1155 | return result; |
| 887 | } | 1156 | } |
| 888 | 1157 | ||
| @@ -890,6 +1159,15 @@ LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_ty | |||
| 890 | 1159 | ||
| 891 | namespace rt::xmem { | 1160 | namespace rt::xmem { |
| 892 | 1161 | ||
| 1162 | void geometry_aliases(std::uintptr_t va, std::vector<std::uintptr_t>& addresses) { | ||
| 1163 | std::lock_guard lock(g_phys_mutex); | ||
| 1164 | const auto mapped = g_mapped.find(va); | ||
| 1165 | if (mapped == g_mapped.end()) return; | ||
| 1166 | const auto peers = g_page_addresses.find(mapped->second); | ||
| 1167 | if (peers != g_page_addresses.end()) | ||
| 1168 | for (auto other : peers->second) if (other != va) addresses.push_back(other); | ||
| 1169 | } | ||
| 1170 | |||
| 893 | bool commit_physical_range(const void* address, size_t size) { | 1171 | bool commit_physical_range(const void* address, size_t size) { |
| 894 | if (size == 0) return true; | 1172 | if (size == 0) return true; |
| 895 | const uintptr_t start = reinterpret_cast<uintptr_t>(address); | 1173 | const uintptr_t start = reinterpret_cast<uintptr_t>(address); |
| @@ -915,13 +1193,24 @@ std::shared_ptr<std::uint8_t> pin_mapped_data(const void* address, std::size_t s | |||
| 915 | const auto end = start + size; | 1193 | const auto end = start + size; |
| 916 | const auto first = start & ~std::uintptr_t(kPhysicalPageSize - 1); | 1194 | const auto first = start & ~std::uintptr_t(kPhysicalPageSize - 1); |
| 917 | const FaultLockShared lock; | 1195 | const FaultLockShared lock; |
| 918 | const auto base = g_mapped.find(first); | 1196 | // The view that holds a page: a run of pages is one view, or several after a partial unmap. |
| 919 | if (base == g_mapped.end() || !base->second.section || !base->second.section->scratch) return {}; | 1197 | const auto view_of = [](std::uintptr_t page) { |
| 1198 | auto it = g_views.upper_bound(page); | ||
| 1199 | if (it == g_views.begin()) return g_views.end(); | ||
| 1200 | --it; | ||
| 1201 | return (page - it->first) / kPhysicalPageSize < it->second.count ? it : g_views.end(); | ||
| 1202 | }; | ||
| 1203 | const auto base = view_of(first); | ||
| 1204 | if (base == g_views.end() || !base->second.section || !base->second.section->scratch) return {}; | ||
| 920 | const auto section = base->second.section; | 1205 | const auto section = base->second.section; |
| 921 | const auto offset = base->second.offset; | 1206 | const auto offset = base->second.offset + (first - base->first); |
| 1207 | // A view the title mapped writable can be read-only for a while: the D3D12 layer guards the pages its shadows | ||
| 1208 | // copy and opens them again at the title's next write. | ||
| 1209 | bool writable = true; | ||
| 922 | for (auto page=first; page<end; page+=kPhysicalPageSize) { | 1210 | for (auto page=first; page<end; page+=kPhysicalPageSize) { |
| 923 | const auto it = g_mapped.find(page); | 1211 | const auto it = view_of(page); |
| 924 | if (it==g_mapped.end() || it->second.section != section || it->second.offset != offset+page-first) return {}; | 1212 | if (it==g_views.end() || it->second.section != section || it->second.offset+(page-it->first) != offset+page-first) return {}; |
| 1213 | if ((it->second.protect & 255)!=PAGE_READWRITE && (it->second.protect & 255)!=PAGE_WRITECOPY) writable = false; | ||
| 925 | DWORD previous{}; | 1214 | DWORD previous{}; |
| 926 | const auto ready = commit_mapped_page(page, std::max(page,start), previous); | 1215 | const auto ready = commit_mapped_page(page, std::max(page,start), previous); |
| 927 | if (ready!=PageCommit::committed_before && ready!=PageCommit::committed_now) return {}; | 1216 | if (ready!=PageCommit::committed_before && ready!=PageCommit::committed_now) return {}; |
| @@ -930,19 +1219,19 @@ std::shared_ptr<std::uint8_t> pin_mapped_data(const void* address, std::size_t s | |||
| 930 | MEMORY_BASIC_INFORMATION info{}; | 1219 | MEMORY_BASIC_INFORMATION info{}; |
| 931 | if (!VirtualQuery(reinterpret_cast<const void*>(at), &info, sizeof(info)) || | 1220 | if (!VirtualQuery(reinterpret_cast<const void*>(at), &info, sizeof(info)) || |
| 932 | info.Type!=MEM_MAPPED || info.State!=MEM_COMMIT || (info.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || | 1221 | info.Type!=MEM_MAPPED || info.State!=MEM_COMMIT || (info.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || |
| 933 | ((info.Protect & 255)!=PAGE_READWRITE && (info.Protect & 255)!=PAGE_WRITECOPY)) return {}; | 1222 | ((info.Protect & 255)!=PAGE_READWRITE && (info.Protect & 255)!=PAGE_WRITECOPY && |
| 1223 | !(writable && (info.Protect & 255)==PAGE_READONLY))) return {}; | ||
| 934 | at=reinterpret_cast<std::uintptr_t>(info.BaseAddress)+info.RegionSize; | 1224 | at=reinterpret_cast<std::uintptr_t>(info.BaseAddress)+info.RegionSize; |
| 935 | } | 1225 | } |
| 936 | return {section,static_cast<std::uint8_t*>(section->scratch)+offset+(start-first)}; | 1226 | return {section,static_cast<std::uint8_t*>(section->scratch)+offset+(start-first)}; |
| 937 | } | 1227 | } |
| 938 | 1228 | ||
| 939 | bool commit_physical_pages(const uint64_t* page_array, size_t count) { | 1229 | static bool commit_pages_locked(const uint64_t* page_array, size_t count) { |
| 940 | if (count == 0) return true; | 1230 | if (count == 0) return true; |
| 941 | if (!page_array) { | 1231 | if (!page_array) { |
| 942 | SetLastError(ERROR_INVALID_PARAMETER); | 1232 | SetLastError(ERROR_INVALID_PARAMETER); |
| 943 | return false; | 1233 | return false; |
| 944 | } | 1234 | } |
| 945 | const std::lock_guard lock(g_phys_mutex); | ||
| 946 | size_t first = 0; | 1235 | size_t first = 0; |
| 947 | while (first < count) { | 1236 | while (first < count) { |
| 948 | const auto it = g_pages.find(page_array[first]); | 1237 | const auto it = g_pages.find(page_array[first]); |
| @@ -961,26 +1250,69 @@ bool commit_physical_pages(const uint64_t* page_array, size_t count) { | |||
| 961 | } | 1250 | } |
| 962 | void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset; | 1251 | void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset; |
| 963 | if (!it->second.section->file_backed && !VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; | 1252 | if (!it->second.section->file_backed && !VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; |
| 1253 | leonida::title_memory_map::changed(); | ||
| 964 | first = last; | 1254 | first = last; |
| 965 | } | 1255 | } |
| 966 | return true; | 1256 | return true; |
| 967 | } | 1257 | } |
| 968 | 1258 | ||
| 1259 | bool commit_physical_pages(const uint64_t* page_array, size_t count) { | ||
| 1260 | const std::lock_guard lock(g_phys_mutex); | ||
| 1261 | return commit_pages_locked(page_array, count); | ||
| 1262 | } | ||
| 1263 | |||
| 1264 | bool transfer_physical(std::span<const uint64_t> pages, uint16_t offset, std::span<uint8_t> staging, bool write) { | ||
| 1265 | if (staging.empty()) return true; | ||
| 1266 | if (pages.size() != 1 + (staging.size() - 1 + offset) / kPhysicalPageSize) { | ||
| 1267 | SetLastError(ERROR_INVALID_PARAMETER); | ||
| 1268 | return false; | ||
| 1269 | } | ||
| 1270 | const std::lock_guard lock(g_phys_mutex); | ||
| 1271 | if (!commit_pages_locked(pages.data(), pages.size())) return false; | ||
| 1272 | for (const auto page : pages) { | ||
| 1273 | const auto& backing = g_pages.at(page); | ||
| 1274 | auto* ptr = static_cast<uint8_t*>(backing.section->scratch) + backing.offset + offset; | ||
| 1275 | const size_t bytes = (std::min)(staging.size(), size_t(kPhysicalPageSize - offset)); | ||
| 1276 | if (write) { | ||
| 1277 | std::memcpy(ptr, staging.data(), bytes); | ||
| 1278 | if (auto mapped = g_page_addresses.find(page); mapped != g_page_addresses.end()) { | ||
| 1279 | for (uintptr_t address : mapped->second) { | ||
| 1280 | leonida::geometry_writes::notify(address + offset, address + offset + bytes, leonida::geometry_writes::Event::write); | ||
| 1281 | leonida::title_texel_writes::note(reinterpret_cast<void*>(address + offset), bytes); | ||
| 1282 | if (leonida::dstorage::trace_enabled()) | ||
| 1283 | std::fprintf(stderr, "[rt] ds-scatter cpu=%llx bytes=%zu page=%llu\n", | ||
| 1284 | static_cast<unsigned long long>(address + offset), bytes, | ||
| 1285 | static_cast<unsigned long long>(page)); | ||
| 1286 | } | ||
| 1287 | } | ||
| 1288 | } else { | ||
| 1289 | std::memcpy(staging.data(), ptr, bytes); | ||
| 1290 | } | ||
| 1291 | staging = staging.subspan(bytes); | ||
| 1292 | offset = 0; | ||
| 1293 | } | ||
| 1294 | return true; | ||
| 1295 | } | ||
| 1296 | |||
| 969 | } | 1297 | } |
| 970 | 1298 | ||
| 971 | #define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast<void*>(&TitleVirtualAlloc)}, {dll,"VirtualFree",reinterpret_cast<void*>(&TitleVirtualFree)}, {dll,"VirtualFreeEx",reinterpret_cast<void*>(&TitleVirtualFreeEx)} | 1299 | #define TITLE_VIRTUAL_MEMORY(dll) \ |
| 1300 | {dll, "VirtualAlloc", reinterpret_cast<void*>(&TitleVirtualAlloc)}, \ | ||
| 1301 | {dll, "VirtualFree", reinterpret_cast<void*>(&TitleVirtualFree)}, \ | ||
| 1302 | {dll, "VirtualFreeEx", reinterpret_cast<void*>(&TitleVirtualFreeEx)}, \ | ||
| 1303 | {dll, "VirtualProtect", reinterpret_cast<void*>(&TitleVirtualProtect)} | ||
| 972 | 1304 | ||
| 973 | // The classic libraries and the memory api sets a title's imports name. | 1305 | // The classic libraries and the memory api sets a title's imports name. |
| 974 | SHIM_TABLE(title_memory, | 1306 | SHIM_TABLE(title_memory, |
| 975 | TITLE_VIRTUAL_ALLOC("kernel32.dll"), | 1307 | TITLE_VIRTUAL_MEMORY("kernel32.dll"), |
| 976 | TITLE_VIRTUAL_ALLOC("kernelbase.dll"), | 1308 | TITLE_VIRTUAL_MEMORY("kernelbase.dll"), |
| 977 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-0.dll"), | 1309 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-0.dll"), |
| 978 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-1.dll"), | 1310 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-1.dll"), |
| 979 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-2.dll"), | 1311 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-2.dll"), |
| 980 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-3.dll"), | 1312 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-3.dll"), |
| 981 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-4.dll"), | 1313 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-4.dll"), |
| 982 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-5.dll"), | 1314 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-5.dll"), |
| 983 | TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-6.dll"), | 1315 | TITLE_VIRTUAL_MEMORY("api-ms-win-core-memory-l1-1-6.dll"), |
| 984 | ); | 1316 | ); |
| 985 | 1317 | ||
| 986 | SHIM_TABLE(xmem, | 1318 | SHIM_TABLE(xmem, |