#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include "prx/libSceAgcDriver/Execution/include/PageDigest.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/WriteWatchCoverage.hpp" #include "prx/libSceAgcDriver/Execution/include/ThreadScratch.hpp" #include "ThreadOwned.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/General.hpp" #include "prx/libc/include/GuestArena.hpp" #include "prx/libc/include/GuestWriteWatch.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include "prx/libc/include/HostThreadSlot.hpp" #include "prx/libc/include/HostThread.hpp" #include #include #include #include #include #include #include #include #include #if defined(__x86_64__) || defined(_M_X64) #include #if defined(_MSC_VER) && !defined(__clang__) #include #else #include #endif #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _WIN32 #ifndef NOMINMAX #define NOMINMAX #endif #include #else #include #include #include #include #ifndef __APPLE__ #include #endif #include #include #include #include #include "prx/libc/include/specifics/linux/HostMapping.hpp" #ifdef __APPLE__ #include #include #include #endif #endif namespace AgcDriver::GuestMemory { namespace { void require(bool condition, const char* reason) { if (!condition) throw std::runtime_error(std::string("AGC driver: ") + reason); } // A code address relative to its module, for symbolizing debug traces with nm. unsigned long long ModuleOffset(const void* address) { #ifdef _WIN32 HMODULE module = nullptr; GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, static_cast(address), &module); return reinterpret_cast(address) - reinterpret_cast(module); #else Dl_info info{}; if (dladdr(address, &info) == 0 || info.dli_fbase == nullptr) return reinterpret_cast(address); return reinterpret_cast(address) - reinterpret_cast(info.dli_fbase); #endif } #ifdef _WIN32 bool readableProtection(DWORD protection) { return protection == PAGE_READONLY || protection == PAGE_READWRITE || protection == PAGE_WRITECOPY || protection == PAGE_EXECUTE_READ || protection == PAGE_EXECUTE_READWRITE || protection == PAGE_EXECUTE_WRITECOPY; } bool writableProtection(DWORD protection) { return protection == PAGE_READWRITE || protection == PAGE_WRITECOPY || protection == PAGE_EXECUTE_READWRITE || protection == PAGE_EXECUTE_WRITECOPY; } std::uintptr_t userAddressLimit() { static const auto limit = [] { SYSTEM_INFO info{}; GetSystemInfo(&info); return reinterpret_cast(info.lpMaximumApplicationAddress); }(); return limit; } #endif } struct WriteSubscription { std::atomic generation{1}; std::vector blocks; std::vector> spans; struct Bump { std::uint64_t generation; std::uint64_t block; bool plain; bool lookup; }; std::vector bumps; std::uint64_t overflowedAt = 0; }; namespace { constexpr std::uint64_t IndexBlockBytes = 65536; constexpr std::size_t MaxRecordedBumps = 1024; constexpr std::uint64_t SpanGapBytes = std::uint64_t{1} << 20; struct WriteIndex { AgcDriver::Mutex mutex; std::atomic live{0}; std::unordered_map> byBlock; std::atomic subscriptions{0}; std::atomic blocks{0}; std::atomic bumps{0}; std::atomic lookups{0}; std::atomic sweeps{0}; std::atomic sweepFailures{0}; std::atomic overflows{0}; std::atomic lookupNanoseconds{0}; std::array, static_cast(WriteBumpSource::Count)> bySource{}; }; WriteIndex& Index() { static auto* index = new WriteIndex; return *index; } bool brokenSource(WriteBumpSource source) { static const auto broken = [] { std::array(WriteBumpSource::Count)> flags{}; const char* text = std::getenv("APS5_TABLE_INDEX_BREAK"); if (text == nullptr) return flags; const std::string value(text); constexpr std::array(WriteBumpSource::Count)> names{"cpu", "driver", "pending", "unwatch", "forget", "release", "import"}; for (std::size_t i = 0; i < names.size(); ++i) flags[i] = value.find(names[i]) != std::string::npos; return flags; }(); return broken[static_cast(source)]; } void bumpSubscriptions(std::uint64_t address, std::uint64_t bytes, WriteBumpSource source) { auto& index = Index(); if (bytes == 0 || index.live.load(std::memory_order_acquire) == 0 || brokenSource(source)) return; static const bool timed = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto start = timed ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const auto first = address / IndexBlockBytes; const auto last = (address + bytes - 1) / IndexBlockBytes; const bool lookup = source == WriteBumpSource::Release || source == WriteBumpSource::Import; std::uint64_t lookups = 0; std::uint64_t bumped = 0; std::uint64_t overflowed = 0; { std::lock_guard lock(index.mutex); const auto visit = [&](std::uint64_t block, const std::vector& subscribers) { for (auto* subscription : subscribers) { const auto generation = subscription->generation.fetch_add(1, std::memory_order_acq_rel) + 1; if (!subscription->bumps.empty() && subscription->bumps.back().block == block && subscription->bumps.back().lookup == lookup) subscription->bumps.back().generation = generation; else if (subscription->bumps.size() < MaxRecordedBumps) subscription->bumps.push_back({generation, block, !lookup, lookup}); else if (subscription->overflowedAt == 0) { subscription->overflowedAt = generation; ++overflowed; } ++bumped; } }; if (last - first >= index.byBlock.size()) { ++lookups; for (const auto& [block, subscribers] : index.byBlock) { if (block >= first && block <= last) visit(block, subscribers); } } else { for (auto block = first; block <= last; ++block) { ++lookups; if (const auto found = index.byBlock.find(block); found != index.byBlock.end()) visit(block, found->second); } } } index.lookups.fetch_add(lookups, std::memory_order_relaxed); if (bumped != 0) { index.bumps.fetch_add(bumped, std::memory_order_relaxed); index.bySource[static_cast(source)].fetch_add(bumped, std::memory_order_relaxed); } if (overflowed != 0) index.overflows.fetch_add(overflowed, std::memory_order_relaxed); if (timed) index.lookupNanoseconds.fetch_add(static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()), std::memory_order_relaxed); } void releaseSubscription(WriteSubscription* subscription) { auto& index = Index(); { std::lock_guard lock(index.mutex); for (const auto block : subscription->blocks) { const auto found = index.byBlock.find(block); if (found == index.byBlock.end()) continue; auto& subscribers = found->second; subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), subscription), subscribers.end()); if (subscribers.empty()) index.byBlock.erase(found); } index.live.fetch_sub(1, std::memory_order_acq_rel); } delete subscription; } } bool WriteIndexEnabled() { static const bool enabled = [] { const char* text = std::getenv("APS5_TABLE_INDEX"); return text != nullptr && text[0] != '\0' && text[0] != '0'; }(); return enabled; } std::uint64_t WriteBlockOf(std::uint64_t address) { return address / IndexBlockBytes; } std::uint64_t SubscriptionGeneration(const WriteSubscription& subscription) { return subscription.generation.load(std::memory_order_acquire); } std::span> SubscriptionSpans(const WriteSubscription& subscription) { return subscription.spans; } bool SubscriptionBumpsSince(const WriteSubscription& subscription, std::uint64_t generation, std::vector& blocks, std::vector& lookupBlocks) { blocks.clear(); lookupBlocks.clear(); auto& index = Index(); std::lock_guard lock(index.mutex); if (subscription.overflowedAt != 0) return false; for (const auto& bump : subscription.bumps) { if (bump.generation <= generation) continue; if (bump.plain) blocks.push_back(bump.block); if (bump.lookup) lookupBlocks.push_back(bump.block); } for (auto* list : {&blocks, &lookupBlocks}) { std::sort(list->begin(), list->end()); list->erase(std::unique(list->begin(), list->end()), list->end()); } return true; } void TrimSubscriptionBumps(WriteSubscription& subscription, std::uint64_t generation) { auto& index = Index(); std::lock_guard lock(index.mutex); if (subscription.overflowedAt != 0 && subscription.generation.load(std::memory_order_acquire) == generation) { subscription.overflowedAt = 0; subscription.bumps.clear(); return; } subscription.bumps.erase(std::remove_if(subscription.bumps.begin(), subscription.bumps.end(), [generation](const auto& bump) { return bump.generation <= generation; }), subscription.bumps.end()); } void NoteGpuPending(std::uint64_t address, std::size_t bytes) { bumpSubscriptions(address, bytes, WriteBumpSource::Pending); } void NoteTextureReleased(std::uint64_t address) { bumpSubscriptions(address, 1, WriteBumpSource::Release); } WriteIndexStats WriteIndexCounted() { auto& index = Index(); WriteIndexStats stats; stats.subscriptions = index.subscriptions.load(std::memory_order_relaxed); stats.blocks = index.blocks.load(std::memory_order_relaxed); stats.bumps = index.bumps.load(std::memory_order_relaxed); stats.lookups = index.lookups.load(std::memory_order_relaxed); stats.sweeps = index.sweeps.load(std::memory_order_relaxed); stats.sweepFailures = index.sweepFailures.load(std::memory_order_relaxed); stats.overflows = index.overflows.load(std::memory_order_relaxed); stats.lookupNanoseconds = index.lookupNanoseconds.load(std::memory_order_relaxed); for (std::size_t i = 0; i < stats.bySource.size(); ++i) stats.bySource[i] = index.bySource[i].load(std::memory_order_relaxed); return stats; } void ResetWriteIndexCounts() { auto& index = Index(); for (auto* counter : {&index.subscriptions, &index.blocks, &index.bumps, &index.lookups, &index.sweeps, &index.sweepFailures, &index.overflows, &index.lookupNanoseconds}) counter->store(0, std::memory_order_relaxed); for (auto& counter : index.bySource) counter.store(0, std::memory_order_relaxed); } namespace { std::atomic forgetCalls{0}; // See ForgetSerial: odd while a ForgetPages call stores its page states. std::atomic forgetSerial{0}; constexpr std::size_t ForgetSlotCount = 65536; constexpr std::uint64_t ForgetBlockBytes = 65536; std::array, ForgetSlotCount> forgetSlots{}; std::atomic wideForget{0}; void raiseForgetSlot(std::atomic& slot, std::uint64_t serial) { auto current = slot.load(std::memory_order_relaxed); while (current < serial && !slot.compare_exchange_weak(current, serial, std::memory_order_release, std::memory_order_relaxed)) {} } std::atomic forgetBytes{0}; std::atomic collectMemoHits{0}; std::atomic sharedWalkHits{0}; std::atomic sharedCollectWalks{std::getenv("APS5_NO_SHARED_COLLECT_WALKS") == nullptr}; std::atomic collectEpochBumps{0}; std::atomic prefetchRanges{0}; std::atomic prefetchWalks{0}; std::atomic unwatchSerial{0}; // Walks that reported at least one written page (the ones the probe pass used to double), and the // tracker mutex acquisitions that had to wait (APS5_PROFILE_DRAW; see lockTracker). std::atomic collectDirty{0}; #ifndef _WIN32 std::atomic collectDirtyRuns{0}; #endif std::atomic trackerWaits{0}; std::atomic trackerAcquisitions{0}; std::uintptr_t PagesBase(); std::size_t PagesSize(); std::uintptr_t ImagePagesBase(); std::size_t ImagePagesSize(); } // Profile (APS5_PROFILE_DRAW): calls, bytes and time of the guest memory copies and comparisons the // driver makes, printed every 10 s as [guestmem]. Accumulated per thread (the calling thread is the // only writer: plain loads and stores, no locked RMW on a cache line every queue worker shares) and // folded at report time; a finished thread's totals move to `retired`. Nothing is counted without // the profile switch (the counters are only ever printed under it). // Debug aid: APS5_SHARED_MEMORY_COUNTERS=1 accumulates into one shared set with atomic RMWs as before. enum MemoryCounterKind { CounterRead, CounterCompare, CounterWrite, CounterChangedWrite, CounterCollect, CounterVerify, CounterQuery, MemoryCounterCount }; constexpr const char* MemoryCounterNames[MemoryCounterCount] = {"read", "compare", "write", "write-changed", "collect", "verify", "query"}; struct MemoryCounter { std::atomic calls{0}; std::atomic bytes{0}; std::atomic nanoseconds{0}; void Add(std::uint64_t moreBytes, std::uint64_t moreNanoseconds, bool shared) { if (shared) { calls.fetch_add(1, std::memory_order_relaxed); bytes.fetch_add(moreBytes, std::memory_order_relaxed); nanoseconds.fetch_add(moreNanoseconds, std::memory_order_relaxed); return; } calls.store(calls.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed); bytes.store(bytes.load(std::memory_order_relaxed) + moreBytes, std::memory_order_relaxed); nanoseconds.store(nanoseconds.load(std::memory_order_relaxed) + moreNanoseconds, std::memory_order_relaxed); } }; struct MemoryCounters { std::array counters; void FoldInto(std::array, MemoryCounterCount>& totals) const { for (std::size_t i = 0; i < MemoryCounterCount; ++i) { totals[i][0] += counters[i].calls.load(std::memory_order_relaxed); totals[i][1] += counters[i].bytes.load(std::memory_order_relaxed); totals[i][2] += counters[i].nanoseconds.load(std::memory_order_relaxed); } } // Under the profile's threadsMutex (the only writer of `retired`). void AddFrom(const MemoryCounters& other) { for (std::size_t i = 0; i < MemoryCounterCount; ++i) { counters[i].calls.store(counters[i].calls.load(std::memory_order_relaxed) + other.counters[i].calls.load(std::memory_order_relaxed), std::memory_order_relaxed); counters[i].bytes.store(counters[i].bytes.load(std::memory_order_relaxed) + other.counters[i].bytes.load(std::memory_order_relaxed), std::memory_order_relaxed); counters[i].nanoseconds.store(counters[i].nanoseconds.load(std::memory_order_relaxed) + other.counters[i].nanoseconds.load(std::memory_order_relaxed), std::memory_order_relaxed); } } }; struct MemoryProfile { AgcDriver::Mutex threadsMutex; std::vector threads; MemoryCounters retired; MemoryCounters shared; std::atomic lastReport{0}; // Sampled callers of Read and Write (module offsets), to name what touches guest memory most. AgcDriver::Mutex callersMutex; std::array, 16> callers{}; std::array, 16> writeCallers{}; }; // Never destroyed: worker threads' counters unregister at thread exit, which can follow static // destruction at process exit. MemoryProfile& Profile() { static MemoryProfile& profile = *new MemoryProfile(); return profile; } bool SharedMemoryCounters() { static const bool shared = std::getenv("APS5_SHARED_MEMORY_COUNTERS") != nullptr; return shared; } struct ThreadMemoryCounters { MemoryCounters counters; ThreadMemoryCounters() { auto& profile = Profile(); std::lock_guard lock(profile.threadsMutex); profile.threads.push_back(&counters); } ~ThreadMemoryCounters() { auto& profile = Profile(); std::lock_guard lock(profile.threadsMutex); std::erase(profile.threads, &counters); profile.retired.AddFrom(counters); } }; MemoryCounter& CounterFor(MemoryCounterKind kind) { if (SharedMemoryCounters()) return Profile().shared.counters[kind]; struct Slot {}; return ThreadScratch().counters.counters[kind]; } // Every thread's counters, the retired and the shared ones summed: calls, bytes, nanoseconds per kind. std::array, MemoryCounterCount> FoldMemoryCounters() { auto& profile = Profile(); std::array, MemoryCounterCount> totals{}; std::lock_guard lock(profile.threadsMutex); for (const auto* thread : profile.threads) thread->FoldInto(totals); profile.retired.FoldInto(totals); profile.shared.FoldInto(totals); return totals; } void CountCaller(std::array, 16>& callers, std::uint32_t& sampled, std::uint32_t every, const void* returnAddress) { if (++sampled % every != 0) return; auto& state = Profile(); const auto offset = ModuleOffset(returnAddress); std::lock_guard lock(state.callersMutex); for (auto& [caller, count] : callers) { if (caller == offset || count == 0) { caller = offset; count += every; return; } } } struct CurrentPacketSlot {}; struct CurrentReadSiteSlot {}; constexpr std::uint64_t NoPacketBits = NoPacket | (std::uint64_t{0xffffffffu} << 32u); // Sampled reads by site (every 256th Read/ReadCommitted, like the callers), for the [guestmem] line. std::atomic readSiteSamples[static_cast(ReadSite::Count)] = {}; void SetCurrentPacket(std::uint32_t opcode, std::uint32_t queue) { HostThreadSlot::Set((opcode | (std::uint64_t{queue} << 32u)) ^ NoPacketBits); } PacketTag CurrentPacket() { const auto bits = HostThreadSlot::Get() ^ NoPacketBits; return {static_cast(bits), static_cast(bits >> 32u)}; } const char* ReadSiteName(ReadSite site) { static const char* const names[static_cast(ReadSite::Count)] = {"unknown", "capture", "dispatch-cache", "texture-compare", "texture-read", "buffer-upload", "index-buffer", "vertex-buffer", "registers", "indirect-args", "wait", "label", "scanout", "store", "mirror-refresh", "draw-cache", "host-write"}; const auto index = static_cast(site); return index < static_cast(ReadSite::Count) ? names[index] : "?"; } bool WritesGuestMemory(ReadSite site) { return site == ReadSite::Store || site == ReadSite::HostWrite; } ReadSite SetReadSite(ReadSite site) { const auto previous = HostThreadSlot::Get(); HostThreadSlot::Set(site); return previous; } ReadSite CurrentReadSite() { return HostThreadSlot::Get(); } std::size_t CaptureCallerOffsets(std::span frames, unsigned skip) { if (frames.empty()) return 0; #ifdef _WIN32 // Walks the x64 unwind tables, so it needs no frame pointers (unlike __builtin_return_address(n) // for n > 0); frame 0 of the capture is this function's caller. void* raw[16]; const auto wanted = static_cast(std::min(frames.size(), std::size(raw))); const auto captured = RtlCaptureStackBackTrace(1 + skip, wanted, raw, nullptr); // The driver's module is resolved once (this function lives in it): a per-frame // GetModuleHandleEx would take the loader lock several times per sync under the GpuMutex. static const auto module = [] { HMODULE handle = nullptr; GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast(&CaptureCallerOffsets), &handle); std::uintptr_t size = 0; if (handle != nullptr) { // The image size comes from the mapped PE headers (no psapi dependency). const auto* base = reinterpret_cast(handle); const auto* dos = reinterpret_cast(base); const auto* nt = reinterpret_cast(base + dos->e_lfanew); size = nt->OptionalHeader.SizeOfImage; } return std::pair(reinterpret_cast(handle), size); }(); for (std::size_t i = 0; i < captured; ++i) { const auto address = reinterpret_cast(raw[i]); frames[i] = module.first != 0 && address >= module.first && address - module.first < module.second ? address - module.first : 0; } return captured; #else void* raw[24]; const auto wanted = static_cast(std::min(frames.size() + 1 + skip, std::size(raw))); const int captured = backtrace(raw, wanted); static const auto base = [] { Dl_info info{}; return dladdr(reinterpret_cast(&CaptureCallerOffsets), &info) != 0 ? reinterpret_cast(info.dli_fbase) : std::uintptr_t{0}; }(); std::size_t written = 0; for (int i = 1 + static_cast(skip); i < captured && written < frames.size(); ++i) { Dl_info info{}; const auto address = reinterpret_cast(raw[i]); frames[written++] = base != 0 && dladdr(raw[i], &info) != 0 && reinterpret_cast(info.dli_fbase) == base ? address - base : 0; } return written; #endif } bool MemoryProfiled() { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; return profile; } void CountReadCaller(const void* returnAddress) { if (!MemoryProfiled()) return; thread_local std::uint32_t sampled = 0; // Sampled at the same rate as the callers, in step with them (CountCaller advances the counter). if ((sampled + 1) % 256 == 0) readSiteSamples[static_cast(CurrentReadSite())].fetch_add(256, std::memory_order_relaxed); CountCaller(Profile().callers, sampled, 256, returnAddress); } void CountWriteCaller(const void* returnAddress) { if (!MemoryProfiled()) return; thread_local std::uint32_t sampled = 0; CountCaller(Profile().writeCallers, sampled, 16, returnAddress); } class TimedAccess { public: TimedAccess(MemoryCounterKind kind, std::uint64_t bytes) : kind(kind), bytes(bytes), start(MemoryProfiled() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}) {} ~TimedAccess() { if (!MemoryProfiled()) return; const auto now = std::chrono::steady_clock::now(); CounterFor(kind).Add(bytes, static_cast(std::chrono::duration_cast(now - start).count()), SharedMemoryCounters()); auto& state = Profile(); const auto nowMs = std::chrono::duration_cast(now.time_since_epoch()).count(); auto last = state.lastReport.load(); if (nowMs - last < 10000 || !state.lastReport.compare_exchange_strong(last, nowMs)) return; const auto totals = FoldMemoryCounters(); AgcDriver::ProfilePrint_nid_no_patch("[guestmem]"); for (std::size_t i = 0; i < MemoryCounterCount; ++i) { AgcDriver::ProfilePrint_nid_no_patch(" %s %llu calls %.0f MiB %.1f s", MemoryCounterNames[i], static_cast(totals[i][0]), totals[i][1] / 1048576.0, totals[i][2] / 1e9); } AgcDriver::ProfilePrint_nid_no_patch(" collect-memo hits %llu (%llu from other threads' walks), collect epochs %llu, prefetched %llu ranges (%llu walked)", static_cast(collectMemoHits.load()), static_cast(sharedWalkHits.load()), static_cast(collectEpochBumps.load()), static_cast(prefetchRanges.load()), static_cast(prefetchWalks.load())); AgcDriver::ProfilePrint_nid_no_patch(" collect-dirty %llu tracker waits %llu / %llu", static_cast(collectDirty.load()), static_cast(trackerWaits.load()), static_cast(trackerAcquisitions.load())); AgcDriver::ProfilePrint_nid_no_patch(" | arena 0x%llx+0x%llx image 0x%llx+0x%llx forgets %llu (%.0f MiB)", static_cast(PagesBase()), static_cast(PagesSize()), static_cast(ImagePagesBase()), static_cast(ImagePagesSize()), static_cast(forgetCalls.load()), forgetBytes.load() / 1048576.0); { std::lock_guard lock(state.callersMutex); AgcDriver::ProfilePrint_nid_no_patch(" | read callers:"); for (const auto& [caller, count] : state.callers) { if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" +0x%llx=%llu", caller, static_cast(count)); } AgcDriver::ProfilePrint_nid_no_patch(" | write callers:"); for (const auto& [caller, count] : state.writeCallers) { if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" +0x%llx=%llu", caller, static_cast(count)); } } AgcDriver::ProfilePrint_nid_no_patch(" | read sites:"); for (std::size_t site = 0; site < static_cast(ReadSite::Count); ++site) { const auto count = readSiteSamples[site].load(std::memory_order_relaxed); if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" %s=%llu", ReadSiteName(static_cast(site)), static_cast(count)); } AgcDriver::ProfilePrint_nid_no_patch("\n"); } private: MemoryCounterKind kind; std::uint64_t bytes; std::chrono::steady_clock::time_point start; }; namespace { // Page-state cache. VirtualQuery finds the extent of a run of equally mapped pages by walking page // tables, which costs tens of milliseconds inside the game's committed gigabyte heap, and GPU workers // verify ranges thousands of times per second. Committed pages of the guest arena are therefore // remembered, one byte of access flags per 4 KiB page (the table is committed lazily, so only the // pages ever verified cost memory). libc reports every range whose mapping or protection changed // (registry mutations and guest heap decommits) through the invalidator, which forgets those pages. // A second table covers the main guest image (the PE at 0x7ff6b...): its protections change only // through registry mutations (mprotect replaces the registered range and invalidates through the same // callback), and address-based builds verify every image section on each build, so without the table // each of those verifications was a VirtualQuery. APS5_NO_IMAGE_PAGE_CACHE=1 leaves the image uncached. constexpr std::size_t PageBytes = 4096; constexpr std::size_t BlockPages = 64; constexpr std::uint8_t PageReadable = 1; constexpr std::uint8_t PageWritable = 2; constexpr std::uint8_t PageInaccessible = 4; struct PageSpan { std::uintptr_t base = 0; std::size_t size = 0; // Per page: access flags, zero while unknown. std::uint8_t* pages = nullptr; std::uint8_t* blocks = nullptr; static constexpr std::size_t ChunkEntries = 65536; struct alignas(8) Chunk { std::array entries{}; std::array blocks{}; }; std::atomic* chunks = nullptr; Chunk* chunkAt(std::size_t index, bool create) const { auto* chunk = chunks[index].load(std::memory_order_acquire); if (chunk == nullptr && create) { auto fresh = std::unique_ptr(new (std::nothrow) Chunk{}); if (fresh != nullptr && chunks[index].compare_exchange_strong(chunk, fresh.get(), std::memory_order_acq_rel, std::memory_order_acquire)) chunk = fresh.release(); } return chunk; } std::uint8_t* entry(std::size_t index, bool create) const { if (chunks == nullptr) return pages + index; auto* chunk = chunkAt(index / ChunkEntries, create); return chunk == nullptr ? nullptr : chunk->entries.data() + index % ChunkEntries; } std::uint8_t* blockEntry(std::size_t block, bool create) const { if (chunks == nullptr) return blocks + block; auto* chunk = chunkAt(block * BlockPages / ChunkEntries, create); return chunk == nullptr ? nullptr : chunk->blocks.data() + block % (ChunkEntries / BlockPages); } bool allocate() { if (size == 0) return false; const auto count = (size / PageBytes + BlockPages) & ~(BlockPages - 1); #ifdef _WIN32 const auto chunkCount = (count + ChunkEntries - 1) / ChunkEntries; chunks = new (std::nothrow) std::atomic[chunkCount]{}; if (chunks == nullptr) size = 0; return chunks != nullptr; #else const auto blockCount = (count / BlockPages + 8) & ~static_cast(7); pages = static_cast(std::calloc(count + blockCount, 1)); if (pages == nullptr) size = 0; else blocks = pages + count; return pages != nullptr; #endif } bool covers(std::uintptr_t address) const { return size != 0 && address >= base && address - base < size; } static std::uint8_t loadByte(const std::uint8_t* at) { return std::atomic_ref(*const_cast(at)).load(std::memory_order_relaxed); } static void storeByte(std::uint8_t* at, std::uint8_t value) { std::atomic_ref(*at).store(value, std::memory_order_relaxed); } static std::uint64_t loadWide(const std::uint8_t* at) { return std::atomic_ref(*reinterpret_cast(const_cast(at))).load(std::memory_order_relaxed); } std::uint8_t load(std::uintptr_t address) const { auto* value = entry((address - base) / PageBytes, false); return value == nullptr ? 0 : loadByte(value); } std::uint8_t common(std::size_t block) const { const auto* at = entry(block * BlockPages, false); if (at == nullptr) return 0; const auto value = loadByte(at); const std::uint64_t wide = 0x0101010101010101ull * value; for (std::size_t offset = 0; offset < BlockPages; offset += 8) { if (loadWide(at + offset) != wide) return 0; } return value; } void settle(std::size_t first, std::size_t last) { std::atomic_thread_fence(std::memory_order_seq_cst); for (auto block = first / BlockPages; block <= (last - 1) / BlockPages; ++block) { const auto value = common(block); auto* summary = blockEntry(block, false); if (summary == nullptr || loadByte(summary) == value) continue; storeByte(summary, value); if (value == 0) continue; std::atomic_thread_fence(std::memory_order_seq_cst); if (common(block) != value) storeByte(summary, 0); } } void store(std::uintptr_t address, std::uint8_t value) { store(address, address + PageBytes, value); } void store(std::uintptr_t first, std::uintptr_t last, std::uint8_t value) { if (first >= last) return; const auto begin = (first - base) / PageBytes; const auto end = (last - 1 - base) / PageBytes + 1; auto index = begin; while (index < end) { const auto next = std::min(end, (index / ChunkEntries + 1) * ChunkEntries); if (auto* at = entry(index, value != 0 && value != PageInaccessible)) { for (; index < next; ++index, ++at) storeByte(at, value); } else index = next; } settle(begin, end); } // End of the run of pages equal to `value` that starts at `address`, at most `limit`. std::uintptr_t runEnd(std::uintptr_t address, std::uint8_t value, std::uintptr_t limit) const { auto index = (address - base) / PageBytes; const auto stop = std::min((std::min(limit, base + size) - base + PageBytes - 1) / PageBytes, size / PageBytes); const std::uint64_t wide = 0x0101010101010101ull * value; while (index < stop) { auto* at = entry(index, false); if (at == nullptr) { if (value != 0) break; index = std::min(stop, (index / ChunkEntries + 1) * ChunkEntries); continue; } if (index % BlockPages == 0) { const auto block = index / BlockPages; const auto* summary = blockEntry(block, false); if (block % 8 == 0 && index + 8 * BlockPages <= stop && loadWide(summary) == wide) { index += 8 * BlockPages; continue; } if (index + BlockPages <= stop && loadByte(summary) == value) { index += BlockPages; continue; } } if (index % 8 == 0 && index + 8 <= stop && loadWide(at) == wide) { index += 8; continue; } if (loadByte(at) != value) break; ++index; } return std::min(limit, base + index * PageBytes); } void forget(std::uintptr_t address, std::size_t bytes) { if (size == 0 || bytes == 0 || address >= base + size || address + bytes <= base) return; const auto first = (std::max(address, base) - base) / PageBytes; const auto last = (std::min(address + bytes, base + size) - 1 - base) / PageBytes; store(base + first * PageBytes, base + (last + 1) * PageBytes, 0); } }; struct PageStates { std::once_flag once; std::atomic ready{false}; PageSpan arena; PageSpan image; void initialize(); PageSpan* spanOf(std::uintptr_t address) { if (arena.covers(address)) return &arena; if (image.covers(address)) return ℑ return nullptr; } void forget(std::uintptr_t address, std::size_t bytes) { arena.forget(address, bytes); image.forget(address, bytes); } std::atomic accessSerial{0}; void record(std::uintptr_t base, std::uintptr_t regionEnd, bool readable, bool writable, std::uint64_t generation, std::uint64_t access) { for (PageSpan* span : {&arena, &image}) { if (span->size == 0 || regionEnd <= span->base || base >= span->base + span->size) continue; const std::uint8_t value = readable ? static_cast(PageReadable | (writable ? PageWritable : 0u)) : PageInaccessible; const auto first = std::max(base, span->base); const auto last = std::min(regionEnd, span->base + span->size); span->store(first, last, value); if (GuestAllocations::GuestAllocationsGeneration_nid_postfix() != generation || accessSerial.load(std::memory_order_acquire) != access) span->forget(first, static_cast(last - first)); } } void forgetInaccessible(std::uintptr_t address, std::size_t bytes) { for (PageSpan* span : {&arena, &image}) { if (span->size == 0 || bytes == 0 || address >= span->base + span->size || address + bytes <= span->base) continue; const auto last = std::min(address + bytes, span->base + span->size); for (auto at = std::max(address, span->base) & ~static_cast(PageBytes - 1); at < last; at += PageBytes) { if (span->load(at) == PageInaccessible) span->store(at, at + PageBytes, 0); } } } }; PageStates& Pages() { static PageStates pages; return pages; } std::uintptr_t PagesBase() { return Pages().arena.base; } std::size_t PagesSize() { return Pages().arena.size; } std::uintptr_t ImagePagesBase() { return Pages().image.base; } std::size_t ImagePagesSize() { return Pages().image.size; } void ForgetPages(std::uintptr_t address, std::size_t bytes) { bumpSubscriptions(address, bytes, WriteBumpSource::Forget); forgetCalls.fetch_add(1, std::memory_order_relaxed); forgetBytes.fetch_add(bytes, std::memory_order_relaxed); const auto started = forgetSerial.fetch_add(1, std::memory_order_release) + 1; Pages().forget(address, bytes); const auto done = started + 1; if (bytes != 0) { const auto first = address / ForgetBlockBytes; const auto last = (address + bytes - 1) / ForgetBlockBytes; if (last - first >= ForgetSlotCount) raiseForgetSlot(wideForget, done); else for (auto block = first; block <= last; ++block) raiseForgetSlot(forgetSlots[block % ForgetSlotCount], done); } forgetSerial.fetch_add(1, std::memory_order_release); } void ForgetInaccessiblePages(std::uintptr_t address, std::size_t bytes) { Pages().accessSerial.fetch_add(1, std::memory_order_acq_rel); Pages().forgetInaccessible(address, bytes); } #ifdef __linux__ int mainImageExtent(dl_phdr_info* info, std::size_t, void* data) { constexpr auto mask = static_cast(PageBytes - 1); auto& span = *static_cast(data); std::uintptr_t first = std::numeric_limits::max(); std::uintptr_t last = 0; for (int index = 0; index < info->dlpi_phnum; ++index) { const auto& header = info->dlpi_phdr[index]; if (header.p_type != PT_LOAD || header.p_memsz == 0) continue; first = std::min(first, static_cast(info->dlpi_addr + header.p_vaddr) & ~mask); last = std::max(last, static_cast(info->dlpi_addr + header.p_vaddr + header.p_memsz + mask) & ~mask); } if (first < last) { span.base = first; span.size = static_cast(last - first); } return 1; } #endif void PageStates::initialize() { if (ready.load(std::memory_order_acquire)) return; std::call_once(once, [&] { GuestArena::GuestArenaRange_nid_postfix(&arena.base, &arena.size); const bool arenaCached = arena.allocate(); bool imageCached = false; #ifdef _WIN32 // The image extent is the run of regions sharing the module's allocation base, as the registry // walks it when it registers the main image. static const bool noImageCache = std::getenv("APS5_NO_IMAGE_PAGE_CACHE") != nullptr; if (const auto module = noImageCache ? nullptr : GetModuleHandleW(nullptr)) { const auto start = reinterpret_cast(module); auto cursor = start; for (;;) { MEMORY_BASIC_INFORMATION memory{}; if (VirtualQuery(reinterpret_cast(cursor), &memory, sizeof(memory)) != sizeof(memory) || memory.AllocationBase != module || memory.RegionSize == 0 || memory.RegionSize > std::numeric_limits::max() - cursor) break; cursor += memory.RegionSize; } image.base = start; image.size = cursor - start; imageCached = image.allocate(); } #elif defined(__linux__) static const bool noImageCache = std::getenv("APS5_NO_IMAGE_PAGE_CACHE") != nullptr; if (!noImageCache) { dl_iterate_phdr(mainImageExtent, &image); imageCached = image.allocate(); } #endif if (arenaCached || imageCached || WriteIndexEnabled()) GuestAllocations::GuestAllocationsSetInvalidator_nid_postfix(&ForgetPages); if (arenaCached || imageCached) GuestArena::GuestArenaSetAccessObserver_nid_postfix(&ForgetInaccessiblePages); }); ready.store(true, std::memory_order_release); } struct PageRun { std::uintptr_t begin; std::uintptr_t end; bool readable; bool writable; }; #ifndef _WIN32 struct HostRun { std::uintptr_t first = 0; std::uintptr_t last = 0; bool readable = false; bool writable = false; }; enum class MapsScan { Failed, Missing, Found }; MapsScan mappingAbove(std::uintptr_t cursor, HostRun& run) { const TimedAccess timed(CounterQuery, 0); const int fd = open("/proc/self/maps", O_RDONLY | O_CLOEXEC); if (fd < 0) return MapsScan::Failed; struct Slot {}; auto& text = ThreadScratch, Slot>(); enum class Field { First, Last, Permissions, Rest }; auto field = Field::First; std::uintptr_t first = 0; std::uintptr_t last = 0; unsigned digits = 0; char permissions[2] = {}; const auto finish = [&](MapsScan result) { close(fd); return result; }; const auto digit = [](char character) { if (character >= '0' && character <= '9') return character - '0'; if (character >= 'a' && character <= 'f') return character - 'a' + 10; return -1; }; std::size_t wanted = 256; for (;;) { const auto got = read(fd, text.data(), wanted); wanted = text.size(); if (got < 0 && errno == EINTR) continue; if (got < 0) return finish(MapsScan::Failed); if (got == 0) return finish(field == Field::First && digits == 0 ? MapsScan::Missing : MapsScan::Failed); for (ssize_t index = 0; index < got; ++index) { const char character = text[static_cast(index)]; if (field == Field::Rest) { if (character != '\n') continue; field = Field::First; first = 0; last = 0; digits = 0; } else if (field == Field::Permissions) { if (character == ' ' || character == '\n') return finish(MapsScan::Failed); permissions[digits++] = character; if (digits < 2) continue; if (last > cursor) { run = HostRun{first, last, permissions[0] == 'r', permissions[0] == 'r' && permissions[1] == 'w'}; return finish(MapsScan::Found); } field = Field::Rest; } else if (character == (field == Field::First ? '-' : ' ')) { if (digits == 0 || (field == Field::Last && first >= last)) return finish(MapsScan::Failed); field = field == Field::First ? Field::Last : Field::Permissions; digits = 0; } else { const int value = digit(character); if (value < 0 || ++digits > 2 * sizeof(std::uintptr_t)) return finish(MapsScan::Failed); auto& target = field == Field::First ? first : last; target = (target << 4) | static_cast(value); } } } } #endif // Calls `emit` with consecutive runs of uniform accessibility covering [address, address + bytes) in // order, stopping early when it returns false. Returns false when the address space cannot be queried. template bool describePages(std::uintptr_t address, std::size_t bytes, Emit&& emit) { auto& pages = Pages(); pages.initialize(); const auto end = address + bytes; auto cursor = address; while (cursor < end) { if (const auto* span = pages.spanOf(cursor)) { const auto value = span->load(cursor); if (value != 0) { const auto next = span->runEnd(cursor, value, end); if (!emit(PageRun{cursor, next, (value & PageReadable) != 0, (value & PageWritable) != 0})) return true; cursor = next; continue; } } #ifdef _WIN32 const TimedAccess timed(CounterQuery, 0); MEMORY_BASIC_INFORMATION memory{}; const auto queryStart = std::chrono::steady_clock::now(); // A mutation that changes these pages while they are being queried bumps the generation // before it invalidates, so a generation change across the query and the store below means // the stored pages may describe the old state and are forgotten again. const auto generation = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); const auto access = pages.accessSerial.load(std::memory_order_acquire); if (cursor > userAddressLimit()) { static_cast(emit(PageRun{cursor, end, false, false})); return true; } if (VirtualQuery(reinterpret_cast(cursor), &memory, sizeof(memory)) != sizeof(memory)) return false; // Debug aid: APS5_TRACE_QUERY prints every 16th page query with its cost. static const bool traceQuery = std::getenv("APS5_TRACE_QUERY") != nullptr; if (traceQuery) { static std::atomic queries{0}; if (queries.fetch_add(1) % 16 == 0) { const auto us = std::chrono::duration(std::chrono::steady_clock::now() - queryStart).count(); std::fprintf(stderr, "[query] 0x%llx range 0x%zx: base 0x%llx size 0x%llx state 0x%lx protect 0x%lx type 0x%lx %.0f us gen %llu from +0x%llx\n", static_cast(cursor), bytes, reinterpret_cast(memory.BaseAddress), static_cast(memory.RegionSize), memory.State, memory.Protect, memory.Type, us, static_cast(GuestAllocations::GuestAllocationsGeneration_nid_postfix()), ModuleOffset(__builtin_return_address(0))); } } const auto base = reinterpret_cast(memory.BaseAddress); if (memory.RegionSize > std::numeric_limits::max() - base || base + memory.RegionSize <= cursor) return false; const auto regionEnd = base + memory.RegionSize; std::uint32_t logicalProtection = memory.Protect; GuestArena::GuestArenaProtection_nid_postfix(cursor, &logicalProtection); const auto protection = logicalProtection & 0xffu; const bool committed = memory.State == MEM_COMMIT && (memory.Protect & (PAGE_GUARD | PAGE_NOACCESS)) == 0; const bool readable = committed && readableProtection(protection); const bool writable = readable && writableProtection(protection); if ((memory.Protect & PAGE_GUARD) == 0) pages.record(base, regionEnd, readable, writable, generation, access); const auto next = std::min(end, regionEnd); if (!emit(PageRun{cursor, next, readable, writable})) return true; cursor = next; #else const auto generation = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); const auto access = pages.accessSerial.load(std::memory_order_acquire); const auto recordRun = [&](std::uintptr_t next, bool readable, bool writable) { constexpr auto mask = static_cast(PageBytes - 1); pages.record(cursor & ~mask, (next + mask) & ~mask, readable, writable, generation, access); }; if (const int fd = HostMapping::QueryFd(); fd >= 0) { procmap_query query{}; query.size = sizeof(query); query.query_flags = PROCMAP_QUERY_COVERING_OR_NEXT_VMA; query.query_addr = cursor; if (ioctl(fd, PROCMAP_QUERY, &query) == 0) { if (query.vma_end <= cursor || query.vma_start >= query.vma_end) return false; if (query.vma_start > cursor) { const auto gapEnd = std::min(end, query.vma_start); recordRun(gapEnd, false, false); if (!emit(PageRun{cursor, gapEnd, false, false})) return true; cursor = gapEnd; continue; } const bool readable = (query.vma_flags & PROCMAP_QUERY_VMA_READABLE) != 0; const bool writable = readable && (query.vma_flags & PROCMAP_QUERY_VMA_WRITABLE) != 0; const auto next = std::min(end, query.vma_end); recordRun(next, readable, writable); if (!emit(PageRun{cursor, next, readable, writable})) return true; cursor = next; continue; } if (errno == ENOENT) { static_cast(emit(PageRun{cursor, end, false, false})); return true; } return false; } #ifdef __APPLE__ { mach_vm_address_t region = cursor; mach_vm_size_t regionSize = 0; vm_region_basic_info_data_64_t info{}; mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64; mach_port_t object = MACH_PORT_NULL; const auto status = mach_vm_region(mach_task_self(), ®ion, ®ionSize, VM_REGION_BASIC_INFO_64, reinterpret_cast(&info), &count, &object); if (status == KERN_INVALID_ADDRESS) { static_cast(emit(PageRun{cursor, end, false, false})); return true; } if (status != KERN_SUCCESS || regionSize == 0) return false; if (region > cursor) { const auto gapEnd = std::min(end, region); if (!emit(PageRun{cursor, gapEnd, false, false})) return true; cursor = gapEnd; continue; } bool readable = (info.protection & VM_PROT_READ) != 0; bool writable = readable && (info.protection & VM_PROT_WRITE) != 0; auto next = std::min(end, region + regionSize); std::uintptr_t watchedEnd = next; const int logical = GuestWriteWatch::GuestWriteWatchProtection_nid_postfix(cursor, next, &watchedEnd); if (logical >= 0) { readable = readable && (logical & PROT_READ) != 0; writable = readable && (logical & PROT_WRITE) != 0; } if (watchedEnd > cursor && watchedEnd < next) next = watchedEnd; recordRun(next, readable, writable); if (!emit(PageRun{cursor, next, readable, writable})) return true; cursor = next; continue; } #endif HostRun run; const auto scanned = mappingAbove(cursor, run); if (scanned == MapsScan::Failed) return false; if (scanned == MapsScan::Missing) { static_cast(emit(PageRun{cursor, end, false, false})); return true; } if (run.first > cursor) { const auto gapEnd = std::min(end, run.first); recordRun(gapEnd, false, false); if (!emit(PageRun{cursor, gapEnd, false, false})) return true; cursor = gapEnd; continue; } const auto next = std::min(end, run.last); recordRun(next, run.readable, run.writable); if (!emit(PageRun{cursor, next, run.readable, run.writable})) return true; cursor = next; #endif } return true; } bool onOwnLiveStack(std::uintptr_t address, std::size_t bytes) { struct Bounds { std::uintptr_t low = 0; std::uintptr_t high = 0; Bounds() { #ifdef _WIN32 ULONG_PTR lowLimit = 0; ULONG_PTR highLimit = 0; GetCurrentThreadStackLimits(&lowLimit, &highLimit); low = static_cast(lowLimit); high = static_cast(highLimit); #elif defined(__APPLE__) const auto self = pthread_self(); high = reinterpret_cast(pthread_get_stackaddr_np(self)); low = high - pthread_get_stacksize_np(self); #else pthread_attr_t attributes; if (pthread_getattr_np(pthread_self(), &attributes) != 0) return; void* base = nullptr; std::size_t size = 0; if (pthread_attr_getstack(&attributes, &base, &size) == 0 && base != nullptr) { low = reinterpret_cast(base); high = low + size; } pthread_attr_destroy(&attributes); #endif } }; struct Slot {}; const auto& bounds = ThreadScratch(); const auto frame = reinterpret_cast(__builtin_frame_address(0)); return bounds.high != 0 && frame >= bounds.low && frame < bounds.high && address >= frame && address < bounds.high && bytes <= bounds.high - address; } #ifdef __linux__ bool pageStateRecorded(std::uintptr_t address, std::size_t bytes) { auto& pages = Pages(); pages.initialize(); for (auto at = address & ~static_cast(PageBytes - 1); at < address + bytes; at += PageBytes) { if (const auto* span = pages.spanOf(at); span != nullptr && span->load(at) != 0) return true; } return false; } bool readableWithoutQuery(std::uintptr_t address, std::size_t bytes) { constexpr std::size_t limit = 4096; if (bytes > limit || HostMapping::QueryFd() >= 0 || pageStateRecorded(address, bytes)) return false; thread_local std::array scratch; iovec local{scratch.data(), bytes}; iovec remote{reinterpret_cast(address), bytes}; static const pid_t self = getpid(); return ::process_vm_readv(self, &local, 1, &remote, 1, 0) == static_cast(bytes); } #endif // Checks that [address, address + bytes) is mapped with read (and, if asked, write) access. Returns // an empty string when it is, otherwise why it is not. bool checkAccess(std::uintptr_t address, std::size_t bytes, bool writable, std::string* reason) { const TimedAccess timed(CounterVerify, bytes); if (onOwnLiveStack(address, bytes)) return true; #ifdef __linux__ if (!writable && readableWithoutQuery(address, bytes)) return true; #endif bool accessible = true; const bool queried = describePages(address, bytes, [&](const PageRun& run) { if (!run.readable) { accessible = false; if (reason != nullptr) { char text[128]; std::snprintf(text, sizeof(text), "guest memory is not readable at 0x%llx (range 0x%llx+0x%zx)", static_cast(run.begin), static_cast(address), bytes); *reason = text; } } else if (writable && !run.writable) { accessible = false; if (reason != nullptr) *reason = "guest memory has no write permission"; } return accessible; }); if (!queried && accessible) { accessible = false; if (reason != nullptr) *reason = "cannot query guest memory"; } return accessible; } std::string verify(std::uintptr_t address, std::size_t bytes, bool writable) { std::string reason; checkAccess(address, bytes, writable, &reason); return reason; } } void CheckRange(const void* pointer, std::size_t bytes, std::size_t alignment, bool writable) { require(alignment != 0, "zero guest memory alignment"); const auto address = reinterpret_cast(pointer); require(address != 0 && address % alignment == 0, "null or misaligned address"); require(bytes <= std::numeric_limits::max() - address, "address range overflow"); const auto reason = verify(address, bytes, writable); if (!reason.empty()) { // Debug aid: APS5_TRACE_UNREADABLE names the code that checked an inaccessible range. static const bool trace = std::getenv("APS5_TRACE_UNREADABLE") != nullptr; if (trace) std::fprintf(stderr, "[unreadable] %s from +0x%llx\n", reason.c_str(), ModuleOffset(__builtin_return_address(0))); require(false, reason.c_str()); } } bool Accessible(const void* pointer, std::size_t bytes, bool writable) { const auto address = reinterpret_cast(pointer); return address != 0 && bytes <= std::numeric_limits::max() - address && checkAccess(address, bytes, writable, nullptr); } std::uint64_t ForgetSerial() { return forgetSerial.load(std::memory_order_acquire); } std::uint64_t ForgetStamp(std::uint64_t address, std::size_t bytes) { if (bytes == 0) return 0; const auto first = address / ForgetBlockBytes; const auto last = (address + bytes - 1) / ForgetBlockBytes; if (last - first >= ForgetSlotCount) return forgetSerial.load(std::memory_order_acquire); auto newest = wideForget.load(std::memory_order_acquire); for (auto block = first; block <= last; ++block) newest = std::max(newest, forgetSlots[block % ForgetSlotCount].load(std::memory_order_acquire)); return newest; } Commitment DescribeCommitted(std::uint64_t address, std::size_t bytes, bool writable) { require(bytes <= std::numeric_limits::max() - address, "address range overflow"); const TimedAccess timed(CounterVerify, bytes); Commitment result; const bool queried = describePages(static_cast(address), bytes, [&](const PageRun& run) { if (run.readable && (!writable || run.writable)) { if (!result.ranges.empty() && result.ranges.back().second == run.begin) result.ranges.back().second = run.end; else result.ranges.emplace_back(run.begin, run.end); } return true; }); require(queried, "cannot query guest memory"); result.whole = bytes == 0 || (result.ranges.size() == 1 && result.ranges.front().first == address && result.ranges.front().second == address + bytes); return result; } std::vector> CommittedRanges(std::uint64_t address, std::size_t bytes, bool writable) { return DescribeCommitted(address, bytes, writable).ranges; } namespace { constexpr std::size_t WriteBlockBytes = 65536; constexpr std::size_t WritePageBytes = 4096; constexpr std::size_t WritePagesPerBlock = WriteBlockBytes / WritePageBytes; constexpr std::size_t ImportHashPagesPerThread = 1024; constexpr unsigned ImportHashThreads = 4; enum class StampKind : std::uint8_t { Cpu, Driver, ImportWindow, Fresh }; std::uint64_t HashPage(const std::byte* page) { constexpr std::uint64_t prime1 = 0x9E3779B185EBCA87ull; constexpr std::uint64_t prime2 = 0xC2B2AE3D27D4EB4Full; constexpr std::uint64_t prime3 = 0x165667B19E3779F9ull; constexpr std::uint64_t prime4 = 0x85EBCA77C2B2AE63ull; const auto round = [](std::uint64_t accumulator, std::uint64_t word) { return std::rotl(accumulator + word * prime2, 31) * prime1; }; std::array lanes{prime1 + prime2, prime2, 0, 0 - prime1}; for (std::size_t offset = 0; offset < WritePageBytes; offset += 4 * sizeof(std::uint64_t)) { std::array words; std::memcpy(words.data(), page + offset, sizeof(words)); for (std::size_t lane = 0; lane < 4; ++lane) lanes[lane] = round(lanes[lane], words[lane]); } std::uint64_t hash = std::rotl(lanes[0], 1) + std::rotl(lanes[1], 7) + std::rotl(lanes[2], 12) + std::rotl(lanes[3], 18); for (const auto lane : lanes) hash = (hash ^ round(0, lane)) * prime1 + prime4; hash ^= hash >> 33; hash *= prime2; hash ^= hash >> 29; hash *= prime3; return hash ^ (hash >> 32); } template void SplitPages(std::size_t pages, const Range& range) { static const unsigned hostThreads = std::max(1u, std::thread::hardware_concurrency() / 2); const auto workers = std::min({ImportHashThreads, hostThreads, pages / ImportHashPagesPerThread}); if (workers < 2) { range(std::size_t{0}, pages); return; } std::vector threads; threads.reserve(workers - 1); for (std::size_t worker = 1; worker < workers; ++worker) { const auto from = pages * worker / workers; const auto to = pages * (worker + 1) / workers; try { threads.emplace_back(range, from, to); } catch (const std::system_error&) { range(from, to); } } range(std::size_t{0}, pages / workers); } std::vector PagesOf(std::span> spans) { std::vector pages; for (const auto& [begin, end] : spans) { for (auto page = begin; page < end; page += WritePageBytes) pages.push_back(page); } return pages; } std::vector TrappedPages(std::span pages) { std::vector trapped(pages.size(), 0); #if defined(__APPLE__) || defined(__linux__) || defined(_WIN32) std::vector> runs; for (std::size_t from = 0; from < pages.size();) { auto to = from + 1; while (to < pages.size() && pages[to] == pages[to - 1] + WritePageBytes) ++to; GuestWriteWatch::GuestWriteWatchReadTraps_nid_postfix(static_cast(pages[from]), (to - from) * WritePageBytes, +[](void* context, std::uintptr_t begin, std::uintptr_t end) { static_cast>*>(context)->emplace_back(begin, end); }, &runs); from = to; } if (runs.empty()) return trapped; std::sort(runs.begin(), runs.end()); for (std::size_t index = 0; index < pages.size(); ++index) { const auto page = static_cast(pages[index]); const auto run = std::partition_point(runs.begin(), runs.end(), [&](const auto& candidate) { return candidate.second <= page; }); trapped[index] = run != runs.end() && run->first < page + WritePageBytes; } #endif return trapped; } void HashPages(std::uint64_t first, std::span> spans, std::vector& hashes, std::vector& unknown) { const auto pages = PagesOf(spans); const auto trapped = TrappedPages(pages); SplitPages(pages.size(), [&](std::size_t from, std::size_t to) { for (auto index = from; index < to; ++index) { const auto at = static_cast((pages[index] - first) / WritePageBytes); if (trapped[index] != 0) unknown[at] = 1; else hashes[at] = HashPage(reinterpret_cast(pages[index])); } }); } struct WindowCopy { std::uint64_t first; std::span hashes; std::span image; StampKind held = StampKind::ImportWindow; std::span unknown; bool Holds(std::uintptr_t page) const { if (held == StampKind::Driver) return page >= first && page - first <= image.size() && image.size() - (page - first) >= WritePageBytes && CompareMapped(page, image.subspan(page - first, WritePageBytes)) == Compare::Equal; if (page < first || (page - first) / WritePageBytes >= hashes.size()) return false; const auto at = (page - first) / WritePageBytes; return (at >= unknown.size() || unknown[at] == 0) && HashPage(reinterpret_cast(page)) == hashes[at]; } }; #ifdef _WIN32 void watchPrivateMapping(std::uintptr_t address, std::size_t bytes, std::uint64_t generation); #endif struct WriteTracker { AgcDriver::Mutex mutex; bool initialized = false; bool watched = false; static constexpr std::size_t CoarseBlocks = 64; static constexpr std::size_t LeafBlocks = std::size_t{1} << 16; struct Leaf { std::array blocks{}; std::array cpuBlocks{}; std::array coarseBlocks{}; #ifdef _WIN32 std::array hintBlocks{}; #endif }; std::vector> leaves; #ifdef _WIN32 std::uintptr_t base = 0; std::size_t size = 0; WriteWatchCoverage coverage; #else static constexpr std::size_t LeafCount = std::size_t{1} << 15; #endif // Atomic only so a per-thread memo hit can read it without the mutex (every mutation and every // stamp still happen under it): a hit must return the current value, including MarkWritten // bumps, or an image refreshed after a stamp would keep failing UnchangedSince until the next // walk of its range and re-upload at every use of the epoch. std::atomic generation{1}; std::atomic stable{1}; std::vector pages; struct Memo { std::uintptr_t begin = 0; std::uintptr_t end = 0; std::uint64_t epoch = 0; std::uint64_t unwatched = 0; std::uint64_t mapping = 0; }; struct ObservationLeaf { std::array, LeafBlocks> ticks{}; std::array, LeafBlocks / CoarseBlocks> coarse{}; std::array, LeafBlocks> times{}; std::array, LeafBlocks / CoarseBlocks> coarseTimes{}; }; std::unique_ptr[]> observationLeaves; std::size_t observationLeafCount = 0; std::atomic*> observationTable{nullptr}; std::atomic observationFloor{0}; std::atomic observationTimeFloor{0}; std::atomic observationUnwatched{std::numeric_limits::max()}; std::atomic observationMapping{std::numeric_limits::max()}; struct ExactObservation { std::uint64_t first = 0; std::uint64_t stop = 0; std::uint64_t tick = 0; std::uint64_t time = 0; }; std::array exactObservations{}; std::size_t nextExactObservation = 0; bool exactlyObserved(std::uint64_t first, std::uint64_t stop, std::uint64_t need, std::uint64_t timeNeed, bool& hitByTime) const { for (const auto& entry : exactObservations) { if (entry.first > first || stop > entry.stop) continue; if (entry.tick >= need) return true; if (timeNeed != 0 && entry.time > timeNeed) { hitByTime = true; return true; } } return false; } void initialize() { if (initialized) return; initialized = true; #ifdef _WIN32 GuestArena::GuestArenaRange_nid_postfix(&base, &size); watched = size != 0 && GuestArena::GuestArenaWriteWatched_nid_postfix(); if (!watched) return; leaves.resize((size / WriteBlockBytes + LeafBlocks) / LeafBlocks); coverage.Initialize(base, size, std::getenv("APS5_NO_COVERAGE_SUMMARY") == nullptr); pages.resize(1u << 16); GuestArena::GuestArenaSetPrivateMappingObserver_nid_postfix(&watchPrivateMapping); #else watched = GuestWriteWatch::GuestWriteWatchAvailable_nid_postfix(); if (watched) leaves.resize(LeafCount); #endif if (!watched) return; observationLeafCount = leaves.size(); observationLeaves = std::make_unique[]>(observationLeafCount); observationTable.store(observationLeaves.get(), std::memory_order_release); } bool inObservationRange(std::uint64_t first, std::uint64_t stop) const { #ifdef _WIN32 return first >= base && stop <= base + size; #else return stop <= LeafCount * LeafBlocks * WriteBlockBytes; #endif } std::uint64_t observedTick(std::uint64_t block) const { if (block / LeafBlocks >= observationLeafCount) return 0; const auto* leaf = observationLeaves[block / LeafBlocks].load(std::memory_order_relaxed); return leaf != nullptr ? leaf->ticks[block % LeafBlocks].load(std::memory_order_relaxed) : 0; } std::uint64_t observedTime(std::uint64_t block) const { if (block / LeafBlocks >= observationLeafCount) return 0; const auto* leaf = observationLeaves[block / LeafBlocks].load(std::memory_order_relaxed); return leaf != nullptr ? leaf->times[block % LeafBlocks].load(std::memory_order_relaxed) : 0; } bool observedSince(std::uint64_t first, std::uint64_t stop, std::uint64_t epoch, std::uint64_t since, std::uint64_t unwatched, std::uint64_t mapping) const { const auto* table = observationTable.load(std::memory_order_acquire); if (table == nullptr || observationUnwatched.load(std::memory_order_acquire) != unwatched || observationMapping.load(std::memory_order_acquire) != mapping) return false; if (!inObservationRange(first, stop)) return false; const auto need = std::max(epoch, observationFloor.load(std::memory_order_acquire)); const auto timeNeed = since != 0 ? std::max(since, observationTimeFloor.load(std::memory_order_acquire)) : 0; const auto last = blockOf(stop - 1); bool fromSharedTime = false; auto block = blockOf(first); while (block <= last) { const auto index = block / LeafBlocks; if (index >= observationLeafCount) return false; const auto* leaf = table[index].load(std::memory_order_acquire); if (leaf == nullptr) return false; const auto end = std::min(last + 1, (index + 1) * LeafBlocks); while (block < end) { if (block % CoarseBlocks == 0 && block + CoarseBlocks <= end) { const auto group = (block % LeafBlocks) / CoarseBlocks; if (leaf->coarse[group].load(std::memory_order_acquire) >= need) { block += CoarseBlocks; continue; } if (timeNeed == 0) return false; if (leaf->coarseTimes[group].load(std::memory_order_acquire) > timeNeed) { fromSharedTime = true; block += CoarseBlocks; continue; } } const auto slot = block % LeafBlocks; if (leaf->ticks[slot].load(std::memory_order_acquire) < need) { if (timeNeed == 0 || leaf->times[slot].load(std::memory_order_acquire) <= timeNeed) return false; fromSharedTime = true; } ++block; } } if (fromSharedTime) sharedWalkHits.fetch_add(1, std::memory_order_relaxed); return true; } void publishObserved(std::uint64_t first, std::uint64_t last, std::uint64_t tick, std::uint64_t walkStarted) { for (auto block = first; block <= last;) { const auto index = block / LeafBlocks; auto* leaf = observationLeaves[index].load(std::memory_order_relaxed); if (leaf == nullptr) { leaf = new ObservationLeaf(); observationLeaves[index].store(leaf, std::memory_order_release); } const auto end = std::min(last + 1, (index + 1) * LeafBlocks); for (auto at = block; at < end; ++at) { const auto slot = at % LeafBlocks; auto& tickSlot = leaf->ticks[slot]; if (tickSlot.load(std::memory_order_relaxed) < tick) tickSlot.store(tick, std::memory_order_release); auto& timeSlot = leaf->times[slot]; if (timeSlot.load(std::memory_order_relaxed) < walkStarted) timeSlot.store(walkStarted, std::memory_order_release); } for (auto group = (block % LeafBlocks) / CoarseBlocks; group <= ((end - 1) % LeafBlocks) / CoarseBlocks; ++group) { std::uint64_t leastTick = std::numeric_limits::max(); std::uint64_t leastTime = std::numeric_limits::max(); for (std::size_t at = group * CoarseBlocks; at < (group + 1) * CoarseBlocks; ++at) { leastTick = std::min(leastTick, leaf->ticks[at].load(std::memory_order_relaxed)); leastTime = std::min(leastTime, leaf->times[at].load(std::memory_order_relaxed)); } leaf->coarse[group].store(leastTick, std::memory_order_release); leaf->coarseTimes[group].store(leastTime, std::memory_order_release); } block = end; } } bool covers(std::uint64_t address, std::size_t bytes) const { #ifdef _WIN32 return coverage.Covers(address, bytes) && !GuestArena::GuestArenaHostRegionOverlaps_nid_postfix(static_cast(address), bytes); #else return address + bytes <= LeafCount * LeafBlocks * WriteBlockBytes && GuestWriteWatch::GuestWriteWatchCovers_nid_postfix(static_cast(address), bytes); #endif } std::uint64_t blockOf(std::uint64_t address) const { #ifdef _WIN32 return (address - base) / WriteBlockBytes; #else return address / WriteBlockBytes; #endif } std::uint64_t blockBegin(std::uint64_t block) const { #ifdef _WIN32 return base + block * WriteBlockBytes; #else return block * WriteBlockBytes; #endif } #ifdef _WIN32 void startHints(std::uint64_t address, std::size_t bytes) { const auto first = std::max(address, base); const auto stop = std::min(address + bytes, base + size); if (first >= stop) return; bool started = false; for (auto block = blockOf(first); block <= blockOf(stop - 1); ++block) { if (!coverage.Covers(blockBegin(block), static_cast(std::min(WriteBlockBytes, base + size - blockBegin(block))))) continue; if (!started) ++generation; started = true; stampHint(block); } } bool hinted(std::uint64_t first, std::uint64_t stop) const { if (first >= stop || first < base || stop > base + size) return false; for (auto block = blockOf(first); block <= blockOf(stop - 1); ++block) { if (hintOf(block) == 0 || coverage.Covers(blockBegin(block), static_cast(std::min(WriteBlockBytes, base + size - blockBegin(block))))) return false; } return !GuestArena::GuestArenaHostRegionOverlaps_nid_postfix(static_cast(first), static_cast(stop - first)); } std::uint64_t newestHint(std::uint64_t first, std::uint64_t stop) const { std::uint64_t newest = 0; for (auto block = blockOf(first); block <= blockOf(stop - 1); ++block) newest = std::max(newest, hintOf(block)); return newest; } #endif struct DriverPiece { std::uint64_t generation = 0; std::uint32_t begin = 0; std::uint32_t end = 0; }; struct DriverPieces { std::uint64_t whole = 0; std::uint64_t dropped = 0; std::array pieces{}; std::uint64_t possibleWhole = 0; std::uint64_t possibleDropped = 0; std::array possiblePieces{}; bool covers(std::uint32_t begin, std::uint32_t end, std::uint64_t generation) const { if (generation == 0 || begin >= end || dropped > generation) return false; if (whole > generation) return true; while (begin < end) { auto covered = begin; for (const auto& piece : pieces) { if (piece.generation > generation && piece.begin <= begin && piece.end > covered) covered = piece.end; } if (covered == begin) return false; begin = covered; } return true; } }; std::unordered_map driverPieces; std::unordered_map rewatchStamps; std::atomic anyRewatchStamp{false}; struct CpuPages { std::array pages{}; }; std::unordered_map cpuPages; std::unordered_map cpuStoredPages; std::unordered_map walkPages; std::unordered_map windowPages; std::unordered_map rewatchPages; std::map refused; void noteCpuStore(std::uint64_t begin, std::uint64_t end, std::uint64_t stampGeneration) { notePages(cpuPages, begin, end, stampGeneration); notePages(cpuStoredPages, begin, end, stampGeneration); } void noteCpuTouch(std::uint64_t begin, std::uint64_t end, std::uint64_t stampGeneration) { notePages(cpuPages, begin, end, stampGeneration); } void noteWalkStore(std::uint64_t begin, std::uint64_t end, std::uint64_t stampGeneration) { notePages(walkPages, begin, end, stampGeneration); } void notePages(std::unordered_map& pages, std::uint64_t begin, std::uint64_t end, std::uint64_t stampGeneration) { for (auto block = blockOf(begin); block <= blockOf(end - 1); ++block) { const auto blockStart = blockBegin(block); const auto from = std::max(begin, blockStart) - blockStart; const auto to = std::min(end, blockStart + WriteBlockBytes) - blockStart; auto& entry = pages[block]; for (auto page = from / WritePageBytes; page <= (to - 1) / WritePageBytes; ++page) { auto& stamp = entry.pages[page]; stamp = std::max(stamp, stampGeneration); } } } void forgetRewatchedPages(std::uint64_t block, std::uint64_t begin, std::uint64_t end) { const auto found = rewatchPages.find(block); if (found == rewatchPages.end()) return; auto& pages = found->second.pages; const auto blockStart = blockBegin(block); for (auto page = (std::max(begin, blockStart) - blockStart) / WritePageBytes; page < pages.size() && blockStart + page * WritePageBytes < end; ++page) pages[page] = 0; if (std::ranges::all_of(pages, [](std::uint64_t stamp) { return stamp == 0; })) rewatchPages.erase(found); } bool blockPartWatched(std::uint64_t first, std::uint64_t stop) const { #ifdef _WIN32 for (auto page = first; page < stop; page = (page / WritePageBytes + 1) * WritePageBytes) { if (covers(page, 1)) return true; } return false; #else return GuestWriteWatch::GuestWriteWatchOverlaps_nid_postfix(static_cast(first), static_cast(stop - first)); #endif } void stampWatchedPart(std::uint64_t address, std::uint64_t end, std::uint64_t stampGeneration, bool complete) { #ifdef _WIN32 address = std::max(address, base); end = std::min(end, base + size); if (address >= end) return; #else end = std::min(end, LeafCount * LeafBlocks * WriteBlockBytes); if (address >= end || !GuestWriteWatch::GuestWriteWatchOverlaps_nid_postfix(static_cast(address), static_cast(end - address))) return; #endif for (auto block = blockOf(address); block <= blockOf(end - 1); ++block) { const auto first = std::max(address, blockBegin(block)); const auto stop = std::min(end, blockBegin(block) + WriteBlockBytes); if (!blockPartWatched(first, stop)) continue; stamp(block, stampGeneration, StampKind::Driver); noteDriverStore(block, address, end, stampGeneration, complete); } } void noteDriverStore(std::uint64_t block, std::uint64_t address, std::uint64_t end, std::uint64_t stampGeneration, bool complete) { const auto begin = blockBegin(block); const auto from = static_cast(std::max(address, begin) - begin); const auto to = static_cast(std::min(end, begin + WriteBlockBytes) - begin); if (from == 0 && to == WriteBlockBytes) { auto& entry = driverPieces[block]; if (complete) { entry = DriverPieces{}; entry.whole = stampGeneration; } else { entry.possibleWhole = stampGeneration; entry.possibleDropped = 0; entry.possiblePieces = {}; } return; } auto& entry = driverPieces[block]; auto& pieces = complete ? entry.pieces : entry.possiblePieces; auto& dropped = complete ? entry.dropped : entry.possibleDropped; DriverPiece* contained = nullptr; for (auto& piece : pieces) { if (piece.generation == 0 || piece.begin < from || piece.end > to) continue; if (contained == nullptr) contained = &piece; else piece = {}; } if (contained != nullptr) { *contained = {stampGeneration, from, to}; return; } auto* oldest = &pieces.front(); for (auto& piece : pieces) { if (piece.generation < oldest->generation) oldest = &piece; } dropped = std::max(dropped, oldest->generation); *oldest = {stampGeneration, from, to}; } Leaf& leafFor(std::uint64_t block) { auto& leaf = leaves[block / LeafBlocks]; if (leaf == nullptr) leaf = std::make_unique(); return *leaf; } #ifdef _WIN32 void stampHint(std::uint64_t block) { leafFor(block).hintBlocks[block % LeafBlocks] = generation; } std::uint64_t hintOf(std::uint64_t block) const { const auto& leaf = leaves[block / LeafBlocks]; return leaf != nullptr ? leaf->hintBlocks[block % LeafBlocks] : 0; } #endif std::uint64_t stampOf(std::uint64_t block) const { const auto& leaf = leaves[block / LeafBlocks]; return leaf != nullptr ? leaf->blocks[block % LeafBlocks] : 0; } static constexpr std::size_t UnstampedSlots = 1u << 16; std::vector unstampedStores; void noteUnstampedStore(std::uint64_t address, std::uint64_t end) { if (unstampedStores.empty()) unstampedStores.assign(UnstampedSlots, 0); const auto first = address / WriteBlockBytes; const auto last = (end - 1) / WriteBlockBytes; if (last - first >= UnstampedSlots) { std::fill(unstampedStores.begin(), unstampedStores.end(), generation); return; } for (auto block = first; block <= last; ++block) unstampedStores[block % UnstampedSlots] = generation; } std::uint64_t newestUnstampedStamp(std::uint64_t address, std::uint64_t end) const { if (unstampedStores.empty()) return 0; const auto first = address / WriteBlockBytes; const auto last = (end - 1) / WriteBlockBytes; if (last - first >= UnstampedSlots) return *std::max_element(unstampedStores.begin(), unstampedStores.end()); std::uint64_t newest = 0; for (auto block = first; block <= last; ++block) newest = std::max(newest, unstampedStores[block % UnstampedSlots]); return newest; } std::uint64_t newestStamp(std::uint64_t address, std::uint64_t end) const { auto newest = newestUnstampedStamp(address, end); if (!watched) return newest; #ifdef _WIN32 address = std::max(address, base); end = std::min(end, base + size); #else end = std::min(end, LeafCount * LeafBlocks * WriteBlockBytes); #endif if (address >= end) return newest; for (auto block = blockOf(address); block <= blockOf(end - 1); ++block) newest = std::max(newest, stampOf(block)); return newest; } std::uint64_t coarseStampOf(std::uint64_t block) const { const auto& leaf = leaves[block / LeafBlocks]; return leaf != nullptr ? leaf->coarseBlocks[(block % LeafBlocks) / CoarseBlocks] : 0; } bool unchanged(std::uint64_t first, std::uint64_t last, std::uint64_t since) const { if (first == last) return stampOf(first) <= since; const auto newer = [since](std::uint64_t stamp) { return stamp > since; }; while (first <= last) { const auto& leaf = leaves[first / LeafBlocks]; if (leaf == nullptr) { first = (first / LeafBlocks + 1) * LeafBlocks; continue; } const auto end = std::min(last + 1, (first / CoarseBlocks + 1) * CoarseBlocks); if (end - first < CoarseBlocks || coarseStampOf(first) > since) { const auto begin = leaf->blocks.begin() + first % LeafBlocks; if (std::any_of(begin, begin + (end - first), newer)) return false; } first = end; } return true; } std::uint64_t cpuStampOf(std::uint64_t block) const { const auto& leaf = leaves[block / LeafBlocks]; return leaf != nullptr ? leaf->cpuBlocks[block % LeafBlocks] : 0; } bool storedOver(std::uint64_t address, std::uint64_t end, std::uint64_t generation, bool walked, bool storesOnly = false) const { for (auto block = blockOf(address); block <= blockOf(end - 1); ++block) { if (stampOf(block) <= generation) continue; const auto begin = blockBegin(block); const auto from = std::max(address, begin) - begin; const auto to = std::min(end, begin + WriteBlockBytes) - begin; const auto newerPage = [&](const std::unordered_map& pages, std::uint64_t first, std::uint64_t stop) { const auto found = pages.find(block); if (found == pages.end()) return false; for (auto page = first / WritePageBytes; page <= (stop - 1) / WritePageBytes; ++page) { if (found->second.pages[page] > generation) return true; } return false; }; if (cpuPages.find(block) == cpuPages.end() && cpuStampOf(block) > generation) return true; if (newerPage(storesOnly ? cpuStoredPages : cpuPages, from, to)) return true; if (walked && newerPage(walkPages, from, to)) return true; const auto found = driverPieces.find(block); if (found == driverPieces.end()) { if (!walked && newerPage(walkPages, 0, WriteBlockBytes)) return true; continue; } const auto& entry = found->second; if (entry.whole > generation || entry.dropped > generation || entry.possibleWhole > generation || entry.possibleDropped > generation) return true; for (const auto& piece : entry.pieces) { if (piece.generation > generation && piece.begin < to && from < piece.end) return true; } for (const auto& piece : entry.possiblePieces) { if (piece.generation > generation && piece.begin < to && from < piece.end) return true; } if (!walked && walkedBesidePieces(block, entry, from, to, generation)) return true; } return false; } bool walkedBesidePieces(std::uint64_t block, const DriverPieces& entry, std::uint64_t from, std::uint64_t to, std::uint64_t generation) const { const auto found = walkPages.find(block); if (found == walkPages.end()) return false; const auto touches = [&](const std::array& pieces, std::uint64_t pageBegin) { return std::any_of(pieces.begin(), pieces.end(), [&](const DriverPiece& piece) { return piece.generation > generation && piece.begin < pageBegin + WritePageBytes && pageBegin < piece.end; }); }; for (auto page = from / WritePageBytes; page <= (to - 1) / WritePageBytes; ++page) { const auto pageBegin = page * WritePageBytes; if (found->second.pages[page] > generation && !touches(entry.pieces, pageBegin) && !touches(entry.possiblePieces, pageBegin)) return true; } return false; } bool driverStoredOver(std::uint64_t address, std::uint64_t end, std::uint64_t generation) const { for (auto block = blockOf(address); block <= blockOf(end - 1); ++block) { const auto found = driverPieces.find(block); if (found == driverPieces.end()) continue; const auto begin = blockBegin(block); const auto from = std::max(address, begin) - begin; const auto to = std::min(end, begin + WriteBlockBytes) - begin; const auto& entry = found->second; if (entry.whole > generation || entry.dropped > generation || entry.possibleWhole > generation || entry.possibleDropped > generation) return true; for (const auto& piece : entry.pieces) { if (piece.generation > generation && piece.begin < to && from < piece.end) return true; } for (const auto& piece : entry.possiblePieces) { if (piece.generation > generation && piece.begin < to && from < piece.end) return true; } } return false; } bool refusedSince(std::uint64_t address, std::uint64_t end, std::uint64_t since) const { const auto last = blockOf(end - 1); for (auto it = refused.lower_bound(blockOf(address)); it != refused.end() && it->first <= last; ++it) { if (it->second > since) return true; } return false; } bool rangeUnchanged(std::uint64_t address, std::size_t bytes, std::uint64_t since, bool walked = true, bool storesOnly = false) const { if (refusedSince(address, address + bytes, since)) return false; return unchanged(blockOf(address), blockOf(address + bytes - 1), since) || !storedOver(address, address + bytes, since, walked, storesOnly); } bool cpuStoreUnchanged(std::uint64_t address, std::size_t bytes, std::uint64_t generation) const { const auto first = blockOf(address); const auto last = blockOf(address + bytes - 1u); const auto end = address + bytes; for (auto block = first; block <= last; ++block) { if (const auto found = cpuPages.find(block); found != cpuPages.end()) { const auto stored = cpuStoredPages.find(block); const auto begin = blockBegin(block); const auto from = std::max(address, begin) - begin; const auto to = std::min(end, begin + WriteBlockBytes) - begin; for (auto page = from / WritePageBytes; page <= (to - 1u) / WritePageBytes; ++page) { if (found->second.pages[page] > generation && stored != cpuStoredPages.end() && stored->second.pages[page] > generation) return false; } } else if (cpuStampOf(block) > generation) { return false; } } return true; } bool cpuUnchanged(std::uint64_t address, std::size_t bytes, std::uint64_t generation) const { const auto first = blockOf(address); const auto last = blockOf(address + bytes - 1u); const auto end = address + bytes; for (auto block = first; block <= last; ++block) { if (const auto found = cpuPages.find(block); found != cpuPages.end()) { const auto begin = blockBegin(block); const auto from = std::max(address, begin) - begin; const auto to = std::min(end, begin + WriteBlockBytes) - begin; for (auto page = from / WritePageBytes; page <= (to - 1u) / WritePageBytes; ++page) { if (found->second.pages[page] > generation) return false; } } else if (cpuStampOf(block) > generation) { return false; } } return true; } void stamp(std::uint64_t block, std::uint64_t stampGeneration, StampKind kind) { const bool cpu = kind == StampKind::Cpu || kind == StampKind::ImportWindow; const bool stored = kind != StampKind::ImportWindow; auto& leaf = leafFor(block); if (stored) { leaf.blocks[block % LeafBlocks] = stampGeneration; auto& coarse = leaf.coarseBlocks[(block % LeafBlocks) / CoarseBlocks]; coarse = std::max(coarse, stampGeneration); } if (cpu) leaf.cpuBlocks[block % LeafBlocks] = stampGeneration; if (stored) bumpSubscriptions(blockBegin(block), WriteBlockBytes, kind == StampKind::Driver ? WriteBumpSource::Driver : WriteBumpSource::Cpu); } }; WriteTracker& Tracker() { static WriteTracker tracker; return tracker; } // Takes the tracker mutex; under APS5_PROFILE_DRAW an acquisition that found it held is counted // ('tracker waits N / M' in [guestmem]), which says whether walking outside the lock would pay. class TrackerLock { public: explicit TrackerLock(WriteTracker& tracker) : tracker(tracker), lock(tracker.mutex, std::defer_lock) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (!profile) { lock.lock(); return; } if (!lock.try_lock()) { trackerWaits.fetch_add(1, std::memory_order_relaxed); lock.lock(); } trackerAcquisitions.fetch_add(1, std::memory_order_relaxed); } ~TrackerLock() { if (lock.owns_lock()) publish(); } TrackerLock(const TrackerLock&) = delete; TrackerLock& operator=(const TrackerLock&) = delete; void Unlock() { publish(); lock.unlock(); } void Stabilize() { publish(); } void Suspend() { lock.unlock(); } void Resume() { lock.lock(); } class Suspension { public: explicit Suspension(TrackerLock& owner) : owner(owner) { owner.Suspend(); } ~Suspension() { owner.Resume(); } Suspension(const Suspension&) = delete; Suspension& operator=(const Suspension&) = delete; private: TrackerLock& owner; }; private: void publish() { const auto current = tracker.generation.load(std::memory_order_relaxed); if (tracker.stable.load(std::memory_order_relaxed) != current) tracker.stable.store(current, std::memory_order_release); } WriteTracker& tracker; std::unique_lock lock; }; TrackerLock lockTracker(WriteTracker& tracker) { return TrackerLock(tracker); } #ifdef _WIN32 void watchPrivateMapping(std::uintptr_t address, std::size_t bytes, std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); if (!tracker.watched || bytes == 0 || bytes > tracker.size || address < tracker.base || address - tracker.base > tracker.size - bytes) return; tracker.coverage.Restore(address, bytes, generation); ++tracker.generation; tracker.noteCpuStore(address, address + bytes, tracker.generation); for (auto block = tracker.blockOf(address); block <= tracker.blockOf(address + bytes - 1); ++block) { if (const auto& leaf = tracker.leaves[block / WriteTracker::LeafBlocks]; leaf != nullptr) leaf->hintBlocks[block % WriteTracker::LeafBlocks] = 0; if (const auto found = tracker.driverPieces.find(block); found != tracker.driverPieces.end()) found->second.dropped = std::max(found->second.dropped, tracker.generation); tracker.stamp(block, tracker.generation, StampKind::Cpu); } unwatchSerial.fetch_add(1, std::memory_order_release); } #endif std::atomic nextCollectEpoch{1}; struct CollectEpochSlot {}; std::atomic lastBumpedEpoch{0}; std::atomic observationHook{nullptr}; std::uint64_t currentCollectEpoch() { if (const auto epoch = HostThreadSlot::Get(); epoch != 0) return epoch; return nextCollectEpoch.fetch_add(1, std::memory_order_acq_rel) + 1; } bool collectMemoEnabled() { static const bool disabled = std::getenv("APS5_NO_COLLECT_MEMO") != nullptr; return !disabled; } struct ThreadCollectMemo { std::array entries{}; std::size_t next = 0; }; void syncObservationContext(WriteTracker& tracker, std::uint64_t unwatched, std::uint64_t mapping) { if (tracker.observationUnwatched.load(std::memory_order_relaxed) == unwatched && tracker.observationMapping.load(std::memory_order_relaxed) == mapping) return; tracker.observationFloor.store(nextCollectEpoch.fetch_add(1, std::memory_order_acq_rel) + 1, std::memory_order_release); tracker.observationTimeFloor.store(SteadyNanoseconds(), std::memory_order_release); tracker.observationUnwatched.store(unwatched, std::memory_order_release); tracker.observationMapping.store(mapping, std::memory_order_release); } void observationPoint(int point) { if (const auto hook = observationHook.load(std::memory_order_acquire)) hook(point); } struct StampRuns { WriteTracker& tracker; StampKind kind; std::size_t stamped = 0; const WindowCopy* window = nullptr; std::vector> windowRuns; }; void noteWrittenRun(StampRuns& runs, std::uintptr_t begin, std::uintptr_t end, std::uint64_t generation, bool changed = true) { if (runs.kind == StampKind::Driver) runs.tracker.noteWalkStore(begin, end, generation); else if (changed && runs.kind != StampKind::ImportWindow) runs.tracker.noteCpuStore(begin, end, generation); else runs.tracker.noteCpuTouch(begin, end, generation); } void stampWrittenRun(void* context, std::uintptr_t begin, std::uintptr_t end) { auto& runs = *static_cast(context); auto& tracker = runs.tracker; if (end <= begin) return; ++runs.stamped; if (runs.window != nullptr) runs.windowRuns.emplace_back(begin, end); else { const auto generation = tracker.generation.load(std::memory_order_relaxed); noteWrittenRun(runs, begin, end, generation); for (auto block = tracker.blockOf(begin); block <= tracker.blockOf(end - 1); ++block) tracker.stamp(block, generation, runs.kind); } #ifndef _WIN32 collectDirtyRuns.fetch_add(1, std::memory_order_relaxed); #endif } void stampWindowRuns(StampRuns& runs) { const auto pages = PagesOf(runs.windowRuns); const auto trapped = TrappedPages(pages); std::vector held(pages.size(), 0); SplitPages(pages.size(), [&](std::size_t from, std::size_t to) { for (auto index = from; index < to; ++index) held[index] = trapped[index] == 0 && runs.window->Holds(static_cast(pages[index])); }); auto& tracker = runs.tracker; const auto generation = tracker.generation.load(std::memory_order_relaxed); std::size_t index = 0; for (const auto& [begin, end] : runs.windowRuns) { for (auto page = begin; page < end; page += WritePageBytes) { const bool kept = held[index++] != 0; noteWrittenRun(runs, static_cast(page), static_cast(page + WritePageBytes), generation, !kept); if (!kept) tracker.notePages(tracker.windowPages, page, page + WritePageBytes, generation); tracker.stamp(tracker.blockOf(page), generation, kept ? runs.window->held : runs.kind); } } } #ifdef _WIN32 std::atomic freshCollectHook{nullptr}; bool collectWindowsWrites(StampRuns& runs, std::uint64_t first, std::uint64_t stop, bool armedOnly) { auto& tracker = runs.tracker; const bool fresh = runs.kind == StampKind::Fresh; if (fresh) { if (const auto hook = freshCollectHook.load(std::memory_order_acquire)) return hook(static_cast(first), static_cast(stop - first), &stampWrittenRun, &runs); } const auto collect = fresh ? &GuestArena::GuestArenaCollectFreshWrites_nid_postfix : armedOnly ? &GuestArena::GuestArenaCollectArmedWrites_nid_postfix : &GuestArena::GuestArenaCollectWrites_nid_postfix; static const bool singlePass = std::getenv("APS5_NO_SINGLE_PASS_COLLECT") == nullptr; const auto walk = [&](bool clear) { auto cursor = first; while (cursor < stop) { std::size_t count = tracker.pages.size(); if (!collect(cursor, static_cast(stop - cursor), tracker.pages.data(), &count, clear)) return false; for (std::size_t i = 0; i < count; ++i) { const auto page = reinterpret_cast(tracker.pages[i]); stampWrittenRun(&runs, page, page + WritePageBytes); } if (count < tracker.pages.size()) break; cursor = reinterpret_cast(tracker.pages[count - 1]) + WritePageBytes; } return true; }; if (!walk(singlePass || fresh)) return false; if (runs.stamped != 0) collectDirty.fetch_add(1, std::memory_order_relaxed); return fresh || singlePass || runs.stamped == 0 || walk(true); } void noteRefusedWalk(WriteTracker& tracker, std::uint64_t first, std::uint64_t stop) { const auto pagesOf = [&](auto list, auto&& each) { auto cursor = first; while (cursor < stop) { std::size_t count = tracker.pages.size(); list(static_cast(cursor), static_cast(stop - cursor), tracker.pages.data(), &count); for (std::size_t i = 0; i < count; ++i) each(reinterpret_cast(tracker.pages[i])); if (count < tracker.pages.size()) break; cursor = reinterpret_cast(tracker.pages[count - 1]) + WritePageBytes; } }; StampRuns runs{tracker, StampKind::Cpu}; pagesOf(&GuestArena::GuestArenaTakeUnreportedPages_nid_no_patch, [&](std::uintptr_t page) { stampWrittenRun(&runs, page, page + WritePageBytes); }); const auto generation = tracker.generation.load(std::memory_order_relaxed); pagesOf(&GuestArena::GuestArenaComparedPages_nid_no_patch, [&](std::uintptr_t page) { tracker.refused[tracker.blockOf(page)] = generation; }); } #endif bool walkWrites(WriteTracker& tracker, std::uint64_t first, std::uint64_t stop, StampKind kind, bool armedOnly = false, const WindowCopy* window = nullptr) { ++tracker.generation; observationPoint(1); StampRuns runs{tracker, kind, 0, window, {}}; #ifdef _WIN32 const bool complete = collectWindowsWrites(runs, first, stop, armedOnly); #else const auto dirtyRuns = collectDirtyRuns.load(std::memory_order_relaxed); const auto collect = armedOnly ? &GuestWriteWatch::GuestWriteWatchCollectArmed_nid_postfix : &GuestWriteWatch::GuestWriteWatchCollect_nid_postfix; const bool complete = collect(static_cast(first), static_cast(stop - first), &stampWrittenRun, &runs); if (collectDirtyRuns.load(std::memory_order_relaxed) != dirtyRuns) collectDirty.fetch_add(1, std::memory_order_relaxed); #endif if (window != nullptr) stampWindowRuns(runs); #ifdef _WIN32 if (!complete) noteRefusedWalk(tracker, first, stop); #endif return complete; } struct CollectSinceSlot {}; struct CollectPrefetch { static constexpr std::size_t Slots = 16; static constexpr std::size_t RangesPerEpoch = 8192; static constexpr std::size_t GapsBeforeDecay = 4096; static constexpr std::size_t KnownRanges = 1u << 16; std::mutex mutex; std::condition_variable wake; std::array>, Slots> ranges; std::array tags{}; std::array gaps{}; std::size_t gapSamples = 0; std::unordered_map lastWalk; std::atomic bumps{0}; std::uint64_t served = 0; bool started = false; }; CollectPrefetch& collectPrefetch() { static auto* prefetch = new CollectPrefetch(); return *prefetch; } std::atomic collectPrefetchSetting{-1}; bool collectPrefetchEnabled() { static const bool enabled = std::getenv("APS5_NO_COLLECT_PREFETCH") == nullptr; return enabled && collectMemoEnabled(); } bool collectPrefetchWalking() { return collectPrefetchEnabled() && collectPrefetchSetting.load(std::memory_order_relaxed) != 0; } thread_local bool collectPrefetchThread = false; std::uint64_t prefetchPeriod(const CollectPrefetch& prefetch) { std::size_t best = 0; for (std::size_t gap = 2; gap < prefetch.gaps.size(); ++gap) { if (prefetch.gaps[gap] > (best == 0 ? 0 : prefetch.gaps[best])) best = gap; } return best; } std::vector>& prefetchSlot(CollectPrefetch& prefetch, std::uint64_t bump) { const auto slot = bump % CollectPrefetch::Slots; if (prefetch.tags[slot] != bump) { prefetch.ranges[slot].clear(); prefetch.tags[slot] = bump; } return prefetch.ranges[slot]; } void notePrefetchRange(std::uint64_t first, std::uint64_t stop) { auto& prefetch = collectPrefetch(); std::lock_guard lock(prefetch.mutex); const auto bump = prefetch.bumps.load(std::memory_order_relaxed); auto& ranges = prefetchSlot(prefetch, bump); if (ranges.size() < CollectPrefetch::RangesPerEpoch) ranges.emplace_back(first, stop); if (prefetch.lastWalk.size() >= CollectPrefetch::KnownRanges) prefetch.lastWalk.clear(); auto& last = prefetch.lastWalk[first * 0x9e3779b97f4a7c15ull ^ stop]; if (last != 0 && bump > last && bump - last < CollectPrefetch::Slots) { ++prefetch.gaps[bump - last]; if (++prefetch.gapSamples >= CollectPrefetch::GapsBeforeDecay) { for (auto& count : prefetch.gaps) count /= 2; prefetch.gapSamples /= 2; } } last = bump; } Observation observe(std::uint64_t address, std::size_t bytes, bool memoized) { using Status = Observation::Status; if (bytes == 0 || bytes > std::numeric_limits::max() - address) return {Status::Uncovered, 0}; auto& tracker = Tracker(); constexpr std::uint64_t page = 4096; const auto first = address & ~(page - 1); const auto stop = (address + bytes + page - 1) & ~(page - 1); if (stop <= first) return {Status::Uncovered, 0}; const auto epoch = currentCollectEpoch(); const bool shared = memoized && collectMemoEnabled() && HostThreadSlot::Get() != 0; const auto since = shared && sharedCollectWalks.load(std::memory_order_relaxed) ? HostThreadSlot::Get() : 0; if (shared && tracker.observedSince(first, stop, epoch, since, unwatchSerial.load(std::memory_order_acquire), GuestAllocations::GuestAllocationsGeneration_nid_postfix())) { collectMemoHits.fetch_add(1, std::memory_order_relaxed); return {Status::Complete, tracker.stable.load(std::memory_order_acquire)}; } auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || !tracker.covers(address, bytes)) return {Status::Uncovered, 0}; syncObservationContext(tracker, unwatchSerial.load(std::memory_order_acquire), GuestAllocations::GuestAllocationsGeneration_nid_postfix()); const auto tick = nextCollectEpoch.load(std::memory_order_acquire); struct Run { std::uint64_t first; std::uint64_t stop; bool exact; }; struct RunSlot {}; auto& runs = ThreadScratch, RunSlot>(); runs.clear(); bool hitByTime = false; if (!shared) runs.push_back({first, stop, false}); else { const auto need = std::max(epoch, tracker.observationFloor.load(std::memory_order_relaxed)); const auto timeNeed = since != 0 ? std::max(since, tracker.observationTimeFloor.load(std::memory_order_relaxed)) : 0; const auto lastBlock = tracker.blockOf(stop - 1); const auto addRun = [&](std::uint64_t from, std::uint64_t to) { const auto begin = tracker.blockBegin(from); const auto end = tracker.blockBegin(to + 1); if (tracker.covers(begin, static_cast(end - begin))) runs.push_back({begin, end, false}); else if (!tracker.exactlyObserved(std::max(first, begin), std::min(stop, end), need, timeNeed, hitByTime)) runs.push_back({std::max(first, begin), std::min(stop, end), true}); }; bool open = false; std::uint64_t from = 0; for (auto block = tracker.blockOf(first); block <= lastBlock; ++block) { const bool satisfied = tracker.observedTick(block) >= need || (timeNeed != 0 && tracker.observedTime(block) > timeNeed && (hitByTime = true)); if (!satisfied) { if (!open) from = block; open = true; } else if (open) { addRun(from, block - 1); open = false; } } if (open) addRun(from, lastBlock); } if (runs.empty()) { collectMemoHits.fetch_add(1, std::memory_order_relaxed); if (hitByTime) sharedWalkHits.fetch_add(1, std::memory_order_relaxed); } std::optional timed; if (!runs.empty()) timed.emplace(CounterCollect, bytes); const auto walkStarted = !runs.empty() ? SteadyNanoseconds() : 0; std::size_t done = 0; auto status = Status::Complete; for (auto& run : runs) { bool complete = walkWrites(tracker, run.first, run.stop, StampKind::Cpu); if (!complete && (run.first < first || run.stop > stop)) { run = {std::max(first, run.first), std::min(stop, run.stop), true}; complete = walkWrites(tracker, run.first, run.stop, StampKind::Cpu); } if (!complete) { #ifdef _WIN32 status = Status::Refused; #else status = Status::Failed; #endif break; } if (shared && run.exact) tracker.exactObservations[tracker.nextExactObservation++ % tracker.exactObservations.size()] = {run.first, run.stop, tick, walkStarted}; ++done; } lock.Stabilize(); const auto generation = tracker.generation.load(std::memory_order_relaxed); observationPoint(2); for (std::size_t index = 0; index < done; ++index) { auto from = tracker.blockOf(runs[index].first); if (tracker.blockBegin(from) < runs[index].first) ++from; const auto end = tracker.blockOf(runs[index].stop); if (end > from) tracker.publishObserved(from, end - 1, tick, walkStarted); } if (collectPrefetchThread) { if (done != 0) prefetchWalks.fetch_add(1, std::memory_order_relaxed); } else if (shared && done != 0 && status == Status::Complete && collectPrefetchEnabled()) { notePrefetchRange(first, stop); } if (status != Status::Complete) return {status, 0}; return {Status::Complete, generation}; } void runCollectPrefetch() { collectPrefetchThread = true; auto& prefetch = collectPrefetch(); std::vector> pending; std::unordered_set seen; for (;;) { std::uint64_t bump = 0; { std::unique_lock lock(prefetch.mutex); prefetch.wake.wait(lock, [&] { return prefetch.bumps.load(std::memory_order_relaxed) != prefetch.served; }); bump = prefetch.bumps.load(std::memory_order_relaxed); prefetch.served = bump; pending.clear(); if (!collectPrefetchWalking()) continue; const auto period = prefetchPeriod(prefetch); if (period == 0 || bump < period) continue; const auto source = bump - period; const auto slot = source % CollectPrefetch::Slots; if (prefetch.tags[slot] != source) continue; pending = prefetch.ranges[slot]; } seen.clear(); HostThreadSlot::Set(lastBumpedEpoch.load(std::memory_order_acquire)); HostThreadSlot::Set(SteadyNanoseconds()); for (const auto& [first, stop] : pending) { if (prefetch.bumps.load(std::memory_order_acquire) != bump) break; if (!seen.insert(first * 0x9e3779b97f4a7c15ull ^ stop).second) continue; prefetchRanges.fetch_add(1, std::memory_order_relaxed); static_cast(observe(first, static_cast(stop - first), true)); } } } void bumpCollectPrefetch() { if (!collectPrefetchEnabled()) return; auto& prefetch = collectPrefetch(); { std::lock_guard lock(prefetch.mutex); prefetch.bumps.fetch_add(1, std::memory_order_release); if (!collectPrefetchWalking()) return; if (!prefetch.started) { prefetch.started = true; Libc::StartHostThread(runCollectPrefetch).detach(); } } prefetch.wake.notify_one(); } } Observation Observe(std::uint64_t address, std::size_t bytes) { return observe(address, bytes, true); } std::uint64_t CollectWrites(std::uint64_t address, std::size_t bytes) { const auto observation = observe(address, bytes, true); return observation.status == Observation::Status::Complete ? observation.generation : 0; } std::uint64_t CollectWritesUncached(std::uint64_t address, std::size_t bytes) { const auto observation = observe(address, bytes, false); return observation.status == Observation::Status::Complete ? observation.generation : 0; } void SetObservationHookForTest(void (*hook)(int point)) { observationHook.store(hook, std::memory_order_release); } std::uint64_t WriteGeneration() { return Tracker().generation.load(std::memory_order_acquire); } std::atomic changedSinceWalkFailureForTest{false}; void SetChangedSinceWalkFailureForTest(bool fail) { changedSinceWalkFailureForTest.store(fail, std::memory_order_release); } std::uint64_t ChangedSince(std::uint64_t address, std::size_t bytes, std::uint64_t since, std::vector>& changed) { changed.clear(); if (bytes == 0 || bytes > std::numeric_limits::max() - address) return 0; const auto end = address + bytes; const auto append = [&](std::uint64_t begin, std::uint64_t stop) { if (!changed.empty() && changed.back().second == begin) changed.back().second = stop; else changed.emplace_back(begin, stop); }; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched) { append(address, end); return 0; } std::vector> covered; for (auto begin = address; begin < end;) { const auto stop = std::min(end, (begin & ~std::uint64_t{WriteBlockBytes - 1}) + WriteBlockBytes); if (tracker.covers(begin, static_cast(stop - begin))) { if (!covered.empty() && covered.back().second == begin) covered.back().second = stop; else covered.emplace_back(begin, stop); } begin = stop; } std::vector walked(covered.size(), true); const bool cutForTest = changedSinceWalkFailureForTest.load(std::memory_order_acquire); for (std::size_t index = 0; index < covered.size(); ++index) { const auto first = covered[index].first & ~std::uint64_t{WritePageBytes - 1}; const auto stop = (covered[index].second + WritePageBytes - 1) & ~std::uint64_t{WritePageBytes - 1}; if (!cutForTest) { walked[index] = walkWrites(tracker, first, stop, StampKind::Cpu); continue; } const auto cut = first + (((stop - first) / 2) & ~std::uint64_t{WritePageBytes - 1}); if (cut > first) walkWrites(tracker, first, cut, StampKind::Cpu); #ifdef _WIN32 noteRefusedWalk(tracker, cut, stop); #endif walked[index] = false; } const auto newest = [&](std::uint64_t begin) { const auto block = tracker.blockOf(begin); auto stamp = std::max(tracker.stampOf(block), tracker.cpuStampOf(block)); if (!tracker.unstampedStores.empty()) stamp = std::max(stamp, tracker.unstampedStores[(begin / WriteBlockBytes) % WriteTracker::UnstampedSlots]); return stamp; }; auto next = covered.begin(); for (auto begin = address; begin < end;) { const auto stop = std::min(end, (begin & ~std::uint64_t{WriteBlockBytes - 1}) + WriteBlockBytes); while (next != covered.end() && next->second <= begin) ++next; const bool inside = next != covered.end() && next->first <= begin; if (!inside || !walked[static_cast(next - covered.begin())] || newest(begin) > since) append(begin, stop); begin = stop; } return tracker.generation.load(std::memory_order_relaxed); } std::uint64_t CollectWrittenBlocks(std::uint64_t address, std::size_t bytes, std::uint64_t since, std::vector>& written, bool skipRewatch) { written.clear(); if (bytes == 0 || bytes > std::numeric_limits::max() - address) return 0; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched) return 0; #ifdef _WIN32 if (address < tracker.base || bytes > tracker.size || address - tracker.base > tracker.size - bytes) return 0; #endif const auto end = address + bytes; const auto first = tracker.blockOf(address); const auto last = tracker.blockOf(end - 1); const auto clip = [&](std::uint64_t block) { const auto begin = tracker.blockBegin(block); return std::pair{std::max(address, begin), std::min(end, begin + WriteBlockBytes)}; }; std::uint64_t spanBegin = 0; std::uint64_t spanEnd = 0; const auto walkSpan = [&] { if (spanEnd > spanBegin) walkWrites(tracker, spanBegin & ~std::uint64_t{WritePageBytes - 1}, (spanEnd + WritePageBytes - 1) & ~std::uint64_t{WritePageBytes - 1}, StampKind::Cpu); spanBegin = spanEnd = 0; }; const auto extend = [&](std::uint64_t begin, std::uint64_t stop) { if (spanEnd != begin) { walkSpan(); spanBegin = begin; } spanEnd = stop; }; for (auto block = first; block <= last; ++block) { const auto [begin, stop] = clip(block); if (tracker.covers(begin, stop - begin)) { extend(begin, stop); continue; } for (auto page = begin & ~std::uint64_t{WritePageBytes - 1}; page < stop; page += WritePageBytes) { const auto from = std::max(begin, page); const auto to = std::min(stop, page + WritePageBytes); if (tracker.covers(from, static_cast(to - from))) extend(from, to); else walkSpan(); } } walkSpan(); const auto append = [&](std::uint64_t begin, std::uint64_t stop) { if (!written.empty() && written.back().second == begin) written.back().second = stop; else written.emplace_back(begin, stop); }; for (auto block = first; block <= last; ++block) { const bool cpu = tracker.cpuStampOf(block) > since; if (!cpu && tracker.stampOf(block) <= since) continue; const auto [begin, stop] = clip(block); const auto blockStart = tracker.blockBegin(block); const auto noted = tracker.cpuPages.find(block); const auto window = tracker.windowPages.find(block); const auto rewatch = skipRewatch ? tracker.rewatchPages.find(block) : tracker.rewatchPages.end(); const bool rewatched = rewatch != tracker.rewatchPages.end(); std::array listed{}; bool any = false; for (std::size_t page = 0; page < WritePagesPerBlock; ++page) { if (std::max(begin, blockStart + page * WritePageBytes) >= std::min(stop, blockStart + (page + 1) * WritePageBytes)) continue; const bool stored = noted != tracker.cpuPages.end() && noted->second.pages[page] > since; any = any || stored; listed[page] = (stored && !(rewatched && noted->second.pages[page] == rewatch->second.pages[page])) || (window != tracker.windowPages.end() && window->second.pages[page] > since); } if (cpu && !any && !(rewatched && tracker.cpuStampOf(block) == std::ranges::max(rewatch->second.pages))) { append(begin, stop); continue; } for (std::size_t page = 0; page < WritePagesPerBlock; ++page) { if (listed[page]) append(std::max(begin, blockStart + page * WritePageBytes), std::min(stop, blockStart + (page + 1) * WritePageBytes)); } } return tracker.generation.load(std::memory_order_relaxed); } std::uint64_t SteadyNanoseconds() { return static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count()); } void ShareCollectWalks(bool share) { if (sharedCollectWalks.load(std::memory_order_relaxed) != share) sharedCollectWalks.store(share, std::memory_order_relaxed); } bool CollectWalksShared() { return sharedCollectWalks.load(std::memory_order_relaxed); } std::uint64_t CollectSince() { return HostThreadSlot::Get(); } void RaiseCollectSince(std::uint64_t since) { const auto now = SteadyNanoseconds(); const auto raised = since == 0 ? now : std::min(since, now); if (raised > HostThreadSlot::Get()) HostThreadSlot::Set(raised); } void BumpCollectEpochSince(std::uint64_t since) { const auto now = SteadyNanoseconds(); const auto previous = HostThreadSlot::Get(); BumpCollectEpoch(); HostThreadSlot::Set(since == 0 ? now : std::max(previous, std::min(since, now))); } void BumpCollectEpoch() { HostThreadSlot::Set(SteadyNanoseconds()); const auto epoch = nextCollectEpoch.fetch_add(1, std::memory_order_acq_rel) + 1; HostThreadSlot::Set(epoch); auto last = lastBumpedEpoch.load(std::memory_order_relaxed); while (last < epoch && !lastBumpedEpoch.compare_exchange_weak(last, epoch, std::memory_order_release, std::memory_order_relaxed)) {} collectEpochBumps.fetch_add(1, std::memory_order_relaxed); bumpCollectPrefetch(); } std::uint64_t ThreadCollectEpoch() { return collectMemoEnabled() ? HostThreadSlot::Get() : 0; } std::uint64_t UnwatchSerial() { return unwatchSerial.load(std::memory_order_acquire); } void AdoptLatestCollectEpoch() { const auto latest = lastBumpedEpoch.load(std::memory_order_acquire); if (latest > HostThreadSlot::Get()) HostThreadSlot::Set(latest); } std::uint64_t CollectEpochBumps() { return collectEpochBumps.load(std::memory_order_relaxed); } void SetCollectPrefetch(bool enabled) { collectPrefetchSetting.store(enabled ? 1 : 0, std::memory_order_relaxed); } std::uint64_t CollectPrefetchWalks() { return prefetchWalks.load(std::memory_order_relaxed); } namespace { std::atomic proofSerial{1}; thread_local bool proofThread = false; struct OwnProofBreaksSlot {}; } std::uint64_t ProofSerial() { return proofSerial.load(std::memory_order_acquire); } std::uint64_t OwnProofBreaks() { return HostThreadSlot::Get(); } void BreakProofs() { proofSerial.fetch_add(1, std::memory_order_acq_rel); HostThreadSlot::Set(OwnProofBreaks() + 1); } void MarkProofThread() { proofThread = true; } void CollectWritesForGpuUse(const UnchangedQuery& range, GpuUseObservation& observation) { const auto epoch = CollectEpoch(); const auto unwatched = UnwatchSerial(); const auto mapping = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); if (proofThread && epoch != 0 && observation.address == range.address && observation.bytes == range.bytes && observation.generation == range.generation && observation.epoch == epoch && observation.unwatched == unwatched && observation.mapping == mapping) return; const auto collected = CollectWritesUncached(range.address, range.bytes); if (!proofThread || epoch == 0 || collected == 0) { observation = {}; return; } observation = {range.address, range.bytes, range.generation, epoch, unwatched, mapping}; } std::uint64_t CollectEpoch() { return collectMemoEnabled() ? HostThreadSlot::Get() : 0; } namespace { struct ComparedPage { std::uint64_t hash = 0; bool known = false; }; std::atomic leftWatchCompare{false}; std::mutex comparedMutex; std::atomic comparedDecisionHookForTest{nullptr}; std::map comparedPages; template void eachPage(std::uint64_t address, std::size_t bytes, const Each& each) { const auto stop = address + bytes; for (auto page = address & ~std::uint64_t{WritePageBytes - 1}; page < stop; page += WritePageBytes) each(page); } std::vector> hashGuestPages(std::span pages) { std::vector> hashes(pages.size()); for (std::size_t from = 0; from < pages.size();) { auto to = from + 1; while (to < pages.size() && pages[to] == pages[to - 1] + WritePageBytes) ++to; const bool whole = Accessible(reinterpret_cast(static_cast(pages[from])), (to - from) * WritePageBytes); for (auto index = from; index < to; ++index) { const auto* pointer = reinterpret_cast(static_cast(pages[index])); if (whole || Accessible(pointer, WritePageBytes)) hashes[index] = HashPage(pointer); } from = to; } return hashes; } void compareLeavingPages(std::uint64_t address, std::size_t bytes) { if (!leftWatchCompare.load(std::memory_order_acquire)) return; std::vector fresh; { const std::lock_guard lock(comparedMutex); eachPage(address, bytes, [&](std::uint64_t page) { if (!comparedPages.contains(page)) fresh.push_back(page); }); } const auto hashes = hashGuestPages(fresh); const std::lock_guard lock(comparedMutex); for (std::size_t index = 0; index < fresh.size(); ++index) { if (hashes[index]) comparedPages.try_emplace(fresh[index], ComparedPage{*hashes[index], true}); } } void noteLeftWatch(std::uint64_t address, std::size_t bytes) { if (!leftWatchCompare.load(std::memory_order_acquire)) return; const std::lock_guard lock(comparedMutex); eachPage(address, bytes, [&](std::uint64_t page) { comparedPages.try_emplace(page); }); } std::atomic unwatchHook{nullptr}; thread_local bool unwatchWritesProven = true; std::atomic importWalkFailureForTest{0}; std::atomic importWalkFailureSpanForTest{0}; void beforeUnwatch(std::uint64_t address, std::size_t bytes) { compareLeavingPages(address, bytes); const auto hook = unwatchHook.load(std::memory_order_acquire); if (hook == nullptr) return; #ifdef _WIN32 std::uint64_t begin = 0; std::uint64_t end = 0; { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || !tracker.coverage.ExcludedSpan(address, bytes, &begin, &end)) return; } hook(begin, static_cast(end - begin)); #else hook(address, bytes); #endif } void beforeUnwatchUnproven(std::uint64_t address, std::size_t bytes) { struct Unproven { Unproven() { unwatchWritesProven = false; } ~Unproven() { unwatchWritesProven = true; } Unproven(const Unproven&) = delete; Unproven& operator=(const Unproven&) = delete; } unproven; beforeUnwatch(address, bytes); } void unwatchLocked(WriteTracker& tracker, std::uint64_t address, std::size_t bytes) { if (!tracker.watched) return; #ifdef _WIN32 tracker.startHints(address, bytes); if (tracker.coverage.Exclude(address, bytes, GuestArena::GuestArenaCommitGeneration_nid_postfix())) { unwatchSerial.fetch_add(1, std::memory_order_release); bumpSubscriptions(address, bytes, WriteBumpSource::Unwatch); noteLeftWatch(address, bytes); } if (bytes != 0 && (!tracker.rewatchStamps.empty() || !tracker.rewatchPages.empty())) { for (auto block = tracker.blockOf(address); block <= tracker.blockOf(address + bytes - 1); ++block) { tracker.rewatchStamps.erase(block); tracker.forgetRewatchedPages(block, address, address + bytes); } } #else if (GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(reinterpret_cast(address), bytes)) { unwatchSerial.fetch_add(1, std::memory_order_release); bumpSubscriptions(address, bytes, WriteBumpSource::Unwatch); noteLeftWatch(address, bytes); } #endif } thread_local bool ownHostWrite = false; std::atomic hostWritesInFlight{0}; std::atomic hostWritesStopped{false}; class HostWriteInFlight { public: HostWriteInFlight() { hostWritesInFlight.fetch_add(1, std::memory_order_seq_cst); } ~HostWriteInFlight() { hostWritesInFlight.fetch_sub(1, std::memory_order_seq_cst); } HostWriteInFlight(const HostWriteInFlight&) = delete; HostWriteInFlight& operator=(const HostWriteInFlight&) = delete; }; class OwnHostWrite { public: OwnHostWrite() : outer(std::exchange(ownHostWrite, true)) {} ~OwnHostWrite() { ownHostWrite = outer; } OwnHostWrite(const OwnHostWrite&) = delete; OwnHostWrite& operator=(const OwnHostWrite&) = delete; private: bool outer; }; } void SetUnwatchHook(void (*hook)(std::uint64_t, std::size_t)) { unwatchHook.store(hook, std::memory_order_release); } void SetLeftWatchCompare(bool compare) { leftWatchCompare.store(compare, std::memory_order_release); if (compare) return; const std::lock_guard lock(comparedMutex); comparedPages.clear(); } void SeedComparedPages(std::uint64_t address, std::span bytes) { if (!leftWatchCompare.load(std::memory_order_acquire)) return; const auto first = (address + WritePageBytes - 1) & ~std::uint64_t{WritePageBytes - 1}; const std::lock_guard lock(comparedMutex); for (auto page = first; page + WritePageBytes <= address + bytes.size(); page += WritePageBytes) comparedPages[page] = {HashPage(bytes.data() + (page - address)), true}; } void UpdateComparedPages(std::uint64_t address, std::span bytes) { const auto first = (address + WritePageBytes - 1) & ~std::uint64_t{WritePageBytes - 1}; const std::lock_guard lock(comparedMutex); for (auto found = comparedPages.lower_bound(first); found != comparedPages.end() && found->first + WritePageBytes <= address + bytes.size(); ++found) found->second = {HashPage(bytes.data() + (found->first - address)), true}; } void ChangedComparedPages(std::uint64_t address, std::size_t bytes, std::vector>& changed) { changed.clear(); if (bytes == 0 || bytes > std::numeric_limits::max() - address) return; const auto end = address + bytes; std::vector> pages; { const std::lock_guard lock(comparedMutex); for (auto found = comparedPages.lower_bound(address & ~std::uint64_t{WritePageBytes - 1}); found != comparedPages.end() && found->first < end; ++found) pages.push_back(*found); } std::vector addresses; for (const auto& [page, compared] : pages) addresses.push_back(page); const auto hashes = hashGuestPages(addresses); for (std::size_t index = 0; index < pages.size(); ++index) { const auto& [page, compared] = pages[index]; const auto& hash = hashes[index]; if (!hash || (compared.known && *hash == compared.hash)) continue; const auto begin = std::max(address, page); const auto stop = std::min(end, page + WritePageBytes); if (!changed.empty() && changed.back().second == begin) changed.back().second = stop; else changed.emplace_back(begin, stop); } if (pages.empty()) return; if (const auto hook = comparedDecisionHookForTest.load(std::memory_order_acquire)) hook(); auto& tracker = Tracker(); const auto trackerLock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched) return; const std::lock_guard lock(comparedMutex); for (const auto page : addresses) { if (tracker.covers(page, WritePageBytes)) comparedPages.erase(page); } } void SetComparedDecisionHookForTest(void (*hook)()) { comparedDecisionHookForTest.store(hook, std::memory_order_release); } bool UnwatchWritesProven() { return unwatchWritesProven; } void SetImportWalkFailureForTest(int walk, std::uint64_t span) { importWalkFailureSpanForTest.store(span, std::memory_order_release); importWalkFailureForTest.store(walk, std::memory_order_release); } #ifdef _WIN32 void SetFreshCollectHook(FreshCollectHook hook) { freshCollectHook.store(hook, std::memory_order_release); } #endif void Unwatch(std::uint64_t address, std::size_t bytes) { if (bytes == 0 || bytes > std::numeric_limits::max() - address) return; beforeUnwatch(address, bytes); auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); unwatchLocked(tracker, address, bytes); } void Rewatch(std::span> ranges) { #ifdef _WIN32 auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched) return; bool restored = false; for (const auto& [begin, end] : ranges) { if (end <= begin || begin < tracker.base || end - tracker.base > tracker.size || (begin - tracker.base) % WritePageBytes != 0 || (end - tracker.base) % WritePageBytes != 0) continue; const auto bytes = static_cast(end - begin); if (tracker.coverage.Covers(begin, bytes)) continue; GuestArena::GuestArenaCompareWhenShared_nid_no_patch(static_cast(begin), bytes); if (!walkWrites(tracker, begin, end, StampKind::Cpu) || !tracker.coverage.Restore(begin, bytes)) continue; ++tracker.generation; tracker.noteCpuStore(begin, end, tracker.generation); tracker.notePages(tracker.rewatchPages, begin, end, tracker.generation); for (auto block = tracker.blockOf(begin); block <= tracker.blockOf(end - 1); ++block) { if (const auto found = tracker.driverPieces.find(block); found != tracker.driverPieces.end()) found->second.dropped = std::max(found->second.dropped, tracker.generation); tracker.stamp(block, tracker.generation, StampKind::Cpu); tracker.rewatchStamps[block] = tracker.stampOf(block); tracker.anyRewatchStamp.store(true, std::memory_order_release); } restored = true; } if (restored) unwatchSerial.fetch_add(1, std::memory_order_release); #else static_cast(ranges); #endif } bool ImportWatched(std::uint64_t address, std::size_t bytes, const std::function& import, bool staysWatched, bool importMayWriteGuest) { if (bytes == 0 || bytes > std::numeric_limits::max() - address) return import(); if (!staysWatched) { constexpr std::uint64_t page = 4096; const auto first = address & ~(page - 1); beforeUnwatch(first, static_cast(((address + bytes + page - 1) & ~(page - 1)) - first)); } auto& tracker = Tracker(); auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched) { lock.Unlock(); return import(); } constexpr std::uint64_t page = 4096; const auto first = address & ~(page - 1); const auto stop = (address + bytes + page - 1) & ~(page - 1); const bool covered = tracker.covers(first, static_cast(stop - first)); const auto runImport = [&] { #if defined(__APPLE__) const OwnHostWrite own; std::optional open; if (importMayWriteGuest) open.emplace(reinterpret_cast(first), static_cast(stop - first)); #else static_cast(importMayWriteGuest); #endif return import(); }; if (!staysWatched) { const bool before = covered && walkWrites(tracker, first, stop, StampKind::Cpu, true); if (!runImport()) return false; bumpSubscriptions(first, stop - first, WriteBumpSource::Import); if (!before || !walkWrites(tracker, first, stop, StampKind::ImportWindow, true)) unwatchLocked(tracker, first, static_cast(stop - first)); unwatchLocked(tracker, address, bytes); return true; } std::vector> spans; if (covered) spans.emplace_back(first, stop); else { for (auto begin = first; begin < stop;) { const auto end = std::min((begin / WriteBlockBytes + 1) * WriteBlockBytes, stop); if (tracker.covers(begin, static_cast(end - begin))) { if (!spans.empty() && spans.back().second == begin) spans.back().second = end; else spans.emplace_back(begin, end); } begin = end; } } std::vector hashes(static_cast((stop - first) / page), 0); for (const auto& [begin, end] : spans) CheckRange(reinterpret_cast(begin), static_cast(end - begin), 1, false); std::vector unknown(hashes.size(), 0); HashPages(first, spans, hashes, unknown); const auto failWalk = importWalkFailureForTest.load(std::memory_order_acquire); const auto failSpan = importWalkFailureSpanForTest.load(std::memory_order_acquire); const auto failsWalk = [&](int walk, std::uint64_t begin, std::uint64_t end) { return failWalk == walk && (failSpan == 0 || (begin <= failSpan && failSpan < end)); }; const auto leave = [&](const std::vector>& ranges) { if (ranges.empty()) return; const TrackerLock::Suspension suspended{lock}; for (const auto& [begin, end] : ranges) beforeUnwatchUnproven(begin, static_cast(end - begin)); }; std::vector> leaving; std::erase_if(spans, [&](const auto& span) { if (!failsWalk(1, span.first, span.second) && walkWrites(tracker, span.first, span.second, StampKind::Cpu, true)) return false; leaving.push_back(span); return true; }); leave(leaving); if (!runImport()) return false; bumpSubscriptions(first, stop - first, WriteBumpSource::Import); const WindowCopy window{first, hashes, {}, StampKind::ImportWindow, unknown}; leaving.clear(); std::erase_if(spans, [&](const auto& span) { if (failsWalk(2, span.first, span.second) || !walkWrites(tracker, span.first, span.second, StampKind::Cpu, true, &window)) { leaving.push_back(span); return true; } #ifdef _WIN32 GuestArena::GuestArenaCompareResidentWhenShared_nid_no_patch(static_cast(span.first), static_cast(span.second - span.first)); #endif return false; }); leave(leaving); auto unwatchedFrom = first; for (const auto& [begin, end] : spans) { if (unwatchedFrom < begin) unwatchLocked(tracker, unwatchedFrom, static_cast(begin - unwatchedFrom)); unwatchedFrom = end; } if (unwatchedFrom < stop) unwatchLocked(tracker, unwatchedFrom, static_cast(stop - unwatchedFrom)); return true; } bool WriteWatched() { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); return tracker.watched; } bool OnlyRewatchedSince(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { if (bytes == 0 || bytes > std::numeric_limits::max() - address || generation == 0) return false; auto& tracker = Tracker(); if (!tracker.anyRewatchStamp.load(std::memory_order_acquire)) return false; const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || !tracker.covers(address, bytes)) return false; const auto end = address + bytes; if (tracker.newestUnstampedStamp(address, end) > generation) return false; bool rewatched = false; for (auto block = tracker.blockOf(address); block <= tracker.blockOf(end - 1); ++block) { const auto stamp = tracker.stampOf(block); if (stamp <= generation) continue; const auto found = tracker.rewatchStamps.find(block); if (found == tracker.rewatchStamps.end() || found->second != stamp) return false; rewatched = true; } return rewatched; } bool Rewatched(std::uint64_t address, std::size_t bytes) { if (bytes == 0 || bytes > std::numeric_limits::max() - address) return false; auto& tracker = Tracker(); if (!tracker.anyRewatchStamp.load(std::memory_order_acquire)) return false; const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || !tracker.covers(address, bytes)) return false; for (auto block = tracker.blockOf(address); block <= tracker.blockOf(address + bytes - 1); ++block) { if (tracker.rewatchStamps.contains(block)) return true; } return false; } void RewatchedBlocks(std::uint64_t address, std::size_t bytes, std::span since, std::span rewatched) { std::fill(rewatched.begin(), rewatched.end(), std::uint8_t{0}); if (bytes == 0 || bytes > std::numeric_limits::max() - address) return; auto& tracker = Tracker(); if (!tracker.anyRewatchStamp.load(std::memory_order_acquire)) return; const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched) return; const auto end = address + bytes; const auto first = tracker.blockOf(address); for (auto block = first; block <= tracker.blockOf(end - 1); ++block) { const auto k = static_cast(block - first); if (k >= since.size() || k >= rewatched.size()) break; const auto found = tracker.rewatchStamps.find(block); if (found == tracker.rewatchStamps.end()) continue; const auto begin = std::max(address, tracker.blockBegin(block)); const auto stop = std::min(end, tracker.blockBegin(block) + WriteBlockBytes); if (!tracker.covers(begin, static_cast(stop - begin))) continue; const auto stamp = tracker.stampOf(block); if (since[k] == 0 || (stamp > since[k] && stamp == found->second)) rewatched[k] = 1; } } bool Watched(std::uint64_t address, std::size_t bytes) { if (bytes == 0 || bytes > std::numeric_limits::max() - address) return false; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); return tracker.watched && bytes != 0 && bytes <= std::numeric_limits::max() - address && tracker.covers(address, bytes); } std::shared_ptr SubscribeWrites(std::span> ranges) { Pages().initialize(); auto* subscription = new WriteSubscription; std::vector> watched; constexpr std::uint64_t page = 4096; for (const auto& [begin, end] : ranges) { if (end <= begin) continue; for (auto block = begin / IndexBlockBytes; block <= (end - 1) / IndexBlockBytes; ++block) subscription->blocks.push_back(block); const auto first = begin & ~(page - 1); const auto stop = (end + page - 1) & ~(page - 1); if (Watched(first, static_cast(stop - first))) watched.emplace_back(first, stop); } std::sort(subscription->blocks.begin(), subscription->blocks.end()); subscription->blocks.erase(std::unique(subscription->blocks.begin(), subscription->blocks.end()), subscription->blocks.end()); std::sort(watched.begin(), watched.end()); for (const auto& range : watched) { auto& spans = subscription->spans; if (!spans.empty() && range.first <= spans.back().second + SpanGapBytes) { const auto end = std::max(spans.back().second, range.second); if (range.first <= spans.back().second || Watched(spans.back().first, static_cast(end - spans.back().first))) { spans.back().second = end; continue; } } spans.push_back(range); } auto& index = Index(); { std::lock_guard lock(index.mutex); for (const auto block : subscription->blocks) index.byBlock[block].push_back(subscription); index.live.fetch_add(1, std::memory_order_acq_rel); } index.subscriptions.fetch_add(1, std::memory_order_relaxed); index.blocks.fetch_add(subscription->blocks.size(), std::memory_order_relaxed); return std::shared_ptr(subscription, &releaseSubscription); } bool SweepSubscription(const WriteSubscription& subscription) { auto& index = Index(); index.sweeps.fetch_add(1, std::memory_order_relaxed); for (const auto& [begin, end] : subscription.spans) { if (CollectWrites(begin, static_cast(end - begin)) == 0) { index.sweepFailures.fetch_add(1, std::memory_order_relaxed); return false; } } return true; } bool UnchangedSince(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { if (bytes == 0 || bytes > std::numeric_limits::max() - address) return false; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || generation == 0 || bytes == 0 || !tracker.covers(address, bytes)) return false; return tracker.rangeUnchanged(address, bytes, generation); } bool UnchangedSinceAll(std::span queries) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched) return false; for (const auto& [address, bytes, generation] : queries) { if (generation == 0 || bytes == 0 || !tracker.covers(address, bytes)) return false; if (!tracker.rangeUnchanged(address, bytes, generation)) return false; } return true; } std::uint64_t CollectCommittedWrites(std::uint64_t address, std::size_t bytes, std::vector>& ranges) { ranges.clear(); if (bytes == 0 || bytes > std::numeric_limits::max() - address || !WriteWatched()) return 0; auto committed = CommittedRanges(address, bytes); auto generation = TrackerGeneration(); for (const auto& [begin, end] : committed) { generation = CollectWrites(begin, static_cast(end - begin)); if (generation == 0) return 0; } ranges = std::move(committed); return generation; } bool UnchangedCommittedSince(std::span> ranges, std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || generation == 0) return false; for (const auto& [begin, end] : ranges) { if (end <= begin || !tracker.covers(begin, static_cast(end - begin)) || tracker.newestStamp(begin, end) > generation || tracker.refusedSince(begin, end, generation)) return false; } return true; } static GuestAllocations::Lease::Ranges pinStoreRanges(std::uint64_t address, std::size_t bytes) { GuestAllocations::Lease::Ranges pinned; if (bytes > std::numeric_limits::max() - address) return pinned; const auto end = address + bytes; for (auto at = address; at < end;) { auto range = GuestAllocations::GuestAllocationsLookup_nid_postfix(at, true); if (range == nullptr || range->address >= end) break; at = range->address + range->bytes; pinned.push_back(std::move(range)); } return pinned; } struct BreakWhenStored { ~BreakWhenStored() { BreakProofs(); } }; static std::atomic ownStoreCompare{false}; void SetOwnStoreCompare(bool compare) { ownStoreCompare.store(compare, std::memory_order_release); } std::uint64_t storeOwn(std::uint64_t address, std::size_t bytes, bool imaged, const std::function(std::span)>& store, bool complete = true) { if (bytes == 0) return 0; const auto pinned = pinStoreRanges(address, bytes); BreakProofs(); const BreakWhenStored breakStored; const auto stampStored = [complete](WriteTracker& tracker, std::pair stored) -> std::uint64_t { if (stored.second <= stored.first) return 0; ++tracker.generation; if (!tracker.watched || !tracker.covers(stored.first, static_cast(stored.second - stored.first))) { tracker.noteUnstampedStore(stored.first, stored.second); if (tracker.watched) tracker.stampWatchedPart(stored.first, stored.second, tracker.generation, complete); return 0; } for (auto block = tracker.blockOf(stored.first); block <= tracker.blockOf(stored.second - 1); ++block) { tracker.stamp(block, tracker.generation, StampKind::Driver); tracker.noteDriverStore(block, stored.first, stored.second, tracker.generation, complete); } return tracker.generation; }; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || bytes > std::numeric_limits::max() - address || !tracker.covers(address, bytes)) return stampStored(tracker, store({})); constexpr std::uint64_t page = 4096; const auto first = address & ~(page - 1); const auto stop = (address + bytes + page - 1) & ~(page - 1); const bool compare = ownStoreCompare.load(std::memory_order_acquire); std::vector image; std::optional window; if (compare) { if (imaged) { image.resize(static_cast(stop - first)); static_cast(CopyMapped(first, image)); } window = WindowCopy{first, {}, image, StampKind::Driver}; } if (!walkWrites(tracker, first, stop, StampKind::Cpu)) return stampStored(tracker, store({})); const auto stored = store(image.empty() ? std::span{} : std::span(image).subspan(static_cast(address - first), bytes)); walkWrites(tracker, first, stop, StampKind::Driver, false, window ? &*window : nullptr); return stampStored(tracker, stored); } std::uint64_t StoreOwnBytes(std::uint64_t address, std::size_t bytes, const std::function& store) { return storeOwn(address, bytes, false, [&](std::span) { store(); return std::pair{address, address + bytes}; }); } std::uint64_t StoreOwnBytes(std::uint64_t address, std::size_t bytes, const std::function)>& store) { return storeOwn(address, bytes, true, [&](std::span image) { store(image); return std::pair{address, address + bytes}; }); } static void copyOwnBytes(std::uint64_t address, std::span source) { #ifndef _WIN32 if (GuestWriteWatch::GuestWriteWatchAvailable_nid_postfix() && GuestArena::GuestArenaWriteSharedBacking_nid_no_patch(address, source.data(), source.size())) return; #endif std::memcpy(reinterpret_cast(address), source.data(), source.size()); } std::uint64_t StoreOwnBytes(std::uint64_t address, std::span source) { return StoreOwnBytes(address, source.size(), [&](std::span image) { copyOwnBytes(address, source); if (!image.empty()) std::memcpy(image.data(), source.data(), source.size()); }); } static std::uint64_t markWritten(std::uint64_t address, std::size_t bytes, bool complete, std::uint64_t* order = nullptr) { BreakProofs(); const BreakWhenStored breakStored; auto& tracker = Tracker(); auto lock = lockTracker(tracker); if (order != nullptr) *order = 0; tracker.initialize(); if (bytes == 0) return 0; ++tracker.generation; if (!tracker.watched || !tracker.covers(address, bytes)) { tracker.noteUnstampedStore(address, address + bytes); if (tracker.watched) tracker.stampWatchedPart(address, address + bytes, tracker.generation, complete); if (order != nullptr) *order = tracker.generation.load(std::memory_order_relaxed); return 0; } { const auto blockFirst = address & ~(std::uint64_t{WriteBlockBytes} - 1); const auto blockStop = (address + bytes + WriteBlockBytes - 1) & ~(std::uint64_t{WriteBlockBytes} - 1); StampRuns runs{tracker, StampKind::Fresh}; #ifdef _WIN32 const bool collected = collectWindowsWrites(runs, blockFirst, blockStop, false); #else const bool collected = GuestWriteWatch::GuestWriteWatchCollectFresh_nid_postfix(static_cast(blockFirst), static_cast(blockStop - blockFirst), &stampWrittenRun, &runs); #endif if (!collected) { { const TrackerLock::Suspension suspended{lock}; beforeUnwatchUnproven(blockFirst, static_cast(blockStop - blockFirst)); } ++tracker.generation; unwatchLocked(tracker, blockFirst, static_cast(blockStop - blockFirst)); tracker.noteUnstampedStore(address, address + bytes); if (order != nullptr) *order = tracker.generation.load(std::memory_order_relaxed); return 0; } if (runs.stamped != 0) ++tracker.generation; } const auto first = tracker.blockOf(address); const auto last = tracker.blockOf(address + bytes - 1); for (auto block = first; block <= last; ++block) { tracker.stamp(block, tracker.generation, StampKind::Driver); tracker.noteDriverStore(block, address, address + bytes, tracker.generation, complete); } const auto generation = tracker.generation.load(std::memory_order_relaxed); if (order != nullptr) *order = generation; return generation; } std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes) { ForgetKnownZero(address, bytes); return markWritten(address, bytes, true); } std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes) { ForgetKnownZero(address, bytes); return markWritten(address, bytes, false); } std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes, std::uint64_t& order) { ForgetKnownZero(address, bytes); return markWritten(address, bytes, false, &order); } bool StoredOver(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || generation == 0 || bytes == 0 || !tracker.covers(address, bytes)) return true; #ifdef _WIN32 if (GuestArena::GuestArenaHostRegionOverlaps_nid_postfix(address, bytes)) return true; #endif return tracker.storedOver(address, address + bytes, generation, false, true); } bool DriverStoredOver(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || generation == 0 || bytes == 0 || !tracker.covers(address, bytes)) return true; return tracker.driverStoredOver(address, address + bytes, generation); } bool StoredAllSince_nid_no_patch(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { if (generation == 0 || bytes == 0 || bytes > std::numeric_limits::max() - address) return false; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || !tracker.covers(address, bytes)) return false; const auto end = address + bytes; if (!tracker.unstampedStores.empty()) { const auto first = address / WriteBlockBytes; const auto last = (end - 1u) / WriteBlockBytes; if (last - first >= WriteTracker::UnstampedSlots) { if (std::ranges::any_of(tracker.unstampedStores, [&](auto stamp) { return stamp > generation; })) return false; } else { for (auto block = first; block <= last; ++block) if (tracker.unstampedStores[block % WriteTracker::UnstampedSlots] > generation) return false; } } for (auto block = tracker.blockOf(address); block <= tracker.blockOf(end - 1u); ++block) { const auto found = tracker.driverPieces.find(block); if (found == tracker.driverPieces.end()) return false; const auto start = tracker.blockBegin(block); const auto from = static_cast(std::max(address, start) - start); const auto to = static_cast(std::min(end, start + WriteBlockBytes) - start); if (!found->second.covers(from, to, generation)) return false; } return true; } std::uint64_t TrackerGeneration() { auto& tracker = Tracker(); // Under the mutex: a collect bumps the generation before its walk, and a walk still running // when the value is read absorbs stores made after it with a stamp not newer than the value. const auto lock = lockTracker(tracker); return tracker.generation; } void AdvanceTrackerGenerationForTest(std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); if (generation > tracker.generation.load(std::memory_order_relaxed)) tracker.generation.store(generation, std::memory_order_relaxed); } std::uint64_t NewestStamp(std::uint64_t address, std::size_t bytes) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); return bytes == 0 ? 0 : tracker.newestStamp(address, address + bytes); } #ifdef _WIN32 namespace { thread_local ThreadCollectMemo threadHintMemo; bool walkHints(WriteTracker& tracker, std::uint64_t first, std::uint64_t stop) { auto cursor = first; bool marked = false; StampRuns runs{tracker, StampKind::Cpu}; while (cursor < stop) { std::size_t count = tracker.pages.size(); if (!GuestArena::GuestArenaCollectWrites_nid_postfix(static_cast(cursor), static_cast(stop - cursor), tracker.pages.data(), &count, true)) return false; if (count != 0 && !marked) ++tracker.generation; marked = marked || count != 0; for (std::size_t i = 0; i < count; ++i) { const auto page = reinterpret_cast(tracker.pages[i]); tracker.stampHint(tracker.blockOf(page)); if (tracker.coverage.Covers(page, WritePageBytes)) stampWrittenRun(&runs, page, page + WritePageBytes); } if (count < tracker.pages.size()) break; cursor = reinterpret_cast(tracker.pages[count - 1]) + WritePageBytes; } if (marked) collectDirty.fetch_add(1, std::memory_order_relaxed); return true; } } #endif std::uint64_t UntrackedHint(std::uint64_t address, std::size_t bytes) { #ifdef _WIN32 if (bytes == 0 || bytes > std::numeric_limits::max() - address) return 0; constexpr std::uint64_t page = 4096; const auto first = address & ~(page - 1); const auto stop = (address + bytes + page - 1) & ~(page - 1); const auto epoch = currentCollectEpoch(); auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || !tracker.hinted(first, stop)) return 0; const auto unwatched = unwatchSerial.load(std::memory_order_relaxed); const auto mapping = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); const bool memoized = collectMemoEnabled() && std::any_of(threadHintMemo.entries.begin(), threadHintMemo.entries.end(), [&](const WriteTracker::Memo& entry) { return entry.epoch == epoch && entry.unwatched == unwatched && entry.mapping == mapping && entry.begin <= first && stop <= entry.end; }); if (memoized) { collectMemoHits.fetch_add(1, std::memory_order_relaxed); } else { const TimedAccess timed(CounterCollect, bytes); if (!walkHints(tracker, first, stop)) return 0; if (collectMemoEnabled()) threadHintMemo.entries[threadHintMemo.next++ % threadHintMemo.entries.size()] = {first, stop, epoch, unwatched, mapping}; } return tracker.newestHint(first, stop); #else static_cast(address); static_cast(bytes); return 0; #endif } bool UnchangedSinceCollected(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { if (CollectWritesUncached(address, bytes) == 0) return false; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); if (!tracker.watched || generation == 0 || bytes == 0 || !tracker.covers(address, bytes)) return false; return tracker.cpuUnchanged(address, bytes, generation); } bool CpuWroteSince(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { if (generation == 0 || bytes == 0 || CollectWritesUncached(address, bytes) == 0) return false; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); return tracker.watched && tracker.covers(address, bytes) && !tracker.cpuUnchanged(address, bytes, generation); } bool UnchangedSinceLastCollect(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { if (bytes == 0u || bytes > std::numeric_limits::max() - address) return false; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || generation == 0u || !tracker.covers(address, bytes)) return false; return tracker.cpuUnchanged(address, bytes, generation) && tracker.rangeUnchanged(address, bytes, generation, false); } bool StoreUnchangedSinceLastCollect(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { if (bytes == 0u || bytes > std::numeric_limits::max() - address) return false; auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || generation == 0u || !tracker.covers(address, bytes)) return false; return tracker.cpuStoreUnchanged(address, bytes, generation) && tracker.rangeUnchanged(address, bytes, generation, false, true); } bool WrittenSince(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || generation == 0 || bytes == 0 || !tracker.covers(address, bytes)) return false; const auto first = tracker.blockOf(address); const auto last = tracker.blockOf(address + bytes - 1); for (auto block = first; block <= last; ++block) { if (tracker.stampOf(block) > generation) return true; } return false; } bool ChangedBlocks(std::uint64_t address, std::size_t bytes, std::span generations, std::span changed, std::span cpu) { std::fill(changed.begin(), changed.end(), BlockWritten); std::fill(cpu.begin(), cpu.end(), std::uint8_t{1}); auto& tracker = Tracker(); const auto lock = lockTracker(tracker); tracker.initialize(); if (!tracker.watched || bytes == 0 || !tracker.covers(address, bytes)) return false; const auto first = tracker.blockOf(address); const auto last = tracker.blockOf(address + bytes - 1); for (auto block = first; block <= last; ++block) { const auto k = block - first; if (k >= generations.size() || k >= changed.size()) break; const auto generation = generations[k]; changed[k] = generation == 0 || tracker.stampOf(block) > generation ? BlockWritten : BlockUnchanged; if (k < cpu.size()) cpu[k] = generation == 0 || tracker.cpuStampOf(block) > generation ? 1 : 0; } return true; } namespace { // Per-thread GpuMutex wait accounting (APS5_PROFILE_DRAW): a queue worker tags its thread, other // threads (the presenter) report untagged. constexpr std::size_t GpuLockSiteCount = static_cast(GpuLockSite::Count); constexpr const char* GpuLockSiteNames[GpuLockSiteCount] = {"other", "dispatch", "indirect", "draw", "hook", "wait", "label", "flush", "present", "fill", "copy", "end", "try"}; // Hold-side holder matrix: nanoseconds held per (holder thread, site), added by EndHold. Column 0 // is every untagged thread (the presenter, game threads); the queue workers take a column each on // their first hold. A contended lock() snapshots the matrix before and after its wait and credits // the deltas (the holds that ended during the wait) to the waiter's site. constexpr std::size_t HolderColumns = 12; constexpr std::uint32_t UnassignedHolder = 0xfffffffeu; constexpr std::uint32_t PresenterHolderTag = 0xfffffffdu; constexpr int PresenterColumn = 1; using HolderMatrixValues = std::array, HolderColumns>; struct HolderMatrix { std::array, HolderColumns> tags{}; std::array, GpuLockSiteCount>, HolderColumns> heldNs{}; HolderMatrix() { for (auto& tag : tags) tag.store(UnassignedHolder, std::memory_order_relaxed); tags[0].store(0xffffffffu, std::memory_order_relaxed); tags[PresenterColumn].store(PresenterHolderTag, std::memory_order_relaxed); } void Snapshot(HolderMatrixValues& into) const { for (std::size_t h = 0; h < HolderColumns; ++h) { for (std::size_t s = 0; s < GpuLockSiteCount; ++s) into[h][s] = heldNs[h][s].load(std::memory_order_relaxed); } } }; HolderMatrix& Holders() { static HolderMatrix matrix; return matrix; } std::size_t HolderColumnFor(std::uint32_t tag) { if (tag == 0xffffffffu) return 0; auto& holders = Holders(); for (std::size_t i = 1; i < HolderColumns; ++i) { auto expected = UnassignedHolder; if (holders.tags[i].load(std::memory_order_acquire) == tag) return i; if (holders.tags[i].compare_exchange_strong(expected, tag, std::memory_order_acq_rel)) return i; if (expected == tag) return i; } return 0; } struct GpuLockStats { std::uint32_t tag = 0xffffffffu; std::uint64_t acquisitions = 0; std::uint64_t waits = 0; double waitedMs = 0; // The same split by the site tagged before the acquisition (TagGpuLockSite); the tag of the // next lock() is kept here and consumed by it. std::array siteAcquisitions{}; std::array siteWaits{}; std::array siteWaitedMs{}; GpuLockSite nextSite = GpuLockSite::Other; // Holds: the outermost (depth 0 -> 1) acquisition of this thread until the matching unlock, // charged to that acquisition's site (a nested hook lock inside a dispatch's hold extends the // dispatch's hold). The waits above say who waits; these say whom they wait for. std::array siteHolds{}; std::array siteHeldMs{}; std::array siteMaxHeldMs{}; std::size_t holdSite = 0; std::chrono::steady_clock::time_point holdStart; // This thread's column of the holder matrix (-1 until its first hold), and what its contended // acquisitions waited behind: holds by (holder, site) that ended during the waits. int holderColumn = -1; HolderMatrixValues waitedBehindNs{}; std::uint64_t tries = 0; std::uint64_t triesFailed = 0; std::uint64_t lockedGpuWaits = 0; double lockedGpuWaitMs = 0; std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now(); }; GpuLockStats& LockStats() { thread_local GpuLockStats stats; return stats; } bool GpuLockProfiled() { static const bool profiled = std::getenv("APS5_PROFILE_DRAW") != nullptr && std::getenv("APS5_NO_LOCK_PROFILE") == nullptr; return profiled; } // Hold timing costs two clock reads per outermost acquisition (~20000 per 10 s on queue 0, well // under a millisecond); APS5_NO_HOLD_PROFILE=1 keeps only the wait timing. bool GpuHoldProfiled() { static const bool profiled = GpuLockProfiled() && std::getenv("APS5_NO_HOLD_PROFILE") == nullptr; return profiled; } void BeginHold(std::size_t site) { auto& stats = LockStats(); stats.holdSite = site; stats.holdStart = std::chrono::steady_clock::now(); } void EndHold() { auto& stats = LockStats(); const auto heldNs = std::chrono::duration_cast(std::chrono::steady_clock::now() - stats.holdStart).count(); const auto heldMs = static_cast(heldNs) / 1e6; ++stats.siteHolds[stats.holdSite]; stats.siteHeldMs[stats.holdSite] += heldMs; stats.siteMaxHeldMs[stats.holdSite] = std::max(stats.siteMaxHeldMs[stats.holdSite], heldMs); if (stats.holderColumn < 0) stats.holderColumn = static_cast(HolderColumnFor(stats.tag)); Holders().heldNs[static_cast(stats.holderColumn)][stats.holdSite].fetch_add(static_cast(heldNs), std::memory_order_relaxed); } const char* HolderName(std::size_t column, char* text, std::size_t size) { const auto tag = Holders().tags[column].load(std::memory_order_relaxed); if (tag == 0xffffffffu) std::snprintf(text, size, "untagged"); else if (tag == PresenterHolderTag) std::snprintf(text, size, "presenter"); else std::snprintf(text, size, "q0x%x", tag); return text; } // The waiter's matrix as text, largest first, entries of at least a millisecond. std::string WaitedBehindReport(const HolderMatrixValues& waited) { std::vector> entries; for (std::size_t h = 0; h < HolderColumns; ++h) { for (std::size_t s = 0; s < GpuLockSiteCount; ++s) { if (waited[h][s] >= 1000000) entries.emplace_back(waited[h][s], h, s); } } std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { return std::get<0>(a) > std::get<0>(b); }); std::string report; char text[96]; char holder[24]; for (std::size_t i = 0; i < entries.size() && i < 16; ++i) { const auto& [ns, h, s] = entries[i]; std::snprintf(text, sizeof(text), " %s/%s %.0f", HolderName(h, holder, sizeof(holder)), GpuLockSiteNames[s], static_cast(ns) / 1e6); report += text; } return report; } } namespace { std::atomic gpuHoldSerial{0}; } void GpuMutexType::enter() { if (HeldByThisThread() || mutex.try_lock()) return; block(); } void GpuMutexType::block() { waiters.fetch_add(1, std::memory_order_relaxed); LockSpinning(mutex, HandoffSpinWindow()); waiters.fetch_sub(1, std::memory_order_relaxed); } bool GpuMutexType::tryEnter() { return HeldByThisThread() || mutex.try_lock(); } void GpuMutexType::acquired() { owner.store(CurrentThreadToken(), std::memory_order_relaxed); if (++depth == 1) { gpuHoldSerial.fetch_add(1, std::memory_order_relaxed); if (!proofThread) BreakProofs(); } } bool GpuMutexType::try_lock() { if (!GpuLockProfiled()) { if (!tryEnter()) return false; acquired(); return true; } // The tag is consumed whether or not the try succeeds (a failed try must not name the next // acquisition); an untagged try's hold is charged to 'try' (a boundary reap, an idle worker). auto& stats = LockStats(); const auto tagged = std::exchange(stats.nextSite, GpuLockSite::Other); ++stats.tries; if (!tryEnter()) { ++stats.triesFailed; return false; } acquired(); if (depth == 1 && GpuHoldProfiled()) BeginHold(static_cast(tagged == GpuLockSite::Other ? GpuLockSite::Try : tagged)); return true; } namespace { std::atomic gpuUnlockHook{nullptr}; } void SetGpuUnlockHook(void (*hook)()) { gpuUnlockHook.store(hook, std::memory_order_release); } std::uint64_t GpuHoldSerial() { return gpuHoldSerial.load(std::memory_order_relaxed); } void GpuMutexType::unlock() { const bool outermost = --depth == 0; if (outermost) { owner.store(nullptr, std::memory_order_relaxed); // Still the holder here: the hold ends when the mutex is given up, not before. if (GpuHoldProfiled()) EndHold(); mutex.unlock(); } // After the release, so what the hook does (destroying a batch's kept objects) is neither part // of the hold nor waited for by the next holder. if (outermost) { if (auto* hook = gpuUnlockHook.load(std::memory_order_acquire); hook != nullptr) hook(); } } bool GpuMutexType::HeldByThisThread() const { return owner.load(std::memory_order_relaxed) == CurrentThreadToken(); } std::uint32_t GpuMutexType::DepthOnThisThread() const { // `depth` is written by the holder only, so it is read only when that is this thread. return HeldByThisThread() ? depth : 0; } void AssertGpuLockHeld(const char* where) { static const bool enabled = std::getenv("APS5_ASSERT_GPU_LOCK") != nullptr; if (!enabled || GpuMutex().HeldByThisThread()) return; std::fprintf(stderr, "[lock] ASSERT: %s reached without GuestMemory::GpuMutex on thread tagged 0x%x\n", where, GpuLockThreadTag()); std::abort(); } void GpuMutexType::lock() { if (!GpuLockProfiled()) { auto* trace = PerformanceTrace::Recording() ? PerformanceTrace::Thread() : nullptr; if (trace == nullptr) { enter(); } else { const auto site = static_cast(std::exchange(LockStats().nextSite, GpuLockSite::Other)); if (!tryEnter()) { const auto start = std::chrono::steady_clock::now(); block(); trace->Add("GpuMutex.wait", GpuLockSiteNames[site], start, std::chrono::steady_clock::now()); } } acquired(); return; } auto& stats = LockStats(); ++stats.acquisitions; const auto site = static_cast(std::exchange(stats.nextSite, GpuLockSite::Other)); ++stats.siteAcquisitions[site]; // An uncontended (or recursive) acquisition costs no clock reads for the wait; only a wait is // timed. The hold timer (outermost acquisitions only) starts once the mutex is held. if (!tryEnter()) { const bool holders = GpuHoldProfiled(); HolderMatrixValues before{}; if (holders) Holders().Snapshot(before); const auto start = std::chrono::steady_clock::now(); block(); acquired(); const auto now = std::chrono::steady_clock::now(); if (auto* trace = PerformanceTrace::Recording() ? PerformanceTrace::Thread() : nullptr) trace->Add("GpuMutex.wait", GpuLockSiteNames[site], start, now); if (holders) { HolderMatrixValues after{}; Holders().Snapshot(after); for (std::size_t h = 0; h < HolderColumns; ++h) { for (std::size_t s = 0; s < GpuLockSiteCount; ++s) stats.waitedBehindNs[h][s] += after[h][s] - before[h][s]; } } if (depth == 1 && holders) { stats.holdSite = site; stats.holdStart = now; } const auto waitedMs = std::chrono::duration(now - start).count(); stats.waitedMs += waitedMs; ++stats.waits; stats.siteWaitedMs[site] += waitedMs; ++stats.siteWaits[site]; if (now - stats.lastReport < std::chrono::seconds(10)) return; // The line is printed from inside a contended acquisition, so a thread that rarely waits // reports a longer span than 10 s: the real interval is printed. const auto interval = std::chrono::duration(now - stats.lastReport).count(); stats.lastReport = now; std::string sites; for (std::size_t i = 0; i < GpuLockSiteCount; ++i) { if (stats.siteAcquisitions[i] == 0) continue; char text[96]; std::snprintf(text, sizeof(text), " %s %llu/%llu %.0f ms", GpuLockSiteNames[i], static_cast(stats.siteAcquisitions[i]), static_cast(stats.siteWaits[i]), stats.siteWaitedMs[i]); sites += text; } // Holds by site, longest total first: the sites whose holds the other threads wait behind. std::string holds; if (GpuHoldProfiled()) { std::array order{}; for (std::size_t i = 0; i < GpuLockSiteCount; ++i) order[i] = i; std::sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) { return stats.siteHeldMs[a] > stats.siteHeldMs[b]; }); double heldMs = 0; for (std::size_t i = 0; i < GpuLockSiteCount; ++i) heldMs += stats.siteHeldMs[i]; char text[112]; std::snprintf(text, sizeof(text), "; held %.0f ms in total, by site (holds, held, max):", heldMs); holds += text; for (const auto i : order) { if (stats.siteHolds[i] == 0) continue; std::snprintf(text, sizeof(text), " %s %llu %.0f ms (max %.1f)", GpuLockSiteNames[i], static_cast(stats.siteHolds[i]), stats.siteHeldMs[i], stats.siteMaxHeldMs[i]); holds += text; } holds += "; waited behind (holder/site ms):" + WaitedBehindReport(stats.waitedBehindNs); } char counts[160]; std::snprintf(counts, sizeof(counts), "; lock() %llu / try %llu / try failed %llu; locked GPU waits %llu / %.0f ms", static_cast(stats.acquisitions), static_cast(stats.tries), static_cast(stats.triesFailed), static_cast(stats.lockedGpuWaits), stats.lockedGpuWaitMs); holds += counts; if (stats.tag == 0xffffffffu) AgcDriver::ProfilePrint_nid_no_patch("[lock] %s waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.holderColumn == PresenterColumn ? "presenter" : "untagged thread", stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); else AgcDriver::ProfilePrint_nid_no_patch("[lock] queue 0x%x waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.tag, stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); stats.waitedMs = 0; stats.waits = 0; stats.acquisitions = 0; stats.siteAcquisitions.fill(0); stats.siteWaits.fill(0); stats.siteWaitedMs.fill(0); stats.siteHolds.fill(0); stats.siteHeldMs.fill(0); stats.siteMaxHeldMs.fill(0); for (auto& row : stats.waitedBehindNs) row.fill(0); stats.tries = 0; stats.triesFailed = 0; stats.lockedGpuWaits = 0; stats.lockedGpuWaitMs = 0; return; } acquired(); if (depth == 1 && GpuHoldProfiled()) BeginHold(site); } void TagGpuLockSite(GpuLockSite site) { // Off the profiled path the tag is never read, so the thread-local is not touched either. if (!GpuLockProfiled() && !PerformanceTrace::Recording()) return; LockStats().nextSite = site; } void MarkPresenterThread() { LockStats().holderColumn = PresenterColumn; } void NoteLockedGpuWait(double ms) { if (!GpuLockProfiled() || GpuMutex().DepthOnThisThread() == 0) return; auto& stats = LockStats(); ++stats.lockedGpuWaits; stats.lockedGpuWaitMs += ms; } std::uint64_t ThreadCollectedBytes() { if (!MemoryProfiled()) return 0; return CounterFor(CounterCollect).bytes.load(std::memory_order_relaxed); } std::uint32_t GpuLockThreadTag() { return LockStats().tag; } GpuMutexType& GpuMutex() { #ifdef __APPLE__ static auto* mutex = new GpuMutexType; return *mutex; #else static GpuMutexType mutex; return mutex; #endif } std::function YieldToGpuMutexWaiters(std::function stop) { return [stop = std::move(stop), first = true]() mutable { if (stop()) return true; if (first) { first = false; return false; } return GpuMutex().Waiters() != 0; }; } void TagGpuLockThread(std::uint32_t queue) { LockStats().tag = queue; } unsigned long long CodeOffset(const void* address) { return ModuleOffset(address); } namespace { std::atomic flushHook{nullptr}; std::atomic readGuard{nullptr}; void PrepareHostRead(std::uintptr_t address, std::size_t bytes) { if (const auto guard = readGuard.load(std::memory_order_acquire)) guard(address, bytes); FlushGpuWrites(address, bytes); } } void SetFlushHook(void (*hook)(std::uint64_t, std::size_t)) { flushHook.store(hook, std::memory_order_release); GuestArena::GuestArenaSetHostReadHook_nid_no_patch(&PrepareHostRead); } auto CurrentFlushHook() -> void (*)(std::uint64_t, std::size_t) { return flushHook.load(std::memory_order_acquire); } void SetReadGuard(void (*guard)(std::uint64_t address, std::size_t bytes)) { readGuard.store(guard, std::memory_order_release); GuestArena::GuestArenaSetHostReadHook_nid_no_patch(&PrepareHostRead); } void GuardRead(std::uint64_t address, std::size_t bytes) { if (const auto guard = readGuard.load(std::memory_order_acquire)) guard(address, bytes); } void ForgetKnownZero(std::uint64_t address, std::size_t bytes) { #ifdef _WIN32 GuestArena::GuestArenaForgetKnownZero_nid_no_patch(static_cast(address), bytes); #else static_cast(address); static_cast(bytes); #endif } std::uint64_t KnownZeroMarks() { #ifdef _WIN32 return GuestArena::GuestArenaKnownZeroMarks_nid_no_patch(); #else return 0; #endif } void MaterializeKnownZero(std::uint64_t address, std::size_t bytes) { #ifdef _WIN32 GuestArena::GuestArenaKnownZero_nid_no_patch(static_cast(address), bytes, [](void*, std::uintptr_t first, std::uintptr_t last) { for (auto page = first; page < last; page += 4096) static_cast(*reinterpret_cast(page)); }, nullptr); #else static_cast(address); static_cast(bytes); #endif } void FlushGpuWrites(std::uint64_t address, std::size_t bytes) { if (const auto hook = flushHook.load(std::memory_order_acquire)) hook(address, bytes); } namespace { std::atomic lockedHostWrites{0}; std::atomic lockedHostWriteLogged{false}; void noteLockedHostWrite(std::uintptr_t address, std::size_t bytes) { static const bool assertLock = std::getenv("APS5_ASSERT_GPU_LOCK") != nullptr; if (assertLock) { std::fprintf(stderr, "[lock] ASSERT: a host write of 0x%zx bytes at 0x%llx was made under GuestMemory::GpuMutex on thread tagged 0x%x\n", bytes, static_cast(address), GpuLockThreadTag()); std::abort(); } lockedHostWrites.fetch_add(1, std::memory_order_relaxed); if (!lockedHostWriteLogged.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, "[lock] a host write of 0x%zx bytes at 0x%llx was made under GuestMemory::GpuMutex on thread tagged 0x%x; it waits for GPU work with the mutex held (counted, logged once)\n", bytes, static_cast(address), GpuLockThreadTag()); } std::atomic waitedMsProvider{nullptr}; double threadWaitedMs() { const auto provider = waitedMsProvider.load(std::memory_order_acquire); return provider != nullptr ? provider() : 0.0; } struct HostWriteTotals { std::atomic calls{0}; std::atomic waited{0}; std::atomic waitedNanoseconds{0}; std::atomic maxWaitedNanoseconds{0}; std::atomic lastReport{0}; }; HostWriteTotals& HostWrites() { static HostWriteTotals totals; return totals; } void noteHostWriteWait(double waitedMs) { auto& totals = HostWrites(); totals.calls.fetch_add(1, std::memory_order_relaxed); if (waitedMs > 0) { const auto nanoseconds = static_cast(waitedMs * 1e6); totals.waited.fetch_add(1, std::memory_order_relaxed); totals.waitedNanoseconds.fetch_add(nanoseconds, std::memory_order_relaxed); auto most = totals.maxWaitedNanoseconds.load(std::memory_order_relaxed); while (nanoseconds > most && !totals.maxWaitedNanoseconds.compare_exchange_weak(most, nanoseconds, std::memory_order_relaxed)) { } } const auto nowMs = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); auto last = totals.lastReport.load(std::memory_order_relaxed); if (nowMs - last < 10000 || !totals.lastReport.compare_exchange_strong(last, nowMs)) return; AgcDriver::ProfilePrint_nid_no_patch("%s", HostWriteReport().c_str()); } } std::uint64_t LockedHostWrites() { return lockedHostWrites.load(std::memory_order_relaxed); } void SetWaitedMsProvider(double (*provider)()) { waitedMsProvider.store(provider, std::memory_order_release); } HostWriteCounts HostWritesCounted() { const auto& totals = HostWrites(); return {totals.calls.load(std::memory_order_relaxed), totals.waited.load(std::memory_order_relaxed), totals.waitedNanoseconds.load(std::memory_order_relaxed) / 1e6, totals.maxWaitedNanoseconds.load(std::memory_order_relaxed) / 1e6}; } std::string HostWriteReport() { const auto counts = HostWritesCounted(); char line[256]; std::snprintf(line, sizeof(line), "[hostwrite] %llu host writes, %llu waited for GPU work over their range: %.2f ms in total, %.2f ms at most\n", static_cast(counts.calls), static_cast(counts.waited), counts.waitedMs, counts.maxWaitedMs); return line; } void PrepareHostWrite(std::uintptr_t address, std::size_t bytes) { if (ownHostWrite || bytes == 0) return; if (GpuMutex().HeldByThisThread()) noteLockedHostWrite(address, bytes); const HostWriteInFlight inFlight; if (hostWritesStopped.load(std::memory_order_seq_cst)) return; const ReadSiteScope site(ReadSite::HostWrite); if (!MemoryProfiled()) { FlushGpuWrites(address, bytes); return; } const auto waitedBefore = threadWaitedMs(); FlushGpuWrites(address, bytes); noteHostWriteWait(threadWaitedMs() - waitedBefore); } bool StopHostWrites(std::uint32_t boundMs) { hostWritesStopped.store(true, std::memory_order_seq_cst); const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(boundMs); while (hostWritesInFlight.load(std::memory_order_seq_cst) != 0) { if (std::chrono::steady_clock::now() >= deadline) return false; std::this_thread::sleep_for(std::chrono::milliseconds(1)); } return true; } void Read(std::uint64_t address, std::span destination, std::size_t alignment) { if (destination.empty()) return; GuardRead(address, destination.size()); FlushGpuWrites(address, destination.size()); const TimedAccess timed(CounterRead, destination.size()); CountReadCaller(__builtin_return_address(0)); const auto* source = reinterpret_cast(address); try { CheckRange(source, destination.size(), alignment); } catch (const std::runtime_error&) { static const bool trace = std::getenv("APS5_TRACE_UNREADABLE") != nullptr; if (trace) std::fprintf(stderr, "[unreadable] read from +0x%llx\n", ModuleOffset(__builtin_return_address(0))); throw; } CopyGuestBytes(destination.data(), source, destination.size()); } std::uint64_t ReadLabel(std::uint64_t address, std::size_t bytes) { if (bytes != sizeof(std::uint32_t) && bytes != sizeof(std::uint64_t)) throw std::invalid_argument("a guest label is 4 or 8 bytes"); GuardRead(address, bytes); FlushGpuWrites(address, bytes); const TimedAccess timed(CounterRead, bytes); CountReadCaller(__builtin_return_address(0)); CheckRange(reinterpret_cast(address), bytes, bytes); if (bytes == sizeof(std::uint64_t)) return std::atomic_ref(*reinterpret_cast(address)).load(std::memory_order_acquire); return std::atomic_ref(*reinterpret_cast(address)).load(std::memory_order_acquire); } #ifdef ANYPS5_ENABLE_ASAN [[gnu::no_sanitize_address]] void CopyGuestBytes(void* destination, const void* source, std::size_t bytes) { using UnalignedWord [[gnu::aligned(1), gnu::may_alias]] = std::uint64_t; auto* to = static_cast(destination); const auto* from = static_cast(source); std::size_t index = 0; for (; index + sizeof(std::uint64_t) <= bytes; index += sizeof(std::uint64_t)) { const std::uint64_t word = *reinterpret_cast(from + index); std::memcpy(to + index, &word, sizeof(word)); } for (; index < bytes; ++index) to[index] = static_cast(from)[index]; } #else void CopyGuestBytes(void* destination, const void* source, std::size_t bytes) { std::memcpy(destination, source, bytes); } #endif namespace { #ifdef _WIN32 bool readPages(std::byte* destination, std::uint64_t source, std::size_t bytes) { SIZE_T copied = 0; if (ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(source), destination, bytes, &copied) != 0) { require(copied == bytes, "short committed guest memory read"); return true; } const auto error = GetLastError(); require(error == ERROR_PARTIAL_COPY || error == ERROR_NOACCESS || error == ERROR_INVALID_ADDRESS, "cannot read committed guest memory"); return false; } template void visitReadablePages(std::byte* destination, std::uint64_t source, std::size_t bytes, Visit&& visit) { if (readPages(destination, source, bytes)) { visit(std::size_t{0}, bytes, true); return; } ForgetPages(static_cast(source), bytes); for (std::size_t offset = 0; offset < bytes;) { const auto cursor = source + offset; const auto chunk = std::min(bytes - offset, PageBytes - static_cast(cursor % PageBytes)); MEMORY_BASIC_INFORMATION memory{}; require(VirtualQuery(reinterpret_cast(cursor), &memory, sizeof(memory)) == sizeof(memory), "cannot query guest memory after a failed committed read"); const bool readable = memory.State == MEM_COMMIT && (memory.Protect & (PAGE_GUARD | PAGE_NOACCESS)) == 0 && readableProtection(memory.Protect & 0xffu); visit(offset, chunk, readable && readPages(destination + offset, cursor, chunk)); offset += chunk; } } #endif void copyCommittedBytes(std::byte* destination, std::uint64_t source, std::size_t bytes) { #ifdef _WIN32 if (GuestArena::GuestArenaCopyOwned_nid_no_patch(source, destination, bytes)) return; visitReadablePages(destination, source, bytes, [&](std::size_t offset, std::size_t count, bool read) { if (!read) std::memset(destination + offset, 0, count); }); #else std::memcpy(destination, reinterpret_cast(source), bytes); #endif } bool equalsCommittedBytes(std::uint64_t address, const std::byte* expected, std::size_t bytes) { #ifdef _WIN32 bool same = false; if (GuestArena::GuestArenaCompareOwned_nid_no_patch(address, expected, bytes, &same)) return same; constexpr std::size_t ChunkBytes = 64 * PageBytes; struct CompareChunkStorage {}; auto& current = HostThreadLocal, CompareChunkStorage>(); if (current.size() < ChunkBytes) current.resize(ChunkBytes); for (std::size_t done = 0; done < bytes; done += ChunkBytes) { const auto count = std::min(ChunkBytes, bytes - done); bool equal = true; visitReadablePages(current.data(), address + done, count, [&](std::size_t offset, std::size_t length, bool read) { if (read && equal && std::memcmp(current.data() + offset, expected + done + offset, length) != 0) equal = false; }); if (!equal) return false; } return true; #else return std::memcmp(reinterpret_cast(address), expected, bytes) == 0; #endif } static_assert(PageBytes % DigestPageBytes == 0, "a guest page holds whole digest pages"); bool equalsCommittedDigestBytes(std::uint64_t address, std::size_t bytes, std::uint64_t base, std::span digests) { const auto firstPage = base / DigestPageBytes; const auto differs = [&](const std::byte* data, std::uint64_t from, std::size_t length) { for (std::size_t at = 0; at < length;) { const auto cursor = from + at; const auto count = std::min(length - at, DigestPageBytes - static_cast(cursor % DigestPageBytes)); if (PageDigest(data + at, count) != digests[static_cast(cursor / DigestPageBytes - firstPage)]) return true; at += count; } return false; }; #ifdef _WIN32 constexpr std::size_t ChunkBytes = 64 * PageBytes; struct DigestChunkStorage {}; auto& current = HostThreadLocal, DigestChunkStorage>(); if (current.size() < ChunkBytes) current.resize(ChunkBytes); for (std::size_t done = 0; done < bytes;) { const auto cursor = address + done; const auto count = std::min(bytes - done, ChunkBytes - static_cast(cursor % PageBytes)); bool equal = true; if (GuestArena::GuestArenaCopyOwned_nid_no_patch(static_cast(cursor), current.data(), count)) { equal = !differs(current.data(), cursor, count); } else { visitReadablePages(current.data(), cursor, count, [&](std::size_t offset, std::size_t length, bool read) { if (read && equal && differs(current.data() + offset, cursor + offset, length)) equal = false; }); } if (!equal) return false; done += count; } return true; #else return !differs(reinterpret_cast(address), address, bytes); #endif } void copyCommitted(std::uint64_t address, std::span destination) { if (Accessible(reinterpret_cast(address), destination.size())) { copyCommittedBytes(destination.data(), address, destination.size()); return; } std::memset(destination.data(), 0, destination.size()); for (const auto& [begin, end] : CommittedRanges(address, destination.size())) copyCommittedBytes(destination.data() + (begin - address), begin, static_cast(end - begin)); } } void ReadCommitted(std::uint64_t address, std::span destination) { if (destination.empty()) return; GuardRead(address, destination.size()); FlushGpuWrites(address, destination.size()); const TimedAccess timed(CounterRead, destination.size()); CountReadCaller(__builtin_return_address(0)); copyCommitted(address, destination); } void ReadCommittedUnsynced(std::uint64_t address, std::span destination) { if (destination.empty()) return; GuardRead(address, destination.size()); const TimedAccess timed(CounterRead, destination.size()); CountReadCaller(__builtin_return_address(0)); copyCommitted(address, destination); } bool EqualsCommitted(std::uint64_t address, std::span bytes) { if (bytes.empty()) return true; FlushGpuWrites(address, bytes.size()); return EqualsCommittedUnsynced(address, bytes); } bool EqualsCommittedUnsynced(std::uint64_t address, std::span bytes) { if (bytes.empty()) return true; const TimedAccess timed(CounterCompare, bytes.size()); if (Accessible(reinterpret_cast(address), bytes.size())) return equalsCommittedBytes(address, bytes.data(), bytes.size()); for (const auto& [begin, end] : CommittedRanges(address, bytes.size())) { if (!equalsCommittedBytes(begin, bytes.data() + (begin - address), static_cast(end - begin))) return false; } return true; } void PageDigests(std::uint64_t address, std::span bytes, std::vector& digests) { digests.clear(); digests.reserve(DigestPages(address, bytes.size())); for (std::size_t at = 0; at < bytes.size();) { const auto count = std::min(bytes.size() - at, DigestPageBytes - static_cast((address + at) % DigestPageBytes)); digests.push_back(PageDigest(bytes.data() + at, count)); at += count; } } bool EqualsCommittedDigests(std::uint64_t address, std::size_t bytes, std::span digests) { if (bytes == 0) return true; FlushGpuWrites(address, bytes); return EqualsCommittedDigestsUnsynced(address, bytes, digests); } bool EqualsCommittedDigestsUnsynced(std::uint64_t address, std::size_t bytes, std::span digests) { if (bytes == 0) return true; require(digests.size() == DigestPages(address, bytes), "page digests do not cover the compared guest memory"); const TimedAccess timed(CounterCompare, bytes); if (Accessible(reinterpret_cast(address), bytes)) return equalsCommittedDigestBytes(address, bytes, address, digests); const auto end = address + bytes; for (const auto& [first, last] : CommittedRanges(address, bytes)) { require((first == address || first % DigestPageBytes == 0) && (last == end || last % DigestPageBytes == 0), "a committed run of compared guest memory does not start and end on page boundaries"); if (!equalsCommittedDigestBytes(first, static_cast(last - first), address, digests)) return false; } return true; } namespace { thread_local void (*compareMappedHook)(std::uint64_t, std::size_t) = nullptr; std::atomic compareMappedHookInstalled{false}; bool compareMappedHookArmed() { return compareMappedHookInstalled.load(std::memory_order_relaxed) && compareMappedHook != nullptr; } } void SetCompareMappedHook(void (*hook)(std::uint64_t address, std::size_t bytes)) { if (hook != nullptr) compareMappedHookInstalled.store(true, std::memory_order_relaxed); compareMappedHook = hook; } Compare CompareMapped(std::uint64_t address, std::span bytes) { if (bytes.empty()) return Compare::Equal; if (address == 0 || bytes.size() > std::numeric_limits::max() - address) return Compare::Unmapped; #ifdef _WIN32 std::uintptr_t arenaBase = 0; std::size_t arenaBytes = 0; GuestArena::GuestArenaRange_nid_postfix(&arenaBase, &arenaBytes); if (address >= arenaBase && bytes.size() <= arenaBytes && address - arenaBase <= arenaBytes - bytes.size() && !GuestArena::GuestArenaHostRegionOverlaps_nid_postfix(static_cast(address), bytes.size())) { if (compareMappedHookArmed()) compareMappedHook(address, bytes.size()); bool same = false; if (!GuestArena::GuestArenaCompareOwned_nid_no_patch(address, bytes.data(), bytes.size(), &same)) return Compare::Unmapped; return same ? Compare::Equal : Compare::Differs; } #elif defined(__linux__) || defined(__APPLE__) if (compareMappedHookArmed()) compareMappedHook(address, bytes.size()); constexpr std::size_t ChunkBytes = 64 * PageBytes; struct CompareMappedChunk {}; auto& chunk = HostThreadLocal, CompareMappedChunk>(); if (chunk.size() < std::min(ChunkBytes, bytes.size())) chunk.resize(std::min(ChunkBytes, bytes.size())); const int savedErrno = errno; const auto compareRun = [&](std::size_t from, std::size_t count) { if (!GuestCopyInUnsynced_nid_no_patch(chunk.data(), reinterpret_cast(address + from), count)) return Compare::Unmapped; return std::memcmp(chunk.data(), bytes.data() + from, count) != 0 ? Compare::Differs : Compare::Equal; }; auto compared = Compare::Equal; for (std::size_t done = 0; done < bytes.size() && compared == Compare::Equal; done += ChunkBytes) { const auto end = done + std::min(ChunkBytes, bytes.size() - done); compared = compareRun(done, end - done); if (compared != Compare::Unmapped) continue; compared = Compare::Equal; for (std::size_t at = done, next = 0; at < end && compared == Compare::Equal; at = next) { next = std::min(end, at + PageBytes - (address + at) % PageBytes); compared = compareRun(at, next - at); } } errno = savedErrno; return compared; #endif auto outcome = Compare::Equal; // Each run's page state is consulted right before its bytes are compared. const bool queried = describePages(static_cast(address), bytes.size(), [&](const PageRun& run) { if (!run.readable) outcome = Compare::Unmapped; else { if (compareMappedHookArmed()) compareMappedHook(run.begin, static_cast(run.end - run.begin)); if (std::memcmp(reinterpret_cast(run.begin), bytes.data() + (run.begin - address), static_cast(run.end - run.begin)) != 0) outcome = Compare::Differs; } return outcome == Compare::Equal; }); return queried ? outcome : Compare::Unmapped; } Compare CopyMapped(std::uint64_t address, std::span out) { if (out.empty()) return Compare::Equal; if (address == 0 || out.size() > std::numeric_limits::max() - address) return Compare::Unmapped; #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) const int savedErrno = errno; const bool copied = GuestCopyInUnsynced_nid_no_patch(out.data(), reinterpret_cast(address), out.size()); errno = savedErrno; return copied ? Compare::Equal : Compare::Unmapped; #else auto outcome = Compare::Equal; const bool queried = describePages(static_cast(address), out.size(), [&](const PageRun& run) { if (!run.readable) outcome = Compare::Unmapped; else std::memcpy(out.data() + (run.begin - address), reinterpret_cast(run.begin), static_cast(run.end - run.begin)); return outcome == Compare::Equal; }); return queried ? outcome : Compare::Unmapped; #endif } void WriteChangedCommitted(std::uint64_t address, std::span current, std::span original) { require(current.size() == original.size(), "write-back snapshot sizes differ"); if (Accessible(reinterpret_cast(address), current.size(), true)) { WriteChanged(address, current, original); return; } for (const auto& [begin, end] : CommittedRanges(address, current.size(), true)) { const auto offset = static_cast(begin - address); const auto length = static_cast(end - begin); WriteChanged(begin, current.subspan(offset, length), original.subspan(offset, length)); } } #if defined(__x86_64__) || defined(_M_X64) static std::uint32_t changedByteCount(__m128i same) { const auto sums = _mm_sad_epu8(_mm_and_si128(same, _mm_set1_epi8(1)), _mm_setzero_si128()); return 16u - static_cast(_mm_cvtsi128_si32(_mm_add_epi32(sums, _mm_unpackhi_epi64(sums, sums)))); } #endif std::uint32_t ChangedByteStoreLimit() { #if defined(__x86_64__) || defined(_M_X64) static const auto limit = [] { #if defined(_MSC_VER) && !defined(__clang__) int registers[4]{}; __cpuid(registers, 0); const auto ebx = static_cast(registers[1]), ecx = static_cast(registers[2]), edx = static_cast(registers[3]); #else unsigned eax = 0, ebx = 0, ecx = 0, edx = 0; if (__get_cpuid(0, &eax, &ebx, &ecx, &edx) == 0) return 4u; #endif return ebx == 0x68747541u && edx == 0x69746e65u && ecx == 0x444d4163u ? 16u : 4u; }(); return limit; #else return 16u; #endif } static void appendStored(std::vector>& stored, std::uint64_t begin, std::uint64_t end) { if (!stored.empty() && stored.back().second == begin) stored.back().second = end; else stored.emplace_back(begin, end); } static void writeChanged(std::uint64_t address, std::span current, std::span original, std::uint32_t byteStoreLimit, bool keepGuest, std::vector>* stored); void WriteChanged(std::uint64_t address, std::span current, std::span original) { writeChanged(address, current, original, ChangedByteStoreLimit(), false, nullptr); } void WriteChanged(std::uint64_t address, std::span current, std::span original, std::vector>& stored) { writeChanged(address, current, original, ChangedByteStoreLimit(), false, &stored); } static void writeChanged(std::uint64_t address, std::span current, std::span original, [[maybe_unused]] std::uint32_t byteStoreLimit, bool keepGuest, std::vector>* stored) { require(current.size() == original.size(), "write-back snapshot sizes differ"); BreakProofs(); if (current.empty()) return; // A store: the hook sync it makes orders this write after a pending GPU write, whatever a read // site above it was doing (the [hooksync] line counts stores apart). const ReadSiteScope site(ReadSite::Store); FlushGpuWrites(address, current.size()); const TimedAccess timed(CounterChangedWrite, current.size()); auto* destination = reinterpret_cast(address); const auto size = current.size(); // Stamped like a GPU write: a collect memoized for this packet would not see the page fault. storeOwn(address, size, true, [&](std::span image) { CheckRange(destination, size, 1, true); std::size_t firstChanged = size; std::size_t lastChanged = 0; std::size_t at = 0; #if defined(__x86_64__) || defined(_M_X64) bool masked = false; for (; at + 16 <= size; at += 16) { const auto bytes = _mm_loadu_si128(reinterpret_cast(current.data() + at)); const auto uploaded = _mm_loadu_si128(reinterpret_cast(original.data() + at)); auto same = _mm_cmpeq_epi8(bytes, uploaded); if (keepGuest) same = _mm_or_si128(same, _mm_xor_si128(_mm_cmpeq_epi8(_mm_loadu_si128(reinterpret_cast(destination + at)), uploaded), _mm_set1_epi8(-1))); const auto equal = static_cast(_mm_movemask_epi8(same)); if (equal == 0xffffu) continue; const auto changed = ~equal & 0xffffu; if (equal == 0) _mm_storeu_si128(reinterpret_cast<__m128i*>(destination + at), bytes); else if (byteStoreLimit < 16 && changedByteCount(same) > byteStoreLimit) { _mm_maskmoveu_si128(bytes, _mm_xor_si128(same, _mm_set1_epi8(-1)), reinterpret_cast(destination + at)); masked = true; } else { for (auto bits = changed; bits != 0; bits &= bits - 1) { const auto index = at + static_cast(std::countr_zero(bits)); destination[index] = current[index]; } } firstChanged = std::min(firstChanged, at + static_cast(std::countr_zero(changed))); lastChanged = std::max(lastChanged, at + 32 - static_cast(std::countl_zero(changed))); if (stored == nullptr) continue; for (auto bits = changed; bits != 0;) { const auto first = static_cast(std::countr_zero(bits)); const auto length = static_cast(std::countr_one(bits >> first)); appendStored(*stored, address + at + first, address + at + first + length); bits &= ~(((1u << length) - 1u) << first); } } if (masked) _mm_sfence(); #endif for (; at < size; ++at) { if (current[at] == original[at] || (keepGuest && destination[at] != original[at])) continue; destination[at] = current[at]; if (stored != nullptr) appendStored(*stored, address + at, address + at + 1); firstChanged = std::min(firstChanged, at); lastChanged = std::max(lastChanged, at + 1); } for (std::size_t index = 0; index < image.size(); ++index) { image[index] = current[index] != original[index] && !(keepGuest && image[index] != original[index]) ? current[index] : image[index]; } return firstChanged < lastChanged ? std::pair{address + firstChanged, address + lastChanged} : std::pair{0, 0}; }); } void WriteChanged(std::uint64_t address, std::span current, std::span original, std::uint32_t byteStoreLimit) { writeChanged(address, current, original, byteStoreLimit, false, nullptr); } void WriteChangedKeepingGuest(std::uint64_t address, std::span current, std::span original) { writeChanged(address, current, original, ChangedByteStoreLimit(), true, nullptr); } static_assert(std::atomic_ref::is_always_lock_free && std::atomic_ref::is_always_lock_free); std::size_t WriteChangedIfHeld(std::uint64_t address, std::span current, std::span original, std::uint64_t unchangedSince) { require(current.size() == original.size(), "write-back snapshot sizes differ"); BreakProofs(); if (current.empty()) return 0; const ReadSiteScope site(ReadSite::Store); FlushGpuWrites(address, current.size()); const TimedAccess timed(CounterChangedWrite, current.size()); auto* destination = reinterpret_cast(address); const auto size = current.size(); std::size_t lost = 0; storeOwn(address, size, false, [&](std::span) { CheckRange(destination, size, 1, true); if (unchangedSince != 0u) { auto& tracker = Tracker(); if (!tracker.cpuUnchanged(address, size, unchangedSince) || tracker.refusedSince(address, address + size, unchangedSince)) { lost = size; return std::pair{0, 0}; } } std::size_t firstChanged = size; std::size_t lastChanged = 0; const auto exchange = [&](std::size_t index) { if (current[index] == original[index]) return; auto expected = std::to_integer(original[index]); firstChanged = std::min(firstChanged, index); lastChanged = std::max(lastChanged, index + 1); if (!std::atomic_ref(destination[index]).compare_exchange_strong(expected, std::to_integer(current[index]))) ++lost; }; std::size_t at = 0; for (; at < size && lost == 0 && ((address + at) & 7u) != 0u; ++at) exchange(at); for (; at + 8 <= size && lost == 0; at += 8) { std::uint64_t wanted, held; std::memcpy(&wanted, current.data() + at, 8); std::memcpy(&held, original.data() + at, 8); if (wanted == held) continue; firstChanged = std::min(firstChanged, at); lastChanged = std::max(lastChanged, at + 8); if (std::atomic_ref(*reinterpret_cast(destination + at)).compare_exchange_strong(held, wanted)) continue; for (std::size_t index = at; index < at + 8; ++index) exchange(index); } for (; at < size && lost == 0; ++at) exchange(at); return firstChanged < lastChanged ? std::pair{address + firstChanged, address + lastChanged} : std::pair{0, 0}; }, false); return lost; } void Write(std::uint64_t address, std::span source, std::size_t alignment) { if (source.empty()) return; // A store, as in WriteChanged. const ReadSiteScope site(ReadSite::Store); FlushGpuWrites(address, source.size()); const TimedAccess timed(CounterWrite, source.size()); CountWriteCaller(__builtin_return_address(0)); auto* destination = reinterpret_cast(address); // Stamped like a GPU write: a collect memoized for this packet would not see the page fault. StoreOwnBytes(address, source.size(), [&](std::span image) { CheckRange(destination, source.size(), alignment, true); if (source.size() >= PageBytes) copyOwnBytes(address, source); else std::memcpy(destination, source.data(), source.size()); if (!image.empty()) std::memcpy(image.data(), source.data(), source.size()); }); } } extern "C" void AgcDriverCheckGuestMemory_nid_postfix(const void* pointer, std::size_t bytes, std::size_t alignment, bool writable) { AgcDriver::GuestMemory::CheckRange(pointer, bytes, alignment, writable); } extern "C" void AgcDriverStoreGuestLabel_nid_postfix(std::uint64_t* pointer, std::uint64_t value) { AgcDriver::GuestMemory::StoreOwnBytes(reinterpret_cast(pointer), sizeof(*pointer), [&](std::span image) { AgcDriver::GuestMemory::CheckRange(pointer, sizeof(*pointer), std::atomic_ref::required_alignment, true); std::atomic_ref(*pointer).store(value, std::memory_order_release); if (!image.empty()) std::memcpy(image.data(), &value, sizeof(value)); }); }