Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
| `LEONIDA_TEXTURE_SWEEP_BUDGET_US` | `400` | Microseconds a pass may spend on residency checks and uploads between textures. |
| `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. |
| `LEONIDA_TITLE_BUFFER_COVERAGE` | on | Such a view counts as covered only when a known buffer spans all its bytes. `0` asks for the first byte only. |
| `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. |
| `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh: as before unchanged generations were skipped, and as before the pages reserved in the title's xmem reservations were passed over. |
| `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. |
| `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. |
| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`). **Since RT-BOOT-COMBINED `0` also needs `LEONIDA_TITLE_WATCHDOG_KICK`**: the watchdog's addresses are no longer built in. With `0` and no `LEONIDA_TITLE_WATCHDOG_KICK`, the loader says once that the watchdog stays armed. |
Expand Down
55 changes: 42 additions & 13 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,8 @@ void copy_run(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, boo
// - pages this tracker made read-only weren't written: skipped;
// - other readable pages (read-only or copy-on-write pages of the title's own, pages another tracker protected)
// can't be watched: copied every time, as before;
// - pages not committed, or not readable, are zero in the copies (written once);
// - pages not committed, or not readable, are zero in the copies (written once); one that is reserved in the
// title's xmem reservations (title_reservations) is not asked about again until the journal names it;
// - pages xmem reports mapped at another address too (title_page_watch.h): a write through the other address
// doesn't fault here, so their 64 KiB blocks are guarded at every address by the geometry watch's cells
// (update_aliased) and copied when a cell's version moved. Without the other addresses (no xmem), or while a
Expand Down Expand Up @@ -527,6 +528,7 @@ class ShadowPages {
zeroed_.clear();
copy_bytes_ = {};
std::uint64_t queries = 0;
const std::uint64_t reservations = leonida::title_reservations::generation();
// LEONIDA_SHADOW_FULL_WALK=1 queries every page at every refresh, as before the generation skip.
static const bool always_full_walk = [] {
char value[8] = {};
Expand All @@ -550,6 +552,11 @@ class ShadowPages {
full_walk = true;
refresh_walked_all_ = full_walk;
refresh_protects_ = alias_arms_;
if (reservations != reservation_generation_) { // one released since: its pages are asked about again
reservation_generation_ = reservations;
for (std::uint8_t& s : state_)
if ((s & (kZero | kHot)) == kZero) s &= std::uint8_t(~kClean);
}
if (pinned_) {
for (std::uint8_t& s : state_) s &= ~kPinned;
pinned_ = false;
Expand Down Expand Up @@ -577,9 +584,15 @@ class ShadowPages {
// Wine (NtQueryVirtualMemory waits for Wine's virtual-memory lock, which the mapping threads hold), a
// fifth of the submitting thread's time. So are aliased pages whose cells no write reached (aliased_clean):
// a mapping, commitment or protection change over a cell moves its version too.
// A page reserved in the title's xmem reservations is passed over at every refresh (kZero | kClean): only
// xmem's and the title's memory calls change it, and the journal names each of them. After the story load
// the walk made 450-7,500 queries a refresh of such pages, one for each of the stream pools' unmapped
// 64 KiB slots, 1.5 us each when nothing else mapped memory and 15-70 us under that lock while the title's
// mapping threads were busy: most of a walk of 100-330 ms a submission (RTX 3090, Wine 11).
const auto skip = [&](std::size_t i) {
const std::uint8_t s = state_[i];
return unchanged(s) || ((s & ~(kZero | kProtected)) == kAliased && aliased_clean(i)) ||
return unchanged(s) || s == (kZero | kClean) ||
((s & ~(kZero | kProtected)) == kAliased && aliased_clean(i)) ||
(!copy_aliased_ && (s == kAliased || s == kZero || s == (kZero | kAliased)));
};
if (!full_walk && skip(i0)) {
Expand All @@ -604,20 +617,34 @@ class ShadowPages {
break;
}
const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0;
if (kind != Kind::zero)
for (std::size_t i = i0; i < i1; ++i)
if (state_[i] & kZero) state_[i] &= std::uint8_t(~kClean); // committed or mapped now
switch (kind) {
case Kind::zero:
case Kind::zero: {
// Reserved, private, and inside the title's xmem reservations: passed over until the journal names it
// (see skip above). Aliased, pinned and write-watched pages are left out: a first touch through a
// physical page's other address is journaled for that address alone, and a pin or a write watch is
// the business of the passes before the walk.
const bool settled = region.State == MEM_RESERVE && region.Type == MEM_PRIVATE &&
leonida::title_reservations::contains(at, next);
for (std::size_t i = i0; i < i1; ++i) {
if (state_[i] & kZero) continue;
const auto [offset, bytes] = span_of(i, i + 1);
zero_targets(offset, bytes);
leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes);
if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset)
zeroed_.back().bytes += bytes;
else
zeroed_.push_back({offset, bytes, false});
state_[i] = std::uint8_t(kZero | (state_[i] & (kAliased | kPinned | kWatched)));
if (!(state_[i] & kZero)) {
const auto [offset, bytes] = span_of(i, i + 1);
zero_targets(offset, bytes);
leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes);
if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset)
zeroed_.back().bytes += bytes;
else
zeroed_.push_back({offset, bytes, false});
state_[i] = std::uint8_t(kZero | (state_[i] & (kAliased | kPinned | kWatched)));
}
const bool alone = (state_[i] & ~(kClean | kRequery)) == kZero;
state_[i] = settled && alone ? std::uint8_t(state_[i] | kClean)
: std::uint8_t(state_[i] & ~kClean);
}
break;
}
case Kind::writable:
case Kind::read_only:
for (std::size_t i = i0; i < i1;) {
Expand Down Expand Up @@ -934,7 +961,8 @@ class ShadowPages {
kAliased = 4, // xmem maps its physical page at another address too
kPinned = 8, // a kernel write into it may be in flight (leonida::kernel_writes)
kWatched = 16, // in a write-watched reservation (leonida::title_write_watch)
kClean = 32, // hot, and not written since it was copied after an asking
kClean = 32, // hot, and not written since it was copied after an asking; on a zero page: reserved in
// the title's xmem reservations, passed over until the journal names it
kHot = 64, // write-watched and asked about at every refresh, never guarded
kRequery = 128, // its mapping, commitment or protection changed (title_memory_map): queried at the next walk
};
Expand Down Expand Up @@ -1427,6 +1455,7 @@ class ShadowPages {
Vector<std::uint8_t> clean_;
Vector<std::uintptr_t> rearm_;
std::uint64_t alias_arms_ = 0; // arm() calls of the last update_aliased()
std::uint64_t reservation_generation_ = ~std::uint64_t(0); // the xmem reservations its zero pages were settled under
std::uint64_t map_generation_ = ~std::uint64_t(0);
bool pinned_ = false; // some page has kPinned
Vector<Job> jobs_; // refresh() only, which DeviceState::shadow_mutex serializes
Expand Down
15 changes: 13 additions & 2 deletions runtime/shims/xmem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -906,11 +906,16 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON
// the host is part way through changing.
const FaultLockExclusive view_lock;
if (!isolate_placeholder(address, size)) return nullptr;
if (window)
if (window) {
replace_window(g_fault_windows, reinterpret_cast<uintptr_t>(address), size, host_prot, true);
else
leonida::title_reservations::add(reinterpret_cast<uintptr_t>(address), size);
} else {
replaced = placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, host_type | MEM_RESERVE,
host_prot, nullptr, 0);
// Ordinary memory now, which the title commits with VirtualAlloc: not a reservation of xmem's.
leonida::title_reservations::forget(reinterpret_cast<uintptr_t>(address),
reinterpret_cast<uintptr_t>(address) + size);
}
}
if (!window) return replaced;
// A reserve-only replacement stays a placeholder: the physical pages are mapped into it.
Expand All @@ -925,6 +930,7 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON
{
const FaultLockExclusive faults;
replace_window(g_fault_windows, reinterpret_cast<uintptr_t>(result), size, host_prot, false);
leonida::title_reservations::add(reinterpret_cast<uintptr_t>(result), size);
}
// Diagnostic (temporary): the windows a fault can be inside.
std::fprintf(stderr, "[rt] xmem: window reserve %p size %llu protect 0x%lx\n", result,
Expand All @@ -936,6 +942,7 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON
const FaultLockExclusive lock;
forget_range(g_title_placeholders, base, base + size); // a release the table missed
g_title_placeholders[base] = Window{size, host_prot};
leonida::title_reservations::add(base, size);
}
std::fprintf(stderr, "[rt] xmem: placeholder reserve %p size %llu\n", result,
static_cast<unsigned long long>(size));
Expand Down Expand Up @@ -1694,6 +1701,7 @@ bool install_physical_page_fault_handler() {
placeholder_api();
leonida::host_heap::handle();
leonida::geometry_writes::state();
leonida::title_reservations::state();
char flag[4]{};
g_pool_zero_pages = GetEnvironmentVariableA("LEONIDA_POOL_ZERO_PAGES", flag, sizeof(flag)) == 1 && flag[0] == '1';
return AddVectoredExceptionHandler(1, &physical_page_fault) != nullptr;
Expand Down Expand Up @@ -2276,6 +2284,9 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) {
} else {
result = VirtualFree(address, size, free_type);
}
// Every release, also of a reservation xmem's tables missed, before the journal names its pages: the host can
// reserve the space again for memory the shadows would otherwise take as settled.
if (result && releases && release_end > start) leonida::title_reservations::forget(start, release_end);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor race note: for tracked windows/placeholders, title_release() frees the pages and drops g_fault_windows / g_title_placeholders under g_phys_mutex + FaultLockExclusive, then unlocks before returning here. If another thread immediately reserves the freed range via XMemVirtualAlloc and calls title_reservations::add() before this line runs, forget(start, release_end) will drop the new reservation (safe -- shadows just fall back to querying it -- only loses the skip optimization for that range). Calling title_reservations::forget(start, end) inside title_release() under FaultLockExclusive (while keeping this fallback for untracked releases) would close that window.

// A release of size 0 frees the whole reservation, whose extent is not known here: a change anywhere.
if (result && size) leonida::title_memory_map::changed(address, size);
else if (result) leonida::title_memory_map::changed();
Expand Down
83 changes: 82 additions & 1 deletion runtime/src/title_page_watch.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@
// faulting page.
//
// Successful title memory map changes also invalidate the shadows' cached protection state. The shadows' own
// protection changes stay local to their trackers.
// protection changes stay local to their trackers. A reserved page of the title's placeholders and physical-page
// windows (title_reservations, below) changes only through such a change, so a shadow doesn't ask about it again
// until one names it.
//
// The shadows themselves are brought up to date in one place, DeviceState::refresh_shadows in
// d3d12_vulkan_device.cpp, which VulkanQueue::execute_now calls (VulkanContext::set_before_execute) before every
Expand Down Expand Up @@ -720,6 +722,85 @@ std::uint64_t ask(std::uint64_t reader, const Runs& runs, Dirty&& dirty, Refused

} // namespace leonida::title_write_watch

// 7. The title's xmem reservations (title_reservations): its placeholders and physical-page windows, from the
// reservation to its release. Nothing but xmem and the title's own memory calls changes their pages, and those
// record every change in title_memory_map (a placeholder refuses a plain commit, and the title doesn't commit
// inside a window with VirtualAlloc: see the windows in xmem.cpp). A shadow takes a page there that is reserved
// and not mapped as zero until the journal names it, instead of asking VirtualQuery at every submission: under
// Wine a query waits for the virtual-memory lock, and the world's thousands of 64 KiB placeholders made the
// queries most of a refresh.
namespace leonida::title_reservations {

// Allocates from host_heap, as title_write_watch does: the D3D12 layer asks under a tracker's lock.
struct State {
std::shared_mutex mutex; // ranges
host_heap::map<std::uintptr_t, std::uintptr_t> ranges; // base -> end; apart, never touching
std::atomic<std::size_t> count{0}; // ranges.size(), read without the lock
std::atomic<std::uint64_t> generation{1}; // moved whenever a range was released or dropped
};

inline State& state() {
static State s;
return s;
}

// xmem: [base, base + size) was reserved as a placeholder or a physical-page window of the title's. Inside one range
// already, it is part of that reservation (a window replacing part of a placeholder). A range it only overlaps was
// released without xmem seeing it, and goes whole, as xmem's tables drop it: nothing outside the new reservation is
// known to be one of the title's any more.
inline void add(std::uintptr_t base, std::uintptr_t size) {
if (!size) return;
State& s = state();
const std::uintptr_t end = base + size;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor defensive guard: if (!size || size > UINTPTR_MAX - base) return; avoids unsigned wraparound if a caller ever passes an unvalidated size.

std::unique_lock lock(s.mutex);
auto it = s.ranges.upper_bound(base);
if (it != s.ranges.begin() && std::prev(it)->second > base) --it;
if (it != s.ranges.end() && it->first <= base && it->second >= end) return; // inside one range already
bool erased = false;
while (it != s.ranges.end() && it->first < end) {
it = s.ranges.erase(it);
erased = true;
}
s.ranges.emplace(base, end);
s.count.store(s.ranges.size(), std::memory_order_release);
if (erased) s.generation.fetch_add(1, std::memory_order_release);
}

// xmem: [start, end) was released.
inline void forget(std::uintptr_t start, std::uintptr_t end) {
State& s = state();
if (start >= end || !s.count.load(std::memory_order_acquire)) return;
std::unique_lock lock(s.mutex);
auto it = s.ranges.lower_bound(start);
if (it != s.ranges.begin() && std::prev(it)->second > start) --it;
bool erased = false;
while (it != s.ranges.end() && it->first < end) {
const std::uintptr_t base = it->first, until = it->second;
it = s.ranges.erase(it);
erased = true;
if (base < start) s.ranges.emplace(base, start);
if (until > end) it = s.ranges.emplace(end, until).first;
}
if (!erased) return;
s.count.store(s.ranges.size(), std::memory_order_release);
s.generation.fetch_add(1, std::memory_order_release);
}

// Moved whenever a reservation was released: what a shadow keeps of the reserved pages starts again. (A reservation
// made covers pages no shadow had settled: they were in no range until then, or in one released since.)
inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); }

// Whether [begin, end) is inside one of the title's xmem reservations.
inline bool contains(std::uintptr_t begin, std::uintptr_t end) {
State& s = state();
if (!s.count.load(std::memory_order_acquire)) return false;
std::shared_lock lock(s.mutex);
auto it = s.ranges.upper_bound(begin);
return it != s.ranges.begin() && (--it)->second >= end;
}

} // namespace leonida::title_reservations

namespace leonida::kernel_writes {

// The layer's side: makes every watched page in [begin, end) writable. Set once the first shadow exists.
Expand Down
Loading
Loading