upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims/xmem.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/shims/xmem.cpp')
-rw-r--r--runtime/shims/xmem.cpp200
1 files changed, 173 insertions, 27 deletions
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index 75f927458..97ee60571 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -18,6 +18,7 @@
18#include <malloc.h> 18#include <malloc.h>
19#include <psapi.h> 19#include <psapi.h>
20 20
21#include <algorithm>
21#include <atomic> 22#include <atomic>
22#include <cstdint> 23#include <cstdint>
23#include <cstdio> 24#include <cstdio>
@@ -261,7 +262,82 @@ std::map<uintptr_t, Window> g_windows; // base -> window
261std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing 262std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing
262std::vector<uint64_t> g_free_slots; 263std::vector<uint64_t> g_free_slots;
263uint64_t g_next_slot = 1; 264uint64_t g_next_slot = 1;
264std::unordered_map<uintptr_t, uint64_t> g_mapped; // mapped 64 KiB address -> page number 265// A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run
266// rather than per page: under Wine each view costs a placeholder split and a section map whose time grows with the
267// number of views, and the retail title maps about 100,000 pages in one call.
268struct View {
269 uint64_t count;
270 std::shared_ptr<Section> section; // kept for remapping part of the run after its pages are freed
271 uint64_t offset; // section offset of the first page
272 DWORD protect;
273};
274std::map<uintptr_t, View> g_views; // view base -> view
275
276// Splitting a view (unmap_range) unmaps it whole and maps its remainders again, so for that moment pages the caller
277// did not name are unmapped. On the console they stay mapped, and another thread may be reading them. The span being
278// split is published here, and a vectored handler makes a thread that faults inside it wait for the remap, then
279// retries the access. The last finished split stays published too, for a fault the handler sees only after the split
280// is done; any other access violation goes on to the next handler.
281// Only the last finished span is kept, so a fault delivered after two later splits is not retried.
282// A span is one word, so a reader never pairs one split's start with another's end: views are 64 KiB aligned and at
283// most kMaxViewPages long, so the base keeps its low 16 bits for the page count. 0 is no span.
284std::atomic<uint64_t> g_split{0};
285std::atomic<uint64_t> g_last_split{0};
286std::atomic<uint64_t> g_splits{0}; // splits started
287
288uint64_t pack_span(uintptr_t begin, uintptr_t end) { return begin | (end - begin) / kPhysicalPageSize; }
289
290bool span_holds(uint64_t span, uintptr_t address) {
291 const uintptr_t begin = span & ~uint64_t{0xffff};
292 return span && address >= begin && address < begin + (span & 0xffff) * kPhysicalPageSize;
293}
294bool g_split_handler = false; // with g_phys_mutex held
295
296LONG CALLBACK wait_for_split(EXCEPTION_POINTERS* info) {
297 const EXCEPTION_RECORD& record = *info->ExceptionRecord;
298 if (record.ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record.NumberParameters < 2) {
299 return EXCEPTION_CONTINUE_SEARCH;
300 }
301 const ULONG_PTR access = record.ExceptionInformation[0]; // 0 read, 1 write, 8 execute
302 const uintptr_t address = record.ExceptionInformation[1];
303 if (access != 0 && access != 1) return EXCEPTION_CONTINUE_SEARCH;
304 for (;;) {
305 const uint64_t splits = g_splits.load(std::memory_order_acquire);
306 bool in_split = false;
307 while (span_holds(g_split.load(std::memory_order_acquire), address)) {
308 in_split = true;
309 SwitchToThread();
310 }
311 in_split = in_split || span_holds(g_last_split.load(std::memory_order_acquire), address);
312 if (!in_split) return EXCEPTION_CONTINUE_SEARCH;
313 // Retry only an access the page now allows: the fault may have come in during a split that has since finished.
314 MEMORY_BASIC_INFORMATION mbi{};
315 if (VirtualQuery(reinterpret_cast<void*>(address), &mbi, sizeof(mbi)) && mbi.State == MEM_COMMIT &&
316 mbi.Type == MEM_MAPPED) {
317 const DWORD protect = mbi.Protect & 0xff;
318 const bool allowed =
319 access == 1 ? protect == PAGE_READWRITE : protect == PAGE_READWRITE || protect == PAGE_READONLY;
320 return allowed ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
321 }
322 // Not mapped. A split that started since the wait ended may have unmapped it again: wait for that one too.
323 if (g_splits.load(std::memory_order_acquire) == splits) return EXCEPTION_CONTINUE_SEARCH;
324 }
325}
326
327// With g_phys_mutex held: publishes [begin, end) as being split until it goes out of scope.
328struct SplitGuard {
329 SplitGuard(uintptr_t begin, uintptr_t end) {
330 if (!g_split_handler) g_split_handler = AddVectoredExceptionHandler(1, &wait_for_split) != nullptr;
331 g_split.store(pack_span(begin, end), std::memory_order_release);
332 g_splits.fetch_add(1, std::memory_order_release);
333 }
334 ~SplitGuard() {
335 g_last_split.store(g_split.load(std::memory_order_relaxed), std::memory_order_release);
336 g_split.store(0, std::memory_order_release);
337 }
338 SplitGuard(const SplitGuard&) = delete;
339 SplitGuard& operator=(const SplitGuard&) = delete;
340};
265 341
266// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with 342// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with
267// kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. 343// kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again.
@@ -425,18 +501,78 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
425 return VirtualAlloc(address, size, host_type, host_prot); 501 return VirtualAlloc(address, size, host_type, host_prot);
426} 502}
427 503
428// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. 504// With g_phys_mutex held. Maps `view` at the 64 KiB-aligned `address`, which holds no mapped page. MEM_REPLACE_PLACEHOLDER
429bool unmap_page(uintptr_t address) { 505// needs the view to fill one placeholder exactly, and earlier partial unmaps can leave several host placeholders in one
430 const auto it = g_mapped.find(address); 506// run, so the run is mapped as one view per placeholder it spans. Views are capped at kMaxViewPages so that unmapping a
431 if (it == g_mapped.end()) return true; 507// page inside a long run only remaps the rest of one capped view, not the whole run.
432 if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(address), 508constexpr uint64_t kMaxViewPages = 1024; // 64 MiB
433 MEM_PRESERVE_PLACEHOLDER)) { 509static_assert(kMaxViewPages < 0x10000, "a split span keeps its page count in 16 bits");
434 return false; 510
511bool map_view(uintptr_t address, const View& view) {
512 for (uint64_t mapped = 0; mapped < view.count;) {
513 const uintptr_t base = address + mapped * kPhysicalPageSize;
514 void* const target = reinterpret_cast<void*>(base);
515 MEMORY_BASIC_INFORMATION info{};
516 if (!VirtualQuery(target, &info, sizeof(info)) || info.State != MEM_RESERVE ||
517 info.RegionSize < kPhysicalPageSize) {
518 SetLastError(ERROR_INVALID_ADDRESS);
519 return false;
520 }
521 const uint64_t available = info.RegionSize / kPhysicalPageSize;
522 const uint64_t remaining = view.count - mapped;
523 const uint64_t count = (std::min)({available, remaining, kMaxViewPages});
524 const SIZE_T size = static_cast<SIZE_T>(count * kPhysicalPageSize);
525 const uint64_t offset = view.offset + mapped * kPhysicalPageSize;
526 if (!isolate_placeholder(target, size)) return false;
527 if (!placeholder_api().map_view3(view.section->handle, GetCurrentProcess(), target, offset, size,
528 MEM_REPLACE_PLACEHOLDER, view.protect, nullptr, 0)) {
529 return false;
530 }
531 g_views.emplace(base, View{count, view.section, offset, view.protect});
532 mapped += count;
533 }
534 return true;
535}
536
537// With g_phys_mutex held. Unmaps every page in [start, end); the addresses become placeholders again. A view that
538// reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so neighbours keep
539// their pages.
540// There is no rollback: if mapping a remainder again fails, those neighbouring pages stay unmapped and the caller only
541// sees the failure.
542bool unmap_range(uintptr_t start, uintptr_t end) {
543 auto it = g_views.upper_bound(start);
544 if (it != g_views.begin()) {
545 const auto prev = std::prev(it);
546 if (prev->first + prev->second.count * kPhysicalPageSize > start) it = prev;
547 }
548 while (it != g_views.end() && it->first < end) {
549 const uintptr_t base = it->first;
550 const View view = it->second;
551 const uintptr_t view_end = base + view.count * kPhysicalPageSize;
552 const SplitGuard guard(base, view_end);
553 if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(base),
554 MEM_PRESERVE_PLACEHOLDER)) {
555 return false;
556 }
557 it = g_views.erase(it);
558 if (base < start) {
559 View left = view;
560 left.count = (start - base) / kPhysicalPageSize;
561 if (!map_view(base, left)) return false;
562 }
563 if (view_end > end) {
564 const uint64_t skipped = (end - base) / kPhysicalPageSize;
565 View right = view;
566 right.count = view.count - skipped;
567 right.offset += skipped * kPhysicalPageSize;
568 return map_view(end, right); // the last view the range touches
569 }
435 } 570 }
436 g_mapped.erase(it);
437 return true; 571 return true;
438} 572}
439 573
574bool unmap_page(uintptr_t address) { return unmap_range(address, address + kPhysicalPageSize); }
575
440// With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was 576// With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was
441// mapped there. The caller has found the window. 577// mapped there. The caller has found the window.
442bool map_page(uintptr_t address, uint64_t page, DWORD protect) { 578bool map_page(uintptr_t address, uint64_t page, DWORD protect) {
@@ -447,14 +583,7 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) {
447 SetLastError(ERROR_INVALID_PARAMETER); 583 SetLastError(ERROR_INVALID_PARAMETER);
448 return false; 584 return false;
449 } 585 }
450 void* const target = reinterpret_cast<void*>(address); 586 return map_view(address, View{1, it->second.section, it->second.offset, protect});
451 if (!isolate_placeholder(target, kPhysicalPageSize)) return false;
452 void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target,
453 it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER,
454 protect, nullptr, 0);
455 if (!view) return false;
456 g_mapped[address] = page;
457 return true;
458} 587}
459 588
460// Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still 589// Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still
@@ -561,8 +690,9 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra
561// or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on 690// or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on
562// success. A page number of 0 in the array unmaps that one page. 691// success. A page number of 0 in the array unmaps that one page.
563// 692//
564// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later 693// Consecutive pages of one allocation are mapped as one view (MapViewOfFile3 into a placeholder of their size); a
565// without touching its neighbours. A failure part-way leaves the pages before it mapped. 694// page remapped or unmapped later splits its view, and its neighbours stay mapped. The range is unmapped first, so a
695// page number that is not a live page fails with the pages before it mapped and the rest of the range unmapped.
566void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { 696void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) {
567 const uintptr_t start = reinterpret_cast<uintptr_t>(address); 697 const uintptr_t start = reinterpret_cast<uintptr_t>(address);
568 if (!aligned_page_address(start) || page_count > (std::numeric_limits<uintptr_t>::max)() / kPhysicalPageSize || 698 if (!aligned_page_address(start) || page_count > (std::numeric_limits<uintptr_t>::max)() / kPhysicalPageSize ||
@@ -575,20 +705,36 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint
575 return nullptr; 705 return nullptr;
576 } 706 }
577 const std::lock_guard lock(g_phys_mutex); 707 const std::lock_guard lock(g_phys_mutex);
578 if (!page_array) { 708 const uintptr_t end = start + page_count * kPhysicalPageSize;
579 for (uint64_t i = 0; i < page_count; ++i) { 709 if (!page_array) return unmap_range(start, end) ? address : nullptr;
580 if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr;
581 }
582 return address;
583 }
584 const Window* const window = find_window(start, page_count * kPhysicalPageSize); 710 const Window* const window = find_window(start, page_count * kPhysicalPageSize);
585 if (!window) { 711 if (!window) {
586 SetLastError(ERROR_INVALID_ADDRESS); 712 SetLastError(ERROR_INVALID_ADDRESS);
587 return nullptr; 713 return nullptr;
588 } 714 }
589 const DWORD protect = view_protect(*window); 715 const DWORD protect = view_protect(*window);
590 for (uint64_t i = 0; i < page_count; ++i) { 716 if (!unmap_range(start, end)) return nullptr;
591 if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr; 717 for (uint64_t i = 0; i < page_count;) {
718 if (page_array[i] == 0) {
719 ++i;
720 continue;
721 }
722 const auto it = g_pages.find(page_array[i]);
723 if (it == g_pages.end()) {
724 SetLastError(ERROR_INVALID_PARAMETER);
725 return nullptr;
726 }
727 View view{1, it->second.section, it->second.offset, protect};
728 while (i + view.count < page_count) {
729 const auto next = g_pages.find(page_array[i + view.count]);
730 if (next == g_pages.end() || next->second.section != view.section ||
731 next->second.offset != view.offset + view.count * kPhysicalPageSize) {
732 break;
733 }
734 ++view.count;
735 }
736 if (!map_view(start + i * kPhysicalPageSize, view)) return nullptr;
737 i += view.count;
592 } 738 }
593 return address; 739 return address;
594} 740}