upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-30 04:34:17 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-30 04:34:17 -0500
commitefc1929908a728d95fa09ffef0a743d2a649b86d (patch)
tree9e2b3a70ef49d7ec265301cf85606686f371ac57 /runtime
parent1aefed0dacd492a040909c9a423f270ebdab84f4 (diff)
runtime: eliminate Windows 11 full-space commit_pages_locked broadcast storm, ShadowPages/TitleTextureCells guard conflict, and streaming budget bursts
Diffstat (limited to 'runtime')
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp186
-rw-r--r--runtime/shims/xmem.cpp49
-rw-r--r--runtime/src/title_geometry_watch.h106
-rw-r--r--runtime/src/title_texture_refresh.h128
-rw-r--r--runtime/test/d3d12_existing_heap_test.cpp164
-rw-r--r--runtime/test/title_texture_refresh_test.cpp104
-rw-r--r--runtime/test/xmem_test.cpp25
7 files changed, 692 insertions, 70 deletions
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index f4bc5d2ea..ba6201a02 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -1179,7 +1179,11 @@ private:
1179 } 1179 }
1180 1180
1181 // Guarded pages [i, j) of a read-only region: pages this tracker protected, and aliased pages whose cells no write 1181 // Guarded pages [i, j) of a read-only region: pages this tracker protected, and aliased pages whose cells no write
1182 // reached, are as the last refresh left them; any other is copied again. 1182 // reached, are as the last refresh left them; non-aliased pages already armed read-only by geometry_writes
1183 // (TitleTextureCells / GeometryViews / TitleMirror) adopt kProtected after one copy so ShadowPages skips them on
1184 // subsequent refreshes instead of recopying them forever as Copy::read_only (shadow_write_fault and
1185 // open_shadow_pages reopen the whole 64 KiB tile via ShadowPages::reopen_range, and release()/set_hot() notify
1186 // title_memory_map::changed()); any other read-only page is copied again.
1183 void guard_read_only(std::size_t i0, std::size_t i1, bool streaming) { 1187 void guard_read_only(std::size_t i0, std::size_t i1, bool streaming) {
1184 const auto clean_at = [&](std::size_t k) { 1188 const auto clean_at = [&](std::size_t k) {
1185 const std::uint8_t s = state_[k]; 1189 const std::uint8_t s = state_[k];
@@ -1190,12 +1194,44 @@ private:
1190 const bool clean = clean_at(i); 1194 const bool clean = clean_at(i);
1191 std::size_t j = i + 1; 1195 std::size_t j = i + 1;
1192 while (j < i1 && clean_at(j) == clean) ++j; 1196 while (j < i1 && clean_at(j) == clean) ++j;
1193 if (!clean && !(!copy_aliased_ && (state_[i] & kAliased))) { 1197 if (!clean) {
1194 for (std::size_t k = i; k < j; ++k) state_[k] &= ~kZero; 1198 for (std::size_t p = i; p < j;) {
1195 add_job(i, j, streaming, 1199 const std::uint8_t flags = state_[p] & (kAliased | kPinned);
1196 state_[i] & kAliased ? Copy::aliased 1200 std::size_t q = p + 1;
1197 : state_[i] & kPinned ? Copy::pinned 1201 while (q < j && (state_[q] & (kAliased | kPinned)) == flags) ++q;
1198 : Copy::read_only); 1202 if (!copy_aliased_ && (flags & kAliased)) {
1203 p = q;
1204 continue;
1205 }
1206 if (!flags && watch_) {
1207 for (std::size_t chunk = p; chunk < q;) {
1208 constexpr std::size_t kChunk = 64;
1209 const std::size_t n = std::min<std::size_t>(q - chunk, kChunk);
1210 std::uint8_t gw[kChunk];
1211 leonida::geometry_writes::query_pages_guarded(first_ + chunk * kPage, n, gw);
1212 for (std::size_t o = 0; o < n;) {
1213 const bool adopted = gw[o] != 0;
1214 std::size_t o_end = o + 1;
1215 while (o_end < n && (gw[o_end] != 0) == adopted) ++o_end;
1216 for (std::size_t k = chunk + o; k < chunk + o_end; ++k) {
1217 state_[k] &= ~kZero;
1218 if (adopted) state_[k] |= kProtected;
1219 }
1220 add_job(chunk + o, chunk + o_end, streaming,
1221 adopted ? Copy::guarded : Copy::read_only);
1222 o = o_end;
1223 }
1224 chunk += n;
1225 }
1226 } else {
1227 for (std::size_t k = p; k < q; ++k) state_[k] &= ~kZero;
1228 add_job(p, q, streaming,
1229 (flags & kAliased) ? Copy::aliased
1230 : (flags & kPinned) ? Copy::pinned
1231 : Copy::read_only);
1232 }
1233 p = q;
1234 }
1199 } 1235 }
1200 i = j; 1236 i = j;
1201 } 1237 }
@@ -1284,8 +1320,9 @@ private:
1284 // A table page with no host view anywhere (src/title_frames.h) has no other address to guard: its own cell, 1320 // A table page with no host view anywhere (src/title_frames.h) has no other address to guard: its own cell,
1285 // which every change of its frame moves, is all there is. 1321 // which every change of its frame moves, is all there is.
1286 if (!copy_aliased_ || (b.peers.empty() && !leonida::title_frames::backed(va))) continue; 1322 if (!copy_aliased_ || (b.peers.empty() && !leonida::title_frames::backed(va))) continue;
1287 b.armed = watch::arm(va, *b.cell); 1323 // allow_hot = false: ShadowPages does not poll geometry_writes::hot_tiles(), so a hot cell stays unarmed.
1288 for (const auto& [other, cell] : b.peers) b.armed = watch::arm(other, *cell) && b.armed; 1324 b.armed = watch::arm(va, *b.cell, false);
1325 for (const auto& [other, cell] : b.peers) b.armed = watch::arm(other, *cell, false) && b.armed;
1289 alias_arms_ += 1 + b.peers.size(); 1326 alias_arms_ += 1 + b.peers.size();
1290 b.version = version; 1327 b.version = version;
1291 } 1328 }
@@ -1431,10 +1468,15 @@ private:
1431 std::size_t copy_changed(const Job& job) { 1468 std::size_t copy_changed(const Job& job) {
1432 std::size_t copied = 0; 1469 std::size_t copied = 0;
1433 alignas(64) std::uint8_t page[kPage]; 1470 alignas(64) std::uint8_t page[kPage];
1434 for (std::size_t at = job.offset, end = job.offset + job.bytes; at < end;) { 1471 const auto copy_page_bytes = [&](std::uintptr_t va, const std::uint8_t* src, std::size_t n, bool streaming) {
1435 const std::uintptr_t va = begin_ + at; 1472 if (!copy_guarded_host(page, src, n, streaming)) {
1436 const std::size_t n = std::min<std::size_t>(end - at, kPage - (va & (kPage - 1))); 1473 for (std::size_t off = 0; off < n;) {
1437 copy_run(page, reinterpret_cast<const std::uint8_t*>(va), n, job.streaming); 1474 const std::size_t in_page = (va + off) & 4095;
1475 const std::size_t m = std::min<std::size_t>(n - off, 4096 - in_page);
1476 if (!copy_guarded_host(page + off, src + off, m, streaming)) std::memset(page + off, 0, m);
1477 off += m;
1478 }
1479 }
1438 leonida::shadow_keep::copy_changed( 1480 leonida::shadow_keep::copy_changed(
1439 page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) { 1481 page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) {
1440 for_each_target(a, b, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { 1482 for_each_target(a, b, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) {
@@ -1442,6 +1484,26 @@ private:
1442 copied += to - from; 1484 copied += to - from;
1443 }); 1485 });
1444 }); 1486 });
1487 };
1488 const std::uintptr_t job_va = begin_ + job.offset;
1489 if (leonida::title_frames::may_hold(job_va, job_va + job.bytes)) {
1490 leonida::title_frames::for_each_part(
1491 job_va, job.bytes, [&](std::uintptr_t part, std::size_t len, std::uint8_t* frame) {
1492 for (std::size_t off = 0; off < len;) {
1493 const std::uintptr_t va = part + off;
1494 const std::size_t n = std::min<std::size_t>(len - off, kPage - (va & (kPage - 1)));
1495 const auto* src = frame ? (frame + off) : reinterpret_cast<const std::uint8_t*>(va);
1496 copy_page_bytes(va, src, n, job.streaming && !frame);
1497 off += n;
1498 }
1499 return true;
1500 });
1501 return copied;
1502 }
1503 for (std::size_t at = job.offset, end = job.offset + job.bytes; at < end;) {
1504 const std::uintptr_t va = begin_ + at;
1505 const std::size_t n = std::min<std::size_t>(end - at, kPage - (va & (kPage - 1)));
1506 copy_page_bytes(va, reinterpret_cast<const std::uint8_t*>(va), n, job.streaming);
1445 at += n; 1507 at += n;
1446 } 1508 }
1447 return copied; 1509 return copied;
@@ -1533,8 +1595,7 @@ private:
1533 VirtualProtect(reinterpret_cast<void*>(first_ + i * kPage), (j - i) * kPage, writable, &old)) 1595 VirtualProtect(reinterpret_cast<void*>(first_ + i * kPage), (j - i) * kPage, writable, &old))
1534 { 1596 {
1535 for (std::size_t k = i; k < j; ++k) state_[k] &= ~kProtected; 1597 for (std::size_t k = i; k < j; ++k) state_[k] &= ~kProtected;
1536 leonida::geometry_writes::notify(first_ + i * kPage, first_ + j * kPage, 1598 leonida::geometry_writes::note_external_reopen(first_ + i * kPage, first_ + j * kPage);
1537 leonida::geometry_writes::Event::write);
1538 } 1599 }
1539 i = j; 1600 i = j;
1540 } 1601 }
@@ -4104,6 +4165,8 @@ struct DeviceState {
4104 // defined after TitleTexture. 4165 // defined after TitleTexture.
4105 std::mutex title_texture_mutex; 4166 std::mutex title_texture_mutex;
4106 std::map<std::uint64_t, std::shared_ptr<TitleTexture>> title_textures; 4167 std::map<std::uint64_t, std::shared_ptr<TitleTexture>> title_textures;
4168 VkDeviceSize title_partial_bytes = 0; // image memory of textures filled in part, under title_texture_mutex
4169 void clear_partial_budget(TitleTexture& t);
4107 // Which registered textures may have changed since their last fill (title_texture_watch.h), under 4170 // Which registered textures may have changed since their last fill (title_texture_watch.h), under
4108 // title_texture_mutex: their tiles are geometry-watch cells, armed read-only. 4171 // title_texture_mutex: their tiles are geometry-watch cells, armed read-only.
4109 TitleTextureCells texture_cells; 4172 TitleTextureCells texture_cells;
@@ -20417,7 +20480,7 @@ struct TitleTexture {
20417 std::uint64_t fills = 0; 20480 std::uint64_t fills = 0;
20418 unsigned view_mip = 0; // minimum effective_min_mip seen across views 20481 unsigned view_mip = 0; // minimum effective_min_mip seen across views
20419 bool view_mip_set = false; 20482 bool view_mip_set = false;
20420 bool partial_budget_counted = false; // backing_bytes currently accounted in title_partial_bytes_ 20483 bool partial_budget_counted = false; // backing_bytes currently accounted in state_.title_partial_bytes
20421 // The last probe: the first mip readable with every smaller one (the mip count: none; only a 2D texture of one 20484 // The last probe: the first mip readable with every smaller one (the mip count: none; only a 2D texture of one
20422 // slice has other values than 0 and the mip count). memory.pending(): above fill_limit, no use yet. 20485 // slice has other values than 0 and the mip count). memory.pending(): above fill_limit, no use yet.
20423 unsigned readable_from = 0; 20486 unsigned readable_from = 0;
@@ -20425,10 +20488,14 @@ struct TitleTexture {
20425 20488
20426 bool is_write_combined() { 20489 bool is_write_combined() {
20427 if (!write_combined_known) { 20490 if (!write_combined_known) {
20428 MEMORY_BASIC_INFORMATION region{}; 20491 const auto va = static_cast<std::uintptr_t>(cpu);
20429 write_combined = VirtualQuery(reinterpret_cast<const void*>(static_cast<std::uintptr_t>(cpu)), &region, 20492 if (va && leonida::title_frames::may_hold(va, va + 1) && leonida::title_frames::backed(va)) {
20430 sizeof(region)) && 20493 write_combined = false;
20431 (region.Protect & PAGE_WRITECOMBINE) != 0; 20494 } else {
20495 MEMORY_BASIC_INFORMATION region{};
20496 write_combined = VirtualQuery(reinterpret_cast<const void*>(va), &region, sizeof(region)) &&
20497 (region.Protect & PAGE_WRITECOMBINE) != 0;
20498 }
20432 write_combined_known = true; 20499 write_combined_known = true;
20433 } 20500 }
20434 return write_combined; 20501 return write_combined;
@@ -20856,6 +20923,12 @@ void DeviceState::title_texture_unmapped(const void* resource, std::uint64_t add
20856 } 20923 }
20857} 20924}
20858 20925
20926void DeviceState::clear_partial_budget(TitleTexture& t) {
20927 if (!t.partial_budget_counted) return;
20928 title_partial_bytes = title_partial_bytes >= t.backing_bytes ? title_partial_bytes - t.backing_bytes : 0;
20929 t.partial_budget_counted = false;
20930}
20931
20859void DeviceState::title_texture_gone(const void* resource, std::uint64_t address) { 20932void DeviceState::title_texture_gone(const void* resource, std::uint64_t address) {
20860 if (t_in_title_textures) { // this thread holds title_texture_mutex 20933 if (t_in_title_textures) { // this thread holds title_texture_mutex
20861 { 20934 {
@@ -20867,6 +20940,7 @@ void DeviceState::title_texture_gone(const void* resource, std::uint64_t address
20867 } 20940 }
20868 const auto it = title_textures.find(address); 20941 const auto it = title_textures.find(address);
20869 if (it != title_textures.end() && it->second->resource == resource) { 20942 if (it != title_textures.end() && it->second->resource == resource) {
20943 clear_partial_budget(*it->second);
20870 it->second->resource = nullptr; 20944 it->second->resource = nullptr;
20871 texture_watch.untrack(address); 20945 texture_watch.untrack(address);
20872 } 20946 }
@@ -20883,6 +20957,7 @@ void DeviceState::title_texture_gone(const void* resource, std::uint64_t address
20883 } 20957 }
20884 const auto it = title_textures.find(address); 20958 const auto it = title_textures.find(address);
20885 if (it != title_textures.end() && it->second->resource == resource) { 20959 if (it != title_textures.end() && it->second->resource == resource) {
20960 clear_partial_budget(*it->second);
20886 texture_watch.untrack(address); 20961 texture_watch.untrack(address);
20887 it->second->resource = nullptr; 20962 it->second->resource = nullptr;
20888 title_textures.erase(it); 20963 title_textures.erase(it);
@@ -23204,6 +23279,7 @@ public:
23204 retired_earliest_ns_.store(0, std::memory_order_release); 23279 retired_earliest_ns_.store(0, std::memory_order_release);
23205 for (auto it = state_.title_textures.begin(); it != state_.title_textures.end();) { 23280 for (auto it = state_.title_textures.begin(); it != state_.title_textures.end();) {
23206 if (it->second && it->second->owned) { 23281 if (it->second && it->second->owned) {
23282 state_.clear_partial_budget(*it->second);
23207 if (it->second->resource) { 23283 if (it->second->resource) {
23208 owned_release.push_back(it->second->resource); 23284 owned_release.push_back(it->second->resource);
23209 it->second->resource = nullptr; 23285 it->second->resource = nullptr;
@@ -23644,6 +23720,7 @@ public:
23644 return; 23720 return;
23645 } 23721 }
23646 if (slot && slot->owned) retire_title_texture(*slot); 23722 if (slot && slot->owned) retire_title_texture(*slot);
23723 if (slot) state_.clear_partial_budget(*slot);
23647 state_.index_texture(*entry); 23724 state_.index_texture(*entry);
23648 slot = std::move(entry); 23725 slot = std::move(entry);
23649 ++title_stats_.registered; 23726 ++title_stats_.registered;
@@ -23684,11 +23761,7 @@ public:
23684 entry.gpu_written = true; 23761 entry.gpu_written = true;
23685 entry.stale = false; 23762 entry.stale = false;
23686 entry.filled_from = 0; 23763 entry.filled_from = 0;
23687 if (entry.partial_budget_counted) { 23764 state_.clear_partial_budget(entry);
23688 title_partial_bytes_ =
23689 title_partial_bytes_ >= entry.backing_bytes ? title_partial_bytes_ - entry.backing_bytes : 0;
23690 entry.partial_budget_counted = false;
23691 }
23692 state_.texture_watch.untrack(entry.address); 23765 state_.texture_watch.untrack(entry.address);
23693 // Never publish views on an unbound deferred VkImage (VUID-vkCreateImageView-image-01020): clear any pending 23766 // Never publish views on an unbound deferred VkImage (VUID-vkCreateImageView-image-01020): clear any pending
23694 // partial clamp so prepare() / bind_placed_memory() binds, initializes, and publishes at mip 0, and only 23767 // partial clamp so prepare() / bind_placed_memory() binds, initializes, and publishes at mip 0, and only
@@ -23766,16 +23839,7 @@ public:
23766 // A fill this pass makes can retire an image (title_texture_gone while this thread holds the registry): the 23839 // A fill this pass makes can retire an image (title_texture_gone while this thread holds the registry): the
23767 // entry stops naming the resource and is erased by drain_titles_gone after the pass. Entries are looked up by 23840 // entry stops naming the resource and is erased by drain_titles_gone after the pass. Entries are looked up by
23768 // key each time, and one without a resource is passed over. 23841 // key each time, and one without a resource is passed over.
23769 if (partial_mips()) { 23842 // state_.title_partial_bytes is maintained incrementally on back/fill/retire/evict/destroy (no O(N) map walk).
23770 title_partial_bytes_ = 0;
23771 for (const auto& [address, entry] : state_.title_textures) {
23772 const bool partial_live =
23773 !entry->gpu_written && entry->resource && entry->backing_bytes &&
23774 ((entry->fills && entry->filled_from) || (!entry->fills && entry->partial_budget_counted));
23775 entry->partial_budget_counted = partial_live;
23776 if (partial_live) title_partial_bytes_ += entry->backing_bytes;
23777 }
23778 }
23779 bool overflow = false; 23843 bool overflow = false;
23780 auto written = leonida::title_texel_writes::take(overflow); 23844 auto written = leonida::title_texel_writes::take(overflow);
23781 stats.written_ranges += written.size(); 23845 stats.written_ranges += written.size();
@@ -23789,17 +23853,14 @@ public:
23789 stats.map_ranges += title_map_changes_.size(); 23853 stats.map_ranges += title_map_changes_.size();
23790 stats.map_all += map_all; 23854 stats.map_all += map_all;
23791 // A mapping change: the textures over it probe their memory again (TextureReadability) and invalidate cached 23855 // A mapping change: the textures over it probe their memory again (TextureReadability) and invalidate cached
23792 // write_combined status. 23856 // write_combined status. Partial-mip upgrades are detected in Stage 2b after the single cached readability
23857 // probe (avoiding uncached per-texture VirtualQuery loops here).
23793 const auto remapped = [&](std::uint64_t key) { 23858 const auto remapped = [&](std::uint64_t key) {
23794 const auto it = state_.title_textures.find(key); 23859 const auto it = state_.title_textures.find(key);
23795 if (it != state_.title_textures.end()) { 23860 if (it != state_.title_textures.end()) {
23796 TitleTexture& t = *it->second; 23861 TitleTexture& t = *it->second;
23797 t.memory.retry(); 23862 t.memory.retry();
23798 t.write_combined_known = false; 23863 t.write_combined_known = false;
23799 if (partial_mips() && !t.gpu_written && t.layout_known && !t.stale && t.resource &&
23800 !t.layout_guessed && (!t.fills || t.filled_from) &&
23801 title_texture_readable(t) && (!t.fills || t.readable_from < t.filled_from))
23802 t.stale = true;
23803 } 23864 }
23804 }; 23865 };
23805 // A pure texel write (XG CopyIntoSubresource / DirectStorage / slot-31 copy): do NOT invalidate cached 23866 // A pure texel write (XG CopyIntoSubresource / DirectStorage / slot-31 copy): do NOT invalidate cached
@@ -23811,10 +23872,6 @@ public:
23811 TitleTexture& t = *it->second; 23872 TitleTexture& t = *it->second;
23812 if (t.memory.pending() || t.filled_from != 0 || !t.fills) { 23873 if (t.memory.pending() || t.filled_from != 0 || !t.fills) {
23813 t.memory.retry(); 23874 t.memory.retry();
23814 if (partial_mips() && !t.gpu_written && t.layout_known && !t.stale && t.resource &&
23815 !t.layout_guessed && (!t.fills || t.filled_from) &&
23816 title_texture_readable(t) && (!t.fills || t.readable_from < t.filled_from))
23817 t.stale = true;
23818 } 23875 }
23819 } 23876 }
23820 }; 23877 };
@@ -24227,6 +24284,16 @@ public:
24227 } 24284 }
24228 } 24285 }
24229 24286
24287 // Per-submission budget for unmapped first-time streamed textures and partial-mip upgrades (default 16 MiB;
24288 // 0 = unlimited). Mapped textures (video planes) and already-filled dynamic updates are never deferred.
24289 static const std::uint64_t stream_budget_bytes = [] {
24290 const char* v = std::getenv("LEONIDA_TITLE_STREAM_BUDGET_MB");
24291 const std::uint64_t mb = (v && *v) ? std::strtoull(v, nullptr, 10) : 16ull;
24292 constexpr std::uint64_t kMaxMb = (std::numeric_limits<std::uint64_t>::max)() >> 20;
24293 return mb >= kMaxMb ? (std::numeric_limits<std::uint64_t>::max)() : (mb << 20);
24294 }();
24295 leonida::TitleStreamBudget stream_budget(stream_budget_bytes);
24296
24230 for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { 24297 for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) {
24231 TitleCandidate& cand = title_candidates_[idx]; 24298 TitleCandidate& cand = title_candidates_[idx];
24232 TitleTexture& t = *cand.entry; 24299 TitleTexture& t = *cand.entry;
@@ -24251,12 +24318,18 @@ public:
24251 } 24318 }
24252 const unsigned from = fill_from(t); 24319 const unsigned from = fill_from(t);
24253 const std::uint64_t span = fill_bytes(t); 24320 const std::uint64_t span = fill_bytes(t);
24254 if (from && t.unbound_bytes && title_partial_bytes_ + t.unbound_bytes > partial_mips_budget()) { 24321 if (from && t.unbound_bytes && state_.title_partial_bytes + t.unbound_bytes > partial_mips_budget()) {
24255 ++stats.partial_refused; 24322 ++stats.partial_refused;
24256 t.stale = false; 24323 t.stale = false;
24257 if (have_mirror) title_mirror_checks_[idx].active = false; 24324 if (have_mirror) title_mirror_checks_[idx].active = false;
24258 continue; 24325 continue;
24259 } 24326 }
24327 const bool partial_upgrade = t.fills && from < t.filled_from;
24328 if (!stream_budget.allow(t.mapped, t.fills != 0, partial_upgrade, span)) {
24329 watch.touch(t.address);
24330 if (have_mirror) title_mirror_checks_[idx].active = false;
24331 continue;
24332 }
24260 if (t.unbound_bytes) { 24333 if (t.unbound_bytes) {
24261 const auto back_start = clock::now(); 24334 const auto back_start = clock::now();
24262 bool did_back = false, did_raw = false; 24335 bool did_back = false, did_raw = false;
@@ -24287,7 +24360,7 @@ public:
24287 mc.cpu = t.cpu; 24360 mc.cpu = t.cpu;
24288 mc.gpu = t.address; 24361 mc.gpu = t.address;
24289 mc.bytes = span; 24362 mc.bytes = span;
24290 mc.written_tiles = (allow_filter && !t.stale) ? &ex.written : nullptr; 24363 mc.written_tiles = (allow_filter && !t.stale && t.fills && !partial_upgrade) ? &ex.written : nullptr;
24291 const bool can_tile_cmp = !t.stale && t.fills && !t.gpu_uploaded && from == t.filled_from && 24364 const bool can_tile_cmp = !t.stale && t.fills && !t.gpu_uploaded && from == t.filled_from &&
24292 t.pieces.valid_for(t.cpu, span) && !ex.written.empty() && 24365 t.pieces.valid_for(t.cpu, span) && !ex.written.empty() &&
24293 ex.written.size() <= tiles; 24366 ex.written.size() <= tiles;
@@ -24976,7 +25049,6 @@ private:
24976 std::uint64_t title_map_generation_ = 0; // under title_texture_mutex: the map changes seen 25049 std::uint64_t title_map_generation_ = 0; // under title_texture_mutex: the map changes seen
24977 leonida::TitleWriteRanges title_map_changes_; // likewise, scratch 25050 leonida::TitleWriteRanges title_map_changes_; // likewise, scratch
24978 VkDeviceSize retired_backing_ = 0; 25051 VkDeviceSize retired_backing_ = 0;
24979 VkDeviceSize title_partial_bytes_ = 0; // likewise: image memory of the textures filled in part, as of this pass
24980 std::vector<std::pair<std::chrono::steady_clock::time_point, Resource*>> retired_title_textures_; // likewise 25052 std::vector<std::pair<std::chrono::steady_clock::time_point, Resource*>> retired_title_textures_; // likewise
24981 std::vector<std::uint8_t> title_tiled_, title_linear_; // scratch, under title_texture_mutex 25053 std::vector<std::uint8_t> title_tiled_, title_linear_; // scratch, under title_texture_mutex
24982 std::vector<std::uint64_t> title_columns_; 25054 std::vector<std::uint64_t> title_columns_;
@@ -25178,6 +25250,7 @@ private:
25178 if (reg_addr != address) { 25250 if (reg_addr != address) {
25179 const auto reg_it = textures.find(reg_addr); 25251 const auto reg_it = textures.find(reg_addr);
25180 if (reg_it != textures.end() && reg_it->second->resource == owner && !reg_it->second->owned) { 25252 if (reg_it != textures.end() && reg_it->second->resource == owner && !reg_it->second->owned) {
25253 state_.clear_partial_budget(*reg_it->second);
25181 state_.texture_watch.untrack(reg_addr); 25254 state_.texture_watch.untrack(reg_addr);
25182 textures.erase(reg_it); 25255 textures.erase(reg_it);
25183 } 25256 }
@@ -25224,6 +25297,7 @@ private:
25224 } 25297 }
25225 state_.drop_gpu_owned(evicted->resource); 25298 state_.drop_gpu_owned(evicted->resource);
25226 } 25299 }
25300 state_.clear_partial_budget(*evicted);
25227 evict_incompatible_gpu_owned_at_base(); 25301 evict_incompatible_gpu_owned_at_base();
25228 state_.index_texture(*replacement); 25302 state_.index_texture(*replacement);
25229 static std::atomic<int> evicted_logged{0}; 25303 static std::atomic<int> evicted_logged{0};
@@ -25442,11 +25516,7 @@ private:
25442 // a few seconds later, when no submission can still read it. Only while it still holds the address: a 25516 // a few seconds later, when no submission can still read it. Only while it still holds the address: a
25443 // slot-133 texture placed there since (register_title_texture retires this entry right after the placement 25517 // slot-133 texture placed there since (register_title_texture retires this entry right after the placement
25444 // took the address over) keeps it, or every T# naming the address would find no texture. 25518 // took the address over) keeps it, or every T# naming the address would find no texture.
25445 if (t.partial_budget_counted) { 25519 state_.clear_partial_budget(t);
25446 title_partial_bytes_ =
25447 title_partial_bytes_ >= t.backing_bytes ? title_partial_bytes_ - t.backing_bytes : 0;
25448 t.partial_budget_counted = false;
25449 }
25450 if (t.resource->image_address()) state_.forget_image_of(t.resource->image_address(), t.resource); 25520 if (t.resource->image_address()) state_.forget_image_of(t.resource->image_address(), t.resource);
25451 retired_backing_ += t.resource->image_backing_bytes(); 25521 retired_backing_ += t.resource->image_backing_bytes();
25452 const auto retired_at = std::chrono::steady_clock::now(); 25522 const auto retired_at = std::chrono::steady_clock::now();
@@ -25506,12 +25576,10 @@ private:
25506 title_stats_.partial_textures += from && !t.fills; 25576 title_stats_.partial_textures += from && !t.fills;
25507 title_stats_.partial_upgrades += t.fills && from < t.filled_from; 25577 title_stats_.partial_upgrades += t.fills && from < t.filled_from;
25508 if (from && t.backing_bytes && !t.partial_budget_counted) { 25578 if (from && t.backing_bytes && !t.partial_budget_counted) {
25509 title_partial_bytes_ += t.backing_bytes; 25579 state_.title_partial_bytes += t.backing_bytes;
25510 t.partial_budget_counted = true; 25580 t.partial_budget_counted = true;
25511 } else if (!from && t.partial_budget_counted) { 25581 } else if (!from && t.partial_budget_counted) {
25512 title_partial_bytes_ = 25582 state_.clear_partial_budget(t);
25513 title_partial_bytes_ >= t.backing_bytes ? title_partial_bytes_ - t.backing_bytes : 0;
25514 t.partial_budget_counted = false;
25515 } 25583 }
25516 t.filled_from = from; 25584 t.filled_from = from;
25517 } 25585 }
@@ -25602,7 +25670,7 @@ private:
25602 need_upgrade = true; 25670 need_upgrade = true;
25603 } else if (!t.fills) { 25671 } else if (!t.fills) {
25604 if ((!from || !t.unbound_bytes || 25672 if ((!from || !t.unbound_bytes ||
25605 title_partial_bytes_ + t.unbound_bytes <= partial_mips_budget()) && 25673 state_.title_partial_bytes + t.unbound_bytes <= partial_mips_budget()) &&
25606 back_title_texture(t, nullptr, nullptr, from)) { 25674 back_title_texture(t, nullptr, nullptr, from)) {
25607 if (t.resource && t.resource->deferred_stream()) { 25675 if (t.resource && t.resource->deferred_stream()) {
25608 // On the staged (!host_transfer) path, register_bound_texture() leaves the image in 25676 // On the staged (!host_transfer) path, register_bound_texture() leaves the image in
@@ -25632,7 +25700,7 @@ private:
25632 if (!title_texture_readable(t)) return 0; 25700 if (!title_texture_readable(t)) return 0;
25633 const unsigned from = fill_from(t); 25701 const unsigned from = fill_from(t);
25634 const std::uint64_t span = fill_bytes(t); 25702 const std::uint64_t span = fill_bytes(t);
25635 if (from && t.unbound_bytes && title_partial_bytes_ + t.unbound_bytes > partial_mips_budget()) { 25703 if (from && t.unbound_bytes && state_.title_partial_bytes + t.unbound_bytes > partial_mips_budget()) {
25636 ++title_stats_.partial_refused; 25704 ++title_stats_.partial_refused;
25637 t.stale = false; // the sweep and its views ask again 25705 t.stale = false; // the sweep and its views ask again
25638 return 0; 25706 return 0;
@@ -25712,7 +25780,7 @@ private:
25712 t.mirror_hash_valid = false; 25780 t.mirror_hash_valid = false;
25713 t.set_resource(t.resource); 25781 t.set_resource(t.resource);
25714 if (publish_from && t.backing_bytes && !t.partial_budget_counted) { 25782 if (publish_from && t.backing_bytes && !t.partial_budget_counted) {
25715 title_partial_bytes_ += t.backing_bytes; 25783 state_.title_partial_bytes += t.backing_bytes;
25716 t.partial_budget_counted = true; 25784 t.partial_budget_counted = true;
25717 } 25785 }
25718 return true; 25786 return true;
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index 247bcbdce..0d32d27a9 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -50,6 +50,7 @@
50#include "../src/title_mirror_space.h" 50#include "../src/title_mirror_space.h"
51#include "../src/title_page_watch.h" 51#include "../src/title_page_watch.h"
52#include "../src/title_geometry_watch.h" 52#include "../src/title_geometry_watch.h"
53#include "../src/title_texture_refresh.h"
53#include "../src/title_va_alias.h" 54#include "../src/title_va_alias.h"
54#include "../src/value_write_sink.h" 55#include "../src/value_write_sink.h"
55 56
@@ -453,6 +454,7 @@ struct Section {
453 void* scratch; 454 void* scratch;
454 bool file_backed; 455 bool file_backed;
455 std::vector<uint32_t, leonida::host_heap::Allocator<uint32_t>> frames; 456 std::vector<uint32_t, leonida::host_heap::Allocator<uint32_t>> frames;
457 leonida::PageCommitBits<leonida::host_heap::Allocator<std::uint64_t>> commit_bits;
456 Section(HANDLE h, bool use_file = false); 458 Section(HANDLE h, bool use_file = false);
457 Section(const Section&) = delete; 459 Section(const Section&) = delete;
458 Section& operator=(const Section&) = delete; 460 Section& operator=(const Section&) = delete;
@@ -1539,12 +1541,15 @@ PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& prot
1539 return PageCommit::not_ours; 1541 return PageCommit::not_ours;
1540 } 1542 }
1541 // The fault handler needs the current protection of the accessed host page to decide whether to retry. 1543 // The fault handler needs the current protection of the accessed host page to decide whether to retry.
1544 const size_t page_idx = static_cast<size_t>((it->second.offset + within) / kPhysicalPageSize);
1542 if (sections_committed() || info.State == MEM_COMMIT) { 1545 if (sections_committed() || info.State == MEM_COMMIT) {
1546 it->second.section->commit_bits.mark_committed(page_idx);
1543 protect = info.Protect; 1547 protect = info.Protect;
1544 return PageCommit::committed_before; 1548 return PageCommit::committed_before;
1545 } 1549 }
1546 void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset + within; 1550 void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset + within;
1547 if (!VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return PageCommit::failed; 1551 if (!VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return PageCommit::failed;
1552 it->second.section->commit_bits.mark_committed(page_idx);
1548 leonida::geometry_writes::notify(address, address + kPhysicalPageSize, leonida::geometry_writes::Event::mapping); 1553 leonida::geometry_writes::notify(address, address + kPhysicalPageSize, leonida::geometry_writes::Event::mapping);
1549 leonida::title_memory_map::changed(address, address + kPhysicalPageSize); 1554 leonida::title_memory_map::changed(address, address + kPhysicalPageSize);
1550 return PageCommit::committed_now; 1555 return PageCommit::committed_now;
@@ -2073,6 +2078,7 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count,
2073 std::fprintf(stderr, "[rt] xmem: %llu physical pages, scratch view %p size %llu\n", 2078 std::fprintf(stderr, "[rt] xmem: %llu physical pages, scratch view %p size %llu\n",
2074 static_cast<unsigned long long>(count), section->scratch, static_cast<unsigned long long>(bytes)); 2079 static_cast<unsigned long long>(count), section->scratch, static_cast<unsigned long long>(bytes));
2075 section->frames.resize(count); 2080 section->frames.resize(count);
2081 section->commit_bits.init(static_cast<std::size_t>(count), use_file || sections_committed());
2076 for (uint64_t i = 0; i < count; ++i) { 2082 for (uint64_t i = 0; i < count; ++i) {
2077 uint64_t slot; 2083 uint64_t slot;
2078 if (!g_free_slots.empty()) { 2084 if (!g_free_slots.empty()) {
@@ -3338,6 +3344,27 @@ static bool commit_pages_locked(const uint64_t* page_array, size_t count) {
3338 SetLastError(ERROR_INVALID_PARAMETER); 3344 SetLastError(ERROR_INVALID_PARAMETER);
3339 return false; 3345 return false;
3340 } 3346 }
3347 const bool all_committed = sections_committed();
3348 leonida::host_heap::vector<uintptr_t> notify_vas;
3349 struct NotifyCommitRuns {
3350 leonida::host_heap::vector<uintptr_t>& vas;
3351 ~NotifyCommitRuns() {
3352 if (vas.empty()) return;
3353 // Notify only the exact title VAs currently mapping these newly-committed physical pages (coalesced into
3354 // contiguous runs), never a full-space title_memory_map::changed() that wakes every watched texture and
3355 // invalidates every ShadowPages / VirtualQuery cache across the process.
3356 leonida::coalesce_page_runs(vas, kPhysicalPageSize, [](std::uintptr_t lo, std::uintptr_t hi) {
3357 leonida::geometry_writes::notify(lo, hi, leonida::geometry_writes::Event::mapping);
3358 leonida::title_memory_map::changed(lo, hi);
3359 });
3360 }
3361 } notify_guard{notify_vas};
3362 const auto collect_page_vas = [&](uint64_t page) {
3363 if (const auto mapped = g_page_addresses.find(page); mapped != g_page_addresses.end())
3364 for (const uintptr_t va : mapped->second) notify_vas.push_back(va);
3365 if (const auto tables = g_page_tables.find(page); tables != g_page_tables.end())
3366 for (const uintptr_t va : tables->second) notify_vas.push_back(va);
3367 };
3341 size_t first = 0; 3368 size_t first = 0;
3342 while (first < count) { 3369 while (first < count) {
3343 const auto it = g_pages.find(page_array[first]); 3370 const auto it = g_pages.find(page_array[first]);
@@ -3345,10 +3372,18 @@ static bool commit_pages_locked(const uint64_t* page_array, size_t count) {
3345 SetLastError(ERROR_INVALID_PARAMETER); 3372 SetLastError(ERROR_INVALID_PARAMETER);
3346 return false; 3373 return false;
3347 } 3374 }
3348 if (sections_committed()) { 3375 if (all_committed) {
3349 ++first; // Already committed, but transfer_physical still needs every page number validated. 3376 ++first; // Already committed, but transfer_physical still needs every page number validated.
3350 continue; 3377 continue;
3351 } 3378 }
3379 Section& sec = *it->second.section;
3380 const size_t idx0 = static_cast<size_t>(it->second.offset / kPhysicalPageSize);
3381 if (sec.file_backed || sec.commit_bits.is_committed(idx0)) {
3382 if (!sec.file_backed && sec.commit_bits.mark_committed_and_notified(idx0))
3383 collect_page_vas(page_array[first]);
3384 ++first;
3385 continue;
3386 }
3352 size_t last = first + 1; 3387 size_t last = first + 1;
3353 while (last < count) { 3388 while (last < count) {
3354 const auto next = g_pages.find(page_array[last]); 3389 const auto next = g_pages.find(page_array[last]);
@@ -3356,12 +3391,16 @@ static bool commit_pages_locked(const uint64_t* page_array, size_t count) {
3356 next->second.offset != it->second.offset + (last - first) * kPhysicalPageSize) { 3391 next->second.offset != it->second.offset + (last - first) * kPhysicalPageSize) {
3357 break; 3392 break;
3358 } 3393 }
3394 const size_t next_idx = static_cast<size_t>(next->second.offset / kPhysicalPageSize);
3395 if (sec.commit_bits.is_committed(next_idx)) break;
3359 ++last; 3396 ++last;
3360 } 3397 }
3361 void* const backing = static_cast<uint8_t*>(it->second.section->scratch) + it->second.offset; 3398 void* const backing = static_cast<uint8_t*>(sec.scratch) + it->second.offset;
3362 if (!it->second.section->file_backed && !VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; 3399 if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false;
3363 // Committing the scratch backing affects every title alias. Their addresses are unknown here. 3400 for (size_t k = first; k < last; ++k) {
3364 leonida::title_memory_map::changed(); 3401 if (sec.commit_bits.mark_committed_and_notified(idx0 + (k - first)))
3402 collect_page_vas(page_array[k]);
3403 }
3365 first = last; 3404 first = last;
3366 } 3405 }
3367 return true; 3406 return true;
diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h
index 7681ab899..bdae70c35 100644
--- a/runtime/src/title_geometry_watch.h
+++ b/runtime/src/title_geometry_watch.h
@@ -4,6 +4,7 @@
4#include <algorithm> 4#include <algorithm>
5#include <array> 5#include <array>
6#include <cstdint> 6#include <cstdint>
7#include <cstring>
7#include <vector> 8#include <vector>
8 9
9namespace leonida::geometry_writes { 10namespace leonida::geometry_writes {
@@ -336,7 +337,8 @@ inline void release(std::uintptr_t va, bool was_hot = false) {
336 } 337 }
337 // A page reopened here may also be one a slot-133 shadow keeps read-only (both guard the title's geometry): 338 // A page reopened here may also be one a slot-133 shadow keeps read-only (both guard the title's geometry):
338 // it is writable now with no fault to tell that shadow, which then walks its pages again. 339 // it is writable now with no fault to tell that shadow, which then walks its pages again.
339 if (reopen(va, c)) title_memory_map::changed(va, va + tile_size); 340 const std::uintptr_t tile_end = va <= UINTPTR_MAX - tile_size ? va + tile_size : UINTPTR_MAX;
341 if (reopen(va, c)) title_memory_map::changed(va, tile_end);
340 s.cells.erase(it); 342 s.cells.erase(it);
341 s.count.store(s.cells.size(), std::memory_order_release); 343 s.count.store(s.cells.size(), std::memory_order_release);
342 return; 344 return;
@@ -487,6 +489,70 @@ inline bool notify(std::uintptr_t begin, std::uintptr_t end, Event event, bool*
487 return opened; 489 return opened;
488} 490}
489 491
492// Queries whether each of `count` consecutive 4 KiB pages starting at `first_page` is currently armed read-only by a
493// live, non-hot Cell in this watch with a ShadowPages-compatible writable base protection (`PAGE_READWRITE` or
494// `PAGE_EXECUTE_READWRITE`, excluding `PAGE_GUARD` and copy-on-write pages). Allocates nothing and holds State::mutex
495// once. Used by ShadowPages::guard_read_only() so pages armed by TitleTextureCells/GeometryViews/TitleMirror adopt
496// kProtected instead of being recopied as Copy::read_only on every submission.
497inline void query_pages_guarded(std::uintptr_t first_page, std::size_t count, std::uint8_t* out) {
498 if (!count) return;
499 auto& s = state();
500 if (!s.count.load(std::memory_order_acquire)) {
501 std::memset(out, 0, count);
502 return;
503 }
504 std::lock_guard lock(s.mutex);
505 auto it = s.cells.lower_bound(first_page & ~(tile_size - 1));
506 for (std::size_t k = 0; k < count; ++k) {
507 const std::uintptr_t p = first_page + k * page_size;
508 if (k > 0 && p < first_page) {
509 std::memset(out + k, 0, count - k);
510 break;
511 }
512 const std::uintptr_t tile = p & ~(tile_size - 1);
513 while (it != s.cells.end() && it->first < tile) ++it;
514 bool guarded = false;
515 if (it != s.cells.end() && it->first == tile && !it->second.hot) {
516 const DWORD r = it->second.restore[(p - tile) / page_size];
517 const DWORD base = r & 0xffu;
518 guarded = !(r & PAGE_GUARD) && (base == PAGE_READWRITE || base == PAGE_EXECUTE_READWRITE);
519 }
520 out[k] = guarded ? 1 : 0;
521 }
522}
523
524// Called when an external guard owner (ShadowPages::reopen_locked) restored write access to [begin, end): clears
525// Cell::restore[] on those sub-pages and armed_map_gen so TitleTextureCells::arm_batch()'s zero-syscall all_armed
526// check never treats now-writable pages as still armed, bumps Cell::version, and queues subscribers without bumping
527// Cell::mapping.
528inline void note_external_reopen(std::uintptr_t begin, std::uintptr_t end) {
529 auto& s = state();
530 if (!s.count.load(std::memory_order_acquire) || end <= begin) return;
531 std::lock_guard lock(s.mutex);
532 auto it = s.cells.lower_bound(begin & ~(tile_size - 1));
533 if (it == s.cells.end() || it->first >= end) return;
534 const auto version = s.serial.load(std::memory_order_relaxed) + 1;
535 for (; it != s.cells.end() && it->first < end; ++it) {
536 auto& cell = it->second;
537 cell.armed_map_gen = Cell::kNoMapGen;
538 for (unsigned i = 0; i < cell.restore.size(); ++i) {
539 const auto p = it->first + i * page_size;
540 if (p < end && p + page_size > begin) cell.restore[i] = 0;
541 }
542 cell.version.store(version, std::memory_order_release);
543 for (WriteQueue* q : s.writers) {
544 std::lock_guard queue_lock(q->mutex);
545 if (q->overflow) continue;
546 if (q->tiles.size() < WriteQueue::kMaxTiles)
547 q->tiles.push_back(it->first);
548 else
549 q->overflow = true, q->tiles.clear();
550 q->pending.store(true, std::memory_order_release);
551 }
552 }
553 s.serial.store(version, std::memory_order_release);
554}
555
490// The tile at `va` is hot for one more owner (`hot`) or one fewer: while any owner holds it hot, its guard is off and 556// The tile at `va` is hot for one more owner (`hot`) or one fewer: while any owner holds it hot, its guard is off and
491// it is not armed again, and hot_tiles() lists it for every subscriber. The cell must be acquired. 557// it is not armed again, and hot_tiles() lists it for every subscriber. The cell must be acquired.
492inline void set_hot(std::uintptr_t va, bool hot) { 558inline void set_hot(std::uintptr_t va, bool hot) {
@@ -497,7 +563,14 @@ inline void set_hot(std::uintptr_t va, bool hot) {
497 Cell& c = it->second; 563 Cell& c = it->second;
498 if (hot) { 564 if (hot) {
499 if (c.hot++) return; 565 if (c.hot++) return;
500 reopen(va, c); 566 // Bump Cell::version so already-armed ShadowPages::update_aliased() blocks see the peer transitioned to hot
567 // and stop treating it as clean (no WriteQueue push needed: subscribers poll hot_tiles()).
568 const auto version = s.serial.load(std::memory_order_relaxed) + 1;
569 c.version.store(version, std::memory_order_release);
570 s.serial.store(version, std::memory_order_release);
571 // A page reopened here may also be one a slot-133 shadow treats as guarded: tell shadows to requery it.
572 const std::uintptr_t tile_end = va <= UINTPTR_MAX - tile_size ? va + tile_size : UINTPTR_MAX;
573 if (reopen(va, c)) title_memory_map::changed(va, tile_end);
501 s.hot.push_back(va); 574 s.hot.push_back(va);
502 } else { 575 } else {
503 if (!c.hot || --c.hot) return; 576 if (!c.hot || --c.hot) return;
@@ -533,16 +606,36 @@ inline void set_hot_batch(const std::uintptr_t* vas, std::size_t count, bool hot
533 std::lock_guard lock(s.mutex); 606 std::lock_guard lock(s.mutex);
534 bool hot_changed = false; 607 bool hot_changed = false;
535 if (hot) { 608 if (hot) {
609 const auto version = s.serial.load(std::memory_order_relaxed) + 1;
610 std::uintptr_t reopened_lo = 0, reopened_hi = 0;
611 const auto flush_reopened = [&] {
612 if (reopened_lo < reopened_hi) {
613 title_memory_map::changed(reopened_lo, reopened_hi);
614 reopened_lo = reopened_hi = 0;
615 }
616 };
536 for (std::size_t i = 0; i < count; ++i) { 617 for (std::size_t i = 0; i < count; ++i) {
537 const std::uintptr_t va = vas[i]; 618 const std::uintptr_t va = vas[i];
538 const auto it = s.cells.find(va); 619 const auto it = s.cells.find(va);
539 if (it == s.cells.end()) continue; 620 if (it == s.cells.end()) continue;
540 Cell& c = it->second; 621 Cell& c = it->second;
541 if (c.hot++) continue; 622 if (c.hot++) continue;
542 reopen(va, c); 623 c.version.store(version, std::memory_order_release);
624 if (reopen(va, c)) {
625 const std::uintptr_t tile_end = va <= UINTPTR_MAX - tile_size ? va + tile_size : UINTPTR_MAX;
626 if (reopened_lo < reopened_hi && va == reopened_hi) {
627 reopened_hi = tile_end;
628 } else {
629 flush_reopened();
630 reopened_lo = va;
631 reopened_hi = tile_end;
632 }
633 }
543 s.hot.push_back(va); 634 s.hot.push_back(va);
544 hot_changed = true; 635 hot_changed = true;
545 } 636 }
637 if (hot_changed) s.serial.store(version, std::memory_order_release);
638 flush_reopened();
546 } else { 639 } else {
547 host_heap::vector<std::uintptr_t> cooled; 640 host_heap::vector<std::uintptr_t> cooled;
548 cooled.reserve(count); 641 cooled.reserve(count);
@@ -597,15 +690,16 @@ inline void hot_tiles(Out& out) {
597} 690}
598 691
599// Arm under the same lock as the write-fault path. A kernel destination may only be guarded again after its pin ends. 692// Arm under the same lock as the write-fault path. A kernel destination may only be guarded again after its pin ends.
600// A hot cell is not protected (true: its writes reach every subscriber through hot_tiles()). 693// A hot cell is not protected (`allow_hot == true`: returns true because subscribers like TitleTextureWatch poll
601inline bool arm(std::uintptr_t va, Cell& c) { 694// hot_tiles(); callers that do NOT poll hot_tiles(), such as ShadowPages::update_aliased(), pass `allow_hot = false`).
695inline bool arm(std::uintptr_t va, Cell& c, bool allow_hot = true) {
602 auto& s = state(); 696 auto& s = state();
603 // Querying an OVERLAPPED can fault into xmem. Never do it with the watch lock held. 697 // Querying an OVERLAPPED can fault into xmem. Never do it with the watch lock held.
604 const auto version = c.version.load(std::memory_order_acquire); 698 const auto version = c.version.load(std::memory_order_acquire);
605 bool pinned = false; 699 bool pinned = false;
606 kernel_writes::for_each_pin(va, va + tile_size, [&](auto, auto) { pinned = true; }); 700 kernel_writes::for_each_pin(va, va + tile_size, [&](auto, auto) { pinned = true; });
607 std::lock_guard lock(s.mutex); 701 std::lock_guard lock(s.mutex);
608 if (c.hot) return true; 702 if (c.hot) return allow_hot;
609 if (pinned || version != c.version.load(std::memory_order_relaxed)) return false; 703 if (pinned || version != c.version.load(std::memory_order_relaxed)) return false;
610 c.armed_map_gen = Cell::kNoMapGen; 704 c.armed_map_gen = Cell::kNoMapGen;
611 for (std::size_t i = 0; i < c.restore.size();) { 705 for (std::size_t i = 0; i < c.restore.size();) {
diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h
index 30ae34234..8b1a9a00e 100644
--- a/runtime/src/title_texture_refresh.h
+++ b/runtime/src/title_texture_refresh.h
@@ -2,11 +2,14 @@
2#include "shadow_keep.h" 2#include "shadow_keep.h"
3 3
4#include <algorithm> 4#include <algorithm>
5#include <atomic>
5#include <bit> 6#include <bit>
6#include <cmath> 7#include <cmath>
7#include <cstdint> 8#include <cstdint>
8#include <deque> 9#include <deque>
10#include <limits>
9#include <map> 11#include <map>
12#include <memory>
10#include <utility> 13#include <utility>
11#include <vector> 14#include <vector>
12 15
@@ -414,4 +417,129 @@ inline std::uint32_t effective_min_mip(std::uint32_t first_mip, float min_lod) {
414 return (std::max)(first_mip, static_cast<std::uint32_t>(std::floor(min_lod))); 417 return (std::max)(first_mip, static_cast<std::uint32_t>(std::floor(min_lod)));
415} 418}
416 419
420// Per-submission streaming upload budget for unmapped first-time streamed textures and partial-mip upgrades.
421// Never defers CPU-mapped textures (e.g. multi-plane video frames that must land together), already-filled dynamic
422// texel updates (from == filled_from), or the first streamed texture of a pass (guaranteeing forward progress for
423// arbitrarily large textures and single-texture tests). Partial-mip upgrades already have valid lower mips clamped via
424// VK_EXT_image_view_min_lod, so they use half the stream budget to coalesce mip-by-mip arrivals across frames.
425class TitleStreamBudget {
426public:
427 explicit TitleStreamBudget(std::uint64_t budget_bytes) noexcept : budget_bytes_(budget_bytes) {}
428
429 bool allow(bool mapped, bool already_filled, bool partial_upgrade, std::uint64_t span) noexcept {
430 if (mapped) return true;
431 if (already_filled && !partial_upgrade) return true;
432 if (!budget_bytes_) return true;
433 const std::uint64_t limit = partial_upgrade ? (budget_bytes_ > 1 ? budget_bytes_ / 2 : 1) : budget_bytes_;
434 if (scheduled_bytes_ > 0 && (span > limit || scheduled_bytes_ > limit - span)) return false;
435 scheduled_bytes_ += span;
436 return true;
437 }
438
439 std::uint64_t scheduled_bytes() const noexcept { return scheduled_bytes_; }
440 std::uint64_t budget_bytes() const noexcept { return budget_bytes_; }
441
442private:
443 std::uint64_t budget_bytes_ = 0;
444 std::uint64_t scheduled_bytes_ = 0;
445};
446
447// Sorts, deduplicates, and coalesces page-aligned addresses into contiguous half-open [lo, hi) runs of `page_size`
448// bytes, emitting each run via `emit(lo, hi)`. Used by xmem::commit_pages_locked() to notify only affected title VAs.
449template<class Alloc, class Emit>
450void coalesce_page_runs(std::vector<std::uintptr_t, Alloc>& pages, std::uintptr_t page_size, Emit&& emit) {
451 if (pages.empty() || !page_size) return;
452 if (pages.size() > 1) {
453 std::sort(pages.begin(), pages.end());
454 pages.erase(std::unique(pages.begin(), pages.end()), pages.end());
455 }
456 constexpr std::uintptr_t kMax = (std::numeric_limits<std::uintptr_t>::max)();
457 for (std::size_t i = 0; i < pages.size();) {
458 const std::uintptr_t lo = pages[i];
459 std::uintptr_t hi = lo <= kMax - page_size ? lo + page_size : kMax;
460 ++i;
461 while (i < pages.size() && pages[i] == hi) {
462 hi = hi <= kMax - page_size ? hi + page_size : kMax;
463 ++i;
464 }
465 if (lo < hi) emit(lo, hi);
466 }
467}
468
469// Lock-free 2-bit-per-page commit/notification tracker for physical-page sections (xmem.cpp).
470// Bit 0 (`kCommitted`): scratch backing is committed in host memory.
471// Bit 1 (`kNotified`): all mapped/table VAs of this page have been notified via title_memory_map::changed(lo, hi).
472// Template Alloc allows xmem.cpp to back the word array from leonida::host_heap so fault-path callers never touch
473// the process heap.
474template<class Alloc = std::allocator<std::uint64_t>>
475class PageCommitBits {
476 using Word = std::atomic<std::uint64_t>;
477 using WordAlloc = typename std::allocator_traits<Alloc>::template rebind_alloc<Word>;
478 using WordTraits = std::allocator_traits<WordAlloc>;
479
480public:
481 PageCommitBits() = default;
482 ~PageCommitBits() { reset(); }
483 PageCommitBits(const PageCommitBits&) = delete;
484 PageCommitBits& operator=(const PageCommitBits&) = delete;
485
486 void init(std::size_t page_count, bool all_committed) {
487 reset();
488 if (!page_count) return;
489 const std::size_t words = (page_count - 1u) / 32u + 1u;
490 WordAlloc alloc;
491 Word* const mem = WordTraits::allocate(alloc, words);
492 const std::uint64_t fill = all_committed ? ~std::uint64_t(0) : std::uint64_t(0);
493 for (std::size_t i = 0; i < words; ++i) WordTraits::construct(alloc, mem + i, fill);
494 words_ = mem;
495 word_count_ = words;
496 page_count_ = page_count;
497 }
498
499 void reset() noexcept {
500 if (!words_) return;
501 WordAlloc alloc;
502 for (std::size_t i = 0; i < word_count_; ++i) WordTraits::destroy(alloc, words_ + i);
503 WordTraits::deallocate(alloc, words_, word_count_);
504 words_ = nullptr;
505 word_count_ = 0;
506 page_count_ = 0;
507 }
508
509 std::size_t size() const noexcept { return page_count_; }
510
511 bool is_committed(std::size_t idx) const noexcept {
512 if (idx >= page_count_) return false;
513 const std::uint64_t mask = std::uint64_t(1) << ((idx & 31u) * 2u);
514 return (words_[idx >> 5].load(std::memory_order_acquire) & mask) != 0;
515 }
516
517 bool is_notified(std::size_t idx) const noexcept {
518 if (idx >= page_count_) return false;
519 const std::uint64_t mask = std::uint64_t(2) << ((idx & 31u) * 2u);
520 return (words_[idx >> 5].load(std::memory_order_acquire) & mask) != 0;
521 }
522
523 // Marks page `idx` committed. Returns true if it transitioned from uncommitted -> committed.
524 bool mark_committed(std::size_t idx) noexcept {
525 if (idx >= page_count_) return false;
526 const std::uint64_t mask = std::uint64_t(1) << ((idx & 31u) * 2u);
527 return (words_[idx >> 5].fetch_or(mask, std::memory_order_acq_rel) & mask) == 0;
528 }
529
530 // Marks page `idx` both committed and notified. Returns true iff `kNotified` transitioned 0 -> 1.
531 bool mark_committed_and_notified(std::size_t idx) noexcept {
532 if (idx >= page_count_) return false;
533 const unsigned shift = static_cast<unsigned>((idx & 31u) * 2u);
534 const std::uint64_t both = std::uint64_t(3) << shift;
535 const std::uint64_t notified = std::uint64_t(2) << shift;
536 return (words_[idx >> 5].fetch_or(both, std::memory_order_acq_rel) & notified) == 0;
537 }
538
539private:
540 Word* words_ = nullptr;
541 std::size_t word_count_ = 0;
542 std::size_t page_count_ = 0;
543};
544
417} // namespace leonida 545} // namespace leonida
diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp
index 735784932..01011b3ef 100644
--- a/runtime/test/d3d12_existing_heap_test.cpp
+++ b/runtime/test/d3d12_existing_heap_test.cpp
@@ -3646,6 +3646,169 @@ void print_cases(const std::vector<Case>& cases, const char* who) {
3646} 3646}
3647} // namespace 3647} // namespace
3648 3648
3649// Regression for PR #2566 shadow Copy::read_only loop & geometry_writes/ShadowPages coherence:
3650// 1. Non-aliased ShadowPages adopts kProtected on a geometry_writes-armed 64 KiB tile (skipping it on clean passes:
3651// 1 query for only the reserved tail instead of 2) while catching writes via fault + re-adoption.
3652// 2. set_hot(tile, true) wakes adopted ShadowPages via title_memory_map::changed() so writes without faulting reach
3653// the GPU; cooling + re-arming resumes clean-pass skipping.
3654// 3. ShadowPages destruction calls note_external_reopen(), clearing Cell::restore[] on reopened pages.
3655// 4. set_hot(peer, true) on an aliased peer bumps Cell::version so already-armed ShadowPages::update_aliased() stops
3656// treating the aliased block as clean and copies writes made through the hot peer.
3657int check_shadow_adopts_geometry_guard(ID3D12Device* device) {
3658 const char* who = "vulkan slot-133 shadow adopts geometry_writes read-only guard";
3659 {
3660 constexpr SIZE_T committed = 0x10000;
3661 constexpr SIZE_T size = 2 * committed; // reserved second half forces a shadow buffer instead of a host import
3662 auto* pages = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE));
3663 bool acquired = false;
3664 bool is_hot = false;
3665 const auto tile = reinterpret_cast<std::uintptr_t>(pages);
3666 struct Guard {
3667 std::uintptr_t tile;
3668 std::uint8_t* pages;
3669 bool& acquired;
3670 bool& is_hot;
3671 ~Guard() {
3672 if (acquired) {
3673 if (is_hot) leonida::geometry_writes::set_hot(tile, false);
3674 leonida::geometry_writes::release(tile);
3675 }
3676 if (pages) VirtualFree(pages, 0, MEM_RELEASE);
3677 }
3678 } guard{tile, pages, acquired, is_hot};
3679 EXPECT(pages != nullptr && VirtualAlloc(pages, committed, MEM_COMMIT, PAGE_READWRITE) == pages);
3680 std::vector<std::uint8_t> want(size, 0), got;
3681 for (SIZE_T i = 0; i < committed; ++i) want[i] = pages[i] = pattern_byte(i, 73);
3682 // Arm the committed 64 KiB tile via geometry_writes BEFORE placing the shadow buffer (simulating
3683 // TitleTextureCells running ahead of ShadowPages::refresh()).
3684 auto* cell = leonida::geometry_writes::acquire(tile);
3685 EXPECT(cell != nullptr);
3686 acquired = true;
3687 EXPECT(leonida::geometry_writes::arm(tile, *cell));
3688 EXPECT((protection_of(pages) & 0xff) == PAGE_READONLY);
3689 {
3690 Ref<ID3D12Resource> buffer;
3691 buffer.p = place_shadow(device, pages, size);
3692 EXPECT(buffer.p != nullptr);
3693 GpuReader reader;
3694 if (reader.init(device, size)) return 1;
3695 // First submission copies the initial bytes and adopts kProtected on the geometry_writes-guarded tile.
3696 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3697 // Second clean submission skips the committed tile (only the reserved second half is queried: 1 query, not 2).
3698 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3699 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1);
3700 // A write to the shared tile faults through geometry_writes + ShadowPages::reopen_range(), re-arms via
3701 // geometry_writes ahead of refresh_shadows(), and reaches the GPU on the next submission.
3702 for (SIZE_T i = 0x1000; i < 0x2000; ++i) want[i] = pages[i] = pattern_byte(i, 199);
3703 EXPECT(leonida::geometry_writes::arm(tile, *cell));
3704 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3705 // After re-adopting kProtected, the following clean submission again skips the committed tile.
3706 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3707 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1);
3708 // Marking the tile hot reopens it without a write fault and notifies title_memory_map::changed():
3709 // adopted ShadowPages must requery and copy writes made while hot.
3710 leonida::geometry_writes::set_hot(tile, true);
3711 is_hot = true;
3712 EXPECT((protection_of(pages) & 0xff) == PAGE_READWRITE);
3713 for (SIZE_T i = 0x2000; i < 0x3000; ++i) want[i] = pages[i] = pattern_byte(i, 41);
3714 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3715 // Cooling and re-arming returns to clean-pass skipping.
3716 leonida::geometry_writes::set_hot(tile, false);
3717 is_hot = false;
3718 EXPECT(leonida::geometry_writes::arm(tile, *cell));
3719 EXPECT((protection_of(pages) & 0xff) == PAGE_READONLY);
3720 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3721 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3722 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1);
3723 }
3724 // ShadowPages destruction reopened the adopted tile and called note_external_reopen(), clearing Cell::restore[].
3725 EXPECT((protection_of(pages) & 0xff) == PAGE_READWRITE);
3726 std::uint8_t gw[16]{};
3727 leonida::geometry_writes::query_pages_guarded(tile, 16, gw);
3728 for (std::uint8_t v : gw) EXPECT(v == 0);
3729 {
3730 std::lock_guard lock(leonida::geometry_writes::state().mutex);
3731 for (const DWORD r : cell->restore) EXPECT(r == 0);
3732 }
3733 }
3734 // Aliased-peer set_hot(peer, true): bumping Cell::version invalidates already-armed ShadowPages::update_aliased().
3735 {
3736 constexpr SIZE_T size = 4 * 0x10000;
3737 constexpr UINT64 committed = size / 2, block = 0x10000;
3738 HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0,
3739 DWORD(size), nullptr);
3740 std::uint8_t* a = nullptr;
3741 std::uint8_t* b = nullptr;
3742 bool aliases_on = false;
3743 bool peer_acquired = false;
3744 bool peer_hot = false;
3745 std::uintptr_t peer_va = 0;
3746 struct AliasGuard {
3747 HANDLE& section;
3748 std::uint8_t*& a;
3749 std::uint8_t*& b;
3750 bool& aliases_on;
3751 bool& peer_acquired;
3752 bool& peer_hot;
3753 std::uintptr_t& peer_va;
3754 ~AliasGuard() {
3755 if (peer_acquired) {
3756 if (peer_hot) leonida::geometry_writes::set_hot(peer_va, false);
3757 leonida::geometry_writes::release(peer_va);
3758 }
3759 if (aliases_on) {
3760 leonida::title_page_aliases::set(g_alias_a + block, false);
3761 leonida::title_page_aliases::set(g_alias_b + block, false);
3762 leonida::geometry_writes::aliases.store(nullptr, std::memory_order_release);
3763 }
3764 if (a) UnmapViewOfFile(a);
3765 if (b) UnmapViewOfFile(b);
3766 if (section) CloseHandle(section);
3767 }
3768 } alias_guard{section, a, b, aliases_on, peer_acquired, peer_hot, peer_va};
3769 EXPECT(section != nullptr);
3770 a = static_cast<std::uint8_t*>(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size));
3771 b = static_cast<std::uint8_t*>(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size));
3772 EXPECT(a != nullptr && b != nullptr);
3773 EXPECT(VirtualAlloc(a, committed, MEM_COMMIT, PAGE_READWRITE) == a);
3774 EXPECT(VirtualAlloc(b, committed, MEM_COMMIT, PAGE_READWRITE) == b);
3775 g_alias_a = reinterpret_cast<std::uintptr_t>(a);
3776 g_alias_b = reinterpret_cast<std::uintptr_t>(b);
3777 peer_va = g_alias_b + block;
3778 leonida::geometry_writes::aliases.store(&aliases_of_test_views, std::memory_order_release);
3779 leonida::title_page_aliases::set(g_alias_a + block, true);
3780 leonida::title_page_aliases::set(g_alias_b + block, true);
3781 aliases_on = true;
3782 {
3783 Ref<ID3D12Resource> buffer;
3784 buffer.p = place_shadow(device, a, size);
3785 EXPECT(buffer.p != nullptr);
3786 GpuReader reader;
3787 if (reader.init(device, size)) return 1;
3788 std::vector<std::uint8_t> want(size, 0), got;
3789 for (UINT64 i = 0; i < committed; ++i) want[i] = a[i] = pattern_byte(i, 31);
3790 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3791 EXPECT((protection_of(a + block) & 0xff) == PAGE_READONLY);
3792 EXPECT((protection_of(b + block) & 0xff) == PAGE_READONLY);
3793 // Peer B becomes hot while shadow's aliased block is armed: writes through B must still reach GPU.
3794 EXPECT(leonida::geometry_writes::acquire(peer_va) != nullptr);
3795 peer_acquired = true;
3796 leonida::geometry_writes::set_hot(peer_va, true);
3797 peer_hot = true;
3798 EXPECT((protection_of(b + block) & 0xff) == PAGE_READWRITE);
3799 for (UINT64 i = block + 0x1000; i < block + 0x1800; ++i) want[i] = b[i] = pattern_byte(i, 211);
3800 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3801 // Cooling peer B lets ShadowPages re-arm it on the next submission.
3802 leonida::geometry_writes::set_hot(peer_va, false);
3803 peer_hot = false;
3804 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3805 EXPECT((protection_of(b + block) & 0xff) == PAGE_READONLY);
3806 }
3807 }
3808 std::printf("%s: ok\n", who);
3809 return 0;
3810}
3811
3649int main(int argc, char** argv) { 3812int main(int argc, char** argv) {
3650 const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; 3813 const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0;
3651 const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0; 3814 const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0;
@@ -3757,6 +3920,7 @@ int main(int argc, char** argv) {
3757 failures += check_mapped_bc_array(staged.p); 3920 failures += check_mapped_bc_array(staged.p);
3758 } 3921 }
3759 failures += check_written_pages_all(ours.p); 3922 failures += check_written_pages_all(ours.p);
3923 failures += check_shadow_adopts_geometry_guard(ours.p);
3760 { 3924 {
3761 // A second device over the same Vulkan device: its shadows are trackers of their own. 3925 // A second device over the same Vulkan device: its shadows are trackers of their own.
3762 Ref<ID3D12Device> second; 3926 Ref<ID3D12Device> second;
diff --git a/runtime/test/title_texture_refresh_test.cpp b/runtime/test/title_texture_refresh_test.cpp
index d1b4e08a0..e19feb4b0 100644
--- a/runtime/test/title_texture_refresh_test.cpp
+++ b/runtime/test/title_texture_refresh_test.cpp
@@ -154,6 +154,110 @@ int main() {
154 CHECK(effective_min_mip(100, inf) == 100u); 154 CHECK(effective_min_mip(100, inf) == 100u);
155 } 155 }
156 156
157 // 5. TitleStreamBudget: bounds unmapped first-time streamed bursts and partial-mip upgrades without ever deferring
158 // mapped textures (video planes), already-filled dynamic updates, or the first streamed texture of a pass.
159 {
160 constexpr std::uint64_t kMiB = 1ull << 20;
161 TitleStreamBudget budget(16 * kMiB);
162
163 // First streamed texture always allowed even if larger than the whole budget (forward progress).
164 CHECK(budget.allow(/*mapped=*/false, /*already_filled=*/false, /*partial_upgrade=*/false, 20 * kMiB));
165 CHECK(budget.scheduled_bytes() == 20 * kMiB);
166 // Second unmapped first-time texture is deferred once budget is exceeded.
167 CHECK(!budget.allow(false, false, false, 1 * kMiB));
168 // Mapped textures and already-filled dynamic updates are NEVER deferred.
169 CHECK(budget.allow(/*mapped=*/true, false, false, 64 * kMiB));
170 CHECK(budget.allow(/*mapped=*/false, /*already_filled=*/true, /*partial_upgrade=*/false, 64 * kMiB));
171 // Overflow-safe check with UINT64_MAX span.
172 CHECK(!budget.allow(false, false, false, UINT64_MAX));
173
174 // Partial-mip upgrades use half the budget (8 MiB) so mip-by-mip arrivals coalesce across frames.
175 TitleStreamBudget partial(16 * kMiB);
176 CHECK(partial.allow(false, true, true, 5 * kMiB));
177 CHECK(partial.allow(false, true, true, 3 * kMiB)); // total 8 MiB == limit
178 CHECK(!partial.allow(false, true, true, 1)); // 8 MiB + 1 > 8 MiB -> deferred
179 // First-time streamed textures still get the remaining 8 MiB of the 16 MiB budget.
180 CHECK(partial.allow(false, false, false, 8 * kMiB));
181 CHECK(!partial.allow(false, false, false, 1));
182
183 // Budget == 1 byte with partial_upgrade == true still clamps limit to 1 (never 0).
184 TitleStreamBudget tiny(1);
185 CHECK(tiny.allow(false, true, true, 1));
186 CHECK(!tiny.allow(false, true, true, 1));
187
188 // Budget == 0 disables budgeting completely.
189 TitleStreamBudget unlimited(0);
190 CHECK(unlimited.allow(false, false, false, 128 * kMiB));
191 CHECK(unlimited.allow(false, false, false, 128 * kMiB));
192 CHECK(unlimited.allow(false, true, true, 128 * kMiB));
193 }
194
195 // 6. coalesce_page_runs: deduplicates, sorts, and merges contiguous 64 KiB page runs without overflowing UINTPTR_MAX.
196 {
197 constexpr std::uintptr_t kPage = 0x10000;
198 std::vector<std::uintptr_t> empty;
199 std::vector<std::pair<std::uintptr_t, std::uintptr_t>> runs;
200 coalesce_page_runs(empty, kPage, [&](std::uintptr_t lo, std::uintptr_t hi) { runs.emplace_back(lo, hi); });
201 CHECK(runs.empty());
202
203 // page_size == 0 emits nothing.
204 std::vector<std::uintptr_t> zero_sz = {0x10000};
205 coalesce_page_runs(zero_sz, 0, [&](std::uintptr_t lo, std::uintptr_t hi) { runs.emplace_back(lo, hi); });
206 CHECK(runs.empty());
207
208 // Single page emits one [lo, lo + page_size) run.
209 std::vector<std::uintptr_t> single = {0x30000};
210 coalesce_page_runs(single, kPage, [&](std::uintptr_t lo, std::uintptr_t hi) { runs.emplace_back(lo, hi); });
211 CHECK(runs.size() == 1 && runs[0] == std::make_pair(std::uintptr_t{0x30000}, std::uintptr_t{0x40000}));
212
213 runs.clear();
214 std::vector<std::uintptr_t> pages = {0x40000, 0x10000, 0x20000, 0x20000, 0x80000, 0x30000};
215 coalesce_page_runs(pages, kPage, [&](std::uintptr_t lo, std::uintptr_t hi) { runs.emplace_back(lo, hi); });
216 CHECK(runs.size() == 2);
217 CHECK(runs[0] == std::make_pair(std::uintptr_t{0x10000}, std::uintptr_t{0x50000}));
218 CHECK(runs[1] == std::make_pair(std::uintptr_t{0x80000}, std::uintptr_t{0x90000}));
219
220 // Near-UINTPTR_MAX clamping without wraparound; UINTPTR_MAX itself never emits an empty [kMax, kMax) run.
221 runs.clear();
222 const std::uintptr_t top = UINTPTR_MAX - 0x4000;
223 std::vector<std::uintptr_t> hi_pages = {top};
224 coalesce_page_runs(hi_pages, kPage, [&](std::uintptr_t lo, std::uintptr_t hi) { runs.emplace_back(lo, hi); });
225 CHECK(runs.size() == 1 && runs[0] == std::make_pair(top, UINTPTR_MAX));
226
227 runs.clear();
228 std::vector<std::uintptr_t> max_page = {UINTPTR_MAX};
229 coalesce_page_runs(max_page, kPage, [&](std::uintptr_t lo, std::uintptr_t hi) { runs.emplace_back(lo, hi); });
230 CHECK(runs.empty());
231 }
232
233 // 7. PageCommitBits: lock-free 2-bit-per-page commit/notify tracker across 64-bit word boundaries.
234 {
235 PageCommitBits<> bits;
236 CHECK(bits.size() == 0 && !bits.is_committed(0) && !bits.mark_committed(0));
237
238 bits.init(105, false);
239 CHECK(bits.size() == 105);
240 for (const std::size_t idx : {std::size_t{0}, std::size_t{31}, std::size_t{32}, std::size_t{63},
241 std::size_t{64}, std::size_t{104}}) {
242 CHECK(!bits.is_committed(idx) && !bits.is_notified(idx));
243 CHECK(bits.mark_committed(idx)); // 0 -> 1
244 CHECK(!bits.mark_committed(idx)); // already committed
245 CHECK(bits.is_committed(idx) && !bits.is_notified(idx));
246 CHECK(bits.mark_committed_and_notified(idx)); // notified 0 -> 1 once
247 CHECK(!bits.mark_committed_and_notified(idx)); // repeat does not re-notify
248 CHECK(bits.is_committed(idx) && bits.is_notified(idx));
249 }
250 // Adjacent untouched indices remain clear; out-of-bounds stays safe.
251 CHECK(!bits.is_committed(1) && !bits.is_notified(1));
252 CHECK(!bits.is_committed(105) && !bits.mark_committed_and_notified(105));
253
254 // init(..., true) marks all pages committed & notified up front (file-backed / Wine sections).
255 bits.init(70, true);
256 CHECK(bits.is_committed(0) && bits.is_notified(0));
257 CHECK(bits.is_committed(69) && bits.is_notified(69));
258 CHECK(!bits.mark_committed(69) && !bits.mark_committed_and_notified(69));
259 }
260
157 std::printf("title_texture_refresh_test: all checks passed\n"); 261 std::printf("title_texture_refresh_test: all checks passed\n");
158 return 0; 262 return 0;
159} 263}
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index ad3d18d0c..9f31d0f3b 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -1804,7 +1804,10 @@ void test_commit_physical_pages(const PhysicalApi& api) {
1804 check(!rt::xmem::commit_physical_pages(nullptr, 1), "committing from a null page array fails"); 1804 check(!rt::xmem::commit_physical_pages(nullptr, 1), "committing from a null page array fails");
1805 const uint64_t unknown = 0x1fffff0; 1805 const uint64_t unknown = 0x1fffff0;
1806 check(!rt::xmem::commit_physical_pages(&unknown, 1), "committing a page number that was never allocated fails"); 1806 check(!rt::xmem::commit_physical_pages(&unknown, 1), "committing a page number that was never allocated fails");
1807 const auto gen_before_unmapped = leonida::title_memory_map::generation();
1807 check(rt::xmem::commit_physical_pages(pages, 2), "commit_physical_pages commits two pages that were never mapped"); 1808 check(rt::xmem::commit_physical_pages(pages, 2), "commit_physical_pages commits two pages that were never mapped");
1809 check(leonida::title_memory_map::generation() == gen_before_unmapped,
1810 "committing unmapped physical pages does not broadcast title_memory_map::changed()");
1808 1811
1809 auto* const window = static_cast<uint8_t*>( 1812 auto* const window = static_cast<uint8_t*>(
1810 api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); 1813 api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE));
@@ -1821,6 +1824,28 @@ void test_commit_physical_pages(const PhysicalApi& api) {
1821 "the two committed by number are committed in the window and the third retains its initial state"); 1824 "the two committed by number are committed in the window and the third retains its initial state");
1822 check(read_u32(window, 0) == 0 && read_u32(window + kPage64k, 0) == 0, 1825 check(read_u32(window, 0) == 0 && read_u32(window + kPage64k, 0) == 0,
1823 "pages committed by number read as zero"); 1826 "pages committed by number read as zero");
1827 // Committing a mapped physical page notifies only its mapped VA (never a full-space broadcast), and repeating
1828 // commit_physical_pages on an already-committed page emits zero title_memory_map changes.
1829 const auto gen_before_mapped = leonida::title_memory_map::generation();
1830 check(rt::xmem::commit_physical_pages(&pages[2], 1), "commit_physical_pages commits mapped page 2");
1831 const auto page2_va = reinterpret_cast<std::uintptr_t>(window + 2 * kPage64k);
1832 const std::uintptr_t unrelated_va = page2_va >= 0x1000000 ? page2_va - 0x1000000 : page2_va + 0x1000000;
1833 std::uint64_t map_now = 0;
1834 bool hit_page2 = false, hit_unrelated = false;
1835 const bool ok_p2 = leonida::title_memory_map::changes_since(
1836 gen_before_mapped, map_now, page2_va, page2_va + kPage64k,
1837 [&](std::uintptr_t from, std::uintptr_t to) { if (from < to) hit_page2 = true; });
1838 const bool ok_un = leonida::title_memory_map::changes_since(
1839 gen_before_mapped, map_now, unrelated_va, unrelated_va + kPage64k,
1840 [&](std::uintptr_t from, std::uintptr_t to) { if (from < to) hit_unrelated = true; });
1841 check(ok_p2 && ok_un && !hit_unrelated,
1842 "committing a mapped physical page never invalidates unrelated title VAs");
1843 if (info[2].State == MEM_RESERVE)
1844 check(hit_page2, "committing a newly committed mapped page notifies its exact VA");
1845 const auto gen_after_first = leonida::title_memory_map::generation();
1846 check(rt::xmem::commit_physical_pages(&pages[2], 1), "repeat commit_physical_pages succeeds");
1847 check(leonida::title_memory_map::generation() == gen_after_first,
1848 "repeat commit_physical_pages on an already-committed page emits no map change");
1824 api.map(window, kPages, nullptr); 1849 api.map(window, kPages, nullptr);
1825 } 1850 }
1826 check(api.free_pages(kPages, pages) == TRUE, "XMemFreePhysicalPages frees them"); 1851 check(api.free_pages(kPages, pages) == TRUE, "XMemFreePhysicalPages frees them");