From a1df1713d49f06556eeb26b8015cce2841951c5c Mon Sep 17 00:00:00 2001 From: DadaCap <167002618+DadaCap@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:44:13 +0100 Subject: [PATCH] d3d12: LEONIDA_TITLE_PARTIAL_MIPS fills the readable smaller mips of a title texture whose larger ones are not there The XG layout of a 2D texture of one slice stores its mips from the smallest to the largest, so the mips from m on are a prefix of its footprint (mip_chain_bytes). With LEONIDA_TITLE_PARTIAL_MIPS=1 the readability probe returns the readable prefix (texture_memory_readable_bytes), first_mip_within the first mip it holds; when the last slot-70 view starts there or later, those mips are filled and only the T#s of views that start there or later are published. The others stay on the fallback until a later fill has their mips. A texture not filled, or filled in part, whose pages came through a map change is marked stale so the next pass fills it. Off by default: the image still has memory for every mip. LEONIDA_TITLE_PARTIAL_MIPS_MB (2048) bounds the image memory of the textures filled in part. Unset, the behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Gt9hwRYcpySx4P4ncQ3wD5 --- docs/d3d12_vulkan.md | 9 ++ runtime/README.md | 2 + runtime/shims/d3d12_title_image_upload.h | 9 +- runtime/shims/d3d12_vulkan_device.cpp | 190 ++++++++++++++++++----- runtime/shims/xg_xs_layout.h | 16 ++ runtime/src/title_texture_memory.h | 26 ++-- runtime/test/xg_xs_test.cpp | 59 +++++++ 7 files changed, 260 insertions(+), 51 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index c29a9ab2f9..1a1b448677 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2946,6 +2946,15 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv complete CPU read. Copies of descriptors written earlier resolve to the fallback until that upload succeeds. `LEONIDA_TITLE_IMAGE_DEFER=0` allocates these textures eagerly. The memory probe reports the live unbound image count and its Vulkan memory requirements in MiB. +- With `LEONIDA_TITLE_PARTIAL_MIPS=1`, such a texture can be filled before all its pages are readable. The XG + layout of a 2D texture of one slice stores its mips from the smallest to the largest, so the mips from `m` on are + the first `mip_chain_bytes(layout, m)` bytes from its base (`xg_xs_layout.h`; checked in `xg_xs_test` for tiled, + tail and linear layouts). The probe (`texture_memory_readable_bytes`) returns how many bytes from the base are + readable and `first_mip_within` the first mip those hold. When the last slot-70 view starts at that mip or later, + the mips from there on are filled and only the descriptor keys of views that start there or later are published. + The others stay on the fallback (`PendingImage::first_mip`) until a later fill has their mips. The image still has + memory for every mip: `LEONIDA_TITLE_PARTIAL_MIPS_MB` (2048) limits the image memory of the textures filled in + part. Arrays, cubes and volumes are filled whole or not at all. - Small optimal Vulkan images synthesized for slot-70 texture views share memory pages. Each slice meets the image's size, alignment and memory type requirements. The GPU retirement queue destroys the image before its slice can be reused. Large images, dedicated-only images, and failed pool allocations use individual memory diff --git a/runtime/README.md b/runtime/README.md index 2af9dc2154..f53107b143 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -382,6 +382,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | | `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. | +| `LEONIDA_TITLE_PARTIAL_MIPS` | unset | `1`: a 2D texture of one slice the title keeps in its own memory, whose larger mips are not readable, is filled from the first mip that is when its last slot-70 view starts there or later. Views that start above keep the fallback until a later fill has their mips. Unset, a texture waits for all its mips. | +| `LEONIDA_TITLE_PARTIAL_MIPS_MB` | `2048` | With `LEONIDA_TITLE_PARTIAL_MIPS=1`, the image memory the textures filled in part may hold, in MiB: each has memory for all its mips. A texture past it keeps the fallback. | | `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. | | `LEONIDA_SLOT133_IMPORT` | on | *Diagnostic.* `0` imports no title-placed buffer (device slot 133) as host memory: each takes the shadow-buffer fallback, so no GPU store can reach the title's memory through an import. | | `LEONIDA_ARENA_NULL_MB` | `0` | `n` (MiB) keeps the first `n` MiB of the descriptor arena, at `heap_base + 0`, zeroed and never allocated, and moves the zero page and the quad indices above it. A translated shader whose address arithmetic starts from a null base then reads or writes there instead of in a title buffer or the shared zero page. Ignored when it would take half of the arena or more; the device logs the region it made. | diff --git a/runtime/shims/d3d12_title_image_upload.h b/runtime/shims/d3d12_title_image_upload.h index 2bb092f999..db73d46ea3 100644 --- a/runtime/shims/d3d12_title_image_upload.h +++ b/runtime/shims/d3d12_title_image_upload.h @@ -35,20 +35,21 @@ class TitleImageUpload { ready_ = VK_NULL_HANDLE; } + // Uploads the mips from `from` on; `tiled` then needs only mip_chain_bytes(layout, from) bytes. template bool write(Device& d, leonida::ResourceId id, const leonida::ResourceBinding& image, const xg_xs::Texture& layout, const std::uint8_t* tiled, std::vector& columns, - bool inspect, bool& nonzero) { + bool inspect, bool& nonzero, unsigned from = 0) { const auto block = leonida::copy_block_format(image, VK_IMAGE_ASPECT_COLOR_BIT); const auto mips = layout.layout.mips; const auto layers = layout.array; - if (!block.bytes || block.bytes != layout.format.bytes || !mips || mips > image.mip_levels || + if (!block.bytes || block.bytes != layout.format.bytes || from >= mips || mips > image.mip_levels || !layers || layers > image.array_layers) return false; regions_.clear(); VkDeviceSize bytes = 0; for (unsigned layer = 0; layer < layers; ++layer) { - for (unsigned level = 0; level < mips; ++level) { + for (unsigned level = from; level < mips; ++level) { const auto& mip = layout.layout.plane[0].mips[level]; VkBufferImageCopy copy{}; copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, layer, 1}; @@ -81,7 +82,7 @@ class TitleImageUpload { [](std::uint8_t c) { return c != 0; }); } - const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, layers}; + const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, from, mips - from, 0, layers}; const auto result = d.context->write_staged_title_image(id, range, [&](const leonida::ReplayFunctions& replay, const leonida::LayoutPieces& pieces) { auto& vk = d.context->vk; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 938e8372d6..e892afe51c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -4470,8 +4470,10 @@ struct DeviceState { std::map image_entries; // A pending stream has a console descriptor immediately. Keep its keys (including aliases) // until the first complete upload. A shader hash miss selects the existing fallback image. + // Once the smaller mips are filled (publish_streamed_texture), only the views that start above first_mip wait. struct PendingImage { VkImage zero = VK_NULL_HANDLE; + std::uint32_t first_mip = UINT32_MAX; std::map keys; }; std::unordered_map pending_image_keys; @@ -4591,7 +4593,7 @@ struct DeviceState { namespace g = leonida::gfx10; if (!bindless) return false; auto pending = pending_image_keys.find(vk_image); - if (pending != pending_image_keys.end()) { + if (pending != pending_image_keys.end() && image.first_mip < pending->second.first_mip) { pending->second.keys.try_emplace(words, image); if (!pending->second.zero) return true; vk_image = pending->second.zero; @@ -4652,7 +4654,8 @@ struct DeviceState { if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); return false; } - if (const auto pending = pending_image_keys.find(vk_image); pending != pending_image_keys.end()) { + if (const auto pending = pending_image_keys.find(vk_image); + pending != pending_image_keys.end() && image.first_mip < pending->second.first_mip) { pending->second.keys.try_emplace(words, image); if (!pending->second.zero) return true; vk_image = pending->second.zero; @@ -5673,9 +5676,9 @@ class Resource final bool replay_seen() const { return replay_seen_.load(std::memory_order_relaxed); } bool staged_title() const { return staged_title_; } bool upload_staged_title(const rt::xg_xs::Texture& layout, const std::uint8_t* tiled, - std::vector& columns, bool inspect, bool& nonzero) { + std::vector& columns, bool inspect, bool& nonzero, unsigned from) { std::lock_guard lock(device_.title_upload_mutex); - return device_.title_upload.write(device_, id(), binding_, layout, tiled, columns, inspect, nonzero); + return device_.title_upload.write(device_, id(), binding_, layout, tiled, columns, inspect, nonzero, from); } // Map and the destructor notify the registry for a slot-133 placement. void mark_title_texture() { title_texture_ = true; } @@ -6562,7 +6565,7 @@ class Resource final return deferred_stream_ ? S_OK : register_bound_texture(); } - // Called with title_texture_mutex held, after a guarded read of the complete console texture. + // Called with title_texture_mutex held, after a guarded read of the console texture (its smaller mips at least). bool back_streamed_texture() { if (!deferred_bytes_) return true; if (!image_backing_bytes_) { @@ -6577,19 +6580,32 @@ class Resource final return true; } - void publish_streamed_texture() { + // The mips from `from` on are filled: the views that start there or later get their T#s, the others wait on. + void publish_streamed_texture(unsigned from = 0) { if (!deferred_stream_) return; std::lock_guard lock(device_.descriptor_mutex); - auto pending = device_.pending_image_keys.extract(image_); + DeviceState::PendingImage ready; + if (const auto pending = device_.pending_image_keys.find(image_); pending != device_.pending_image_keys.end()) { + ready = pending->second; + std::erase_if(ready.keys, [&](const auto& key) { return key.second.first_mip < from; }); + if (from) { + pending->second.first_mip = from; + std::erase_if(pending->second.keys, [&](const auto& key) { return key.second.first_mip >= from; }); + } else { + device_.pending_image_keys.erase(pending); + } + } const auto owner = device_.images_by_address.find(image_address_); - if (!pending.empty() && owner != device_.images_by_address.end() && owner->second == this) { - if (pending.mapped().zero) device_.forget_image_views_locked(image_address_); - for (const auto& [words, image] : pending.mapped().keys) + if (owner != device_.images_by_address.end() && owner->second == this) { + if (ready.zero) device_.forget_image_views_locked(image_address_); + for (const auto& [words, image] : ready.keys) device_.bind_image_locked(words, image, image_, format_, aspects_, false, has_view_format_list(), uint_backed_); } - deferred_stream_ = false; + if (!from) deferred_stream_ = false; } + // Some view still waits, or would wait, for mips not filled yet. + bool deferred_stream() const { return deferred_stream_; } VkDeviceSize unbound_bytes() const { return image_backing_bytes() ? 0 : deferred_bytes_; } @@ -7310,7 +7326,7 @@ class Resource final std::unique_ptr deferred_attachment_; std::atomic replay_seen_{false}; bool staged_title_ = false; - std::atomic deferred_stream_{false}; // keys stay unpublished until the whole first upload succeeds + std::atomic deferred_stream_{false}; // keys stay unpublished until the mips they name are uploaded VkDeviceSize deferred_bytes_ = 0; std::uint32_t deferred_types_ = 0; bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT @@ -10279,6 +10295,11 @@ struct TitleTexture { bool full_hashed = false; bool every_byte() const { return mapped && layout.layout.size <= (4u << 20); } std::uint64_t fills = 0; + unsigned view_mip = 0; // first mip of the last slot-70 view + // The last probe: the first mip readable with every smaller one (the mip count: none; only a 2D texture of one + // slice has other values than 0 and the mip count). memory.pending(): above fill_limit, no use yet. + unsigned readable_from = 0; + unsigned filled_from = 0; // fills > 0: the image holds the mips from here on }; // The layout of a slot-133 texture as the title's own XG computer for its shape says (title_xg_layouts): how the title @@ -12168,13 +12189,16 @@ class Device final // registry, and skips an entry without a resource. const auto entries = leonida::title_texture_snapshot(state_.title_textures); title_pass_ = true; + title_partial_bytes_ = 0; + for (const auto& entry : entries) + if (entry.second->fills && entry.second->filled_from) title_partial_bytes_ += entry.second->backing_bytes; std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; const auto visit = [&](TitleTexture& t) { // A slot-133 texture's guessed layout (no slot-70 view yet) is only used once the title maps it. if (t.gpu_written || !t.layout_known || !t.resource || ((t.layout_guessed || t.layout_from_xg) && !t.mapped && !t.stale)) return; - const std::uint64_t span = t.layout.layout.size; + std::uint64_t span = fill_bytes(t); const bool always = t.mapped && refresh_mapped_pages(); // Out of this pass's fill budget (bytes or time): a texture known to need a fill (stale) waits for the // next pass unprobed and unhashed; hashing it now would only find it changed again (measured: 10,000 @@ -12188,6 +12212,7 @@ class Device final } std::uint64_t hash = 0; if (!title_texture_readable(t)) return; + span = fill_bytes(t); // the probe may have found more mips, or fewer checked += hashed_bytes(span); ++stats.checked; const auto* bytes = reinterpret_cast(static_cast(t.cpu)); @@ -12248,7 +12273,14 @@ class Device final TitleTexture& t = *entry.second; if (t.gpu_written || !t.layout_known) continue; const std::uint64_t begin = t.cpu, end = t.cpu + t.layout.layout.size; - if (map_all || leonida::title_write_overlaps(title_map_changes_, begin, end)) t.memory.retry(); + const bool remapped = leonida::title_write_overlaps(title_map_changes_, begin, end); + if (map_all || remapped) t.memory.retry(); + // Pages that came without a noted write: a texture not filled, or not all of it, is filled in this + // pass's round of stale ones; the sweep reached it many passes later. + if (partial_mips() && remapped && !t.stale && t.resource && !t.layout_guessed && !t.layout_from_xg && + (!t.fills || t.filled_from) && title_texture_readable(t) && + (!t.fills || t.readable_from < t.filled_from)) + t.stale = true; if (leonida::title_write_overlaps(written, begin, end)) { t.memory.retry(); t.stale = true; @@ -12311,6 +12343,9 @@ class Device final std::uint64_t views = 0, null_views = 0, of_slot133 = 0, of_cache = 0, made = 0, retired = 0, registered = 0, refusals = 0, written_ranges = 0, unmaps = 0, unreadable = 0, pending_views = 0; std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0; + // Fills of some mips only; textures whose first fill was one; those that got larger mips later; first fills + // refused by LEONIDA_TITLE_PARTIAL_MIPS_MB. + std::uint64_t partial_fills = 0, partial_textures = 0, partial_upgrades = 0, partial_refused = 0; std::uint64_t staged_fills = 0, staged_ns = 0; // refresh_title_textures, since the last log line std::uint64_t passes = 0, checked = 0, hashed = 0, changed = 0, deferred = 0, filled_bytes = 0, @@ -12396,6 +12431,7 @@ class Device final Resource* r = nullptr; rt::xg_xs::Texture layout{}; std::uint64_t cpu = 0, fills = 0; + unsigned from = 0; bool every_byte = false; { std::lock_guard lock(state_.title_texture_mutex); @@ -12412,6 +12448,7 @@ class Device final layout = t.layout; cpu = t.cpu; fills = t.fills; + from = fill_from(t); every_byte = t.every_byte(); } else { filled = fill_title_texture(t, true) != 0; @@ -12420,7 +12457,7 @@ class Device final } } if (r) { - filled = fill_unlocked(address, *r, layout, cpu, fills, every_byte, f); + filled = fill_unlocked(address, *r, layout, cpu, fills, from, every_byte, f); r->Release(); } std::size_t left = 0; @@ -12444,8 +12481,8 @@ class Device final // The fill worker's fill of a staged texture: copy, hash and upload without the registry lock, then the result // under it, if the registry still names `r` at `address` and nobody filled it meanwhile. bool fill_unlocked(std::uint64_t address, Resource& r, const rt::xg_xs::Texture& layout, std::uint64_t cpu, - std::uint64_t fills, bool every_byte, TitleFiller& f) { - const std::uint64_t span = layout.layout.size; + std::uint64_t fills, unsigned from, bool every_byte, TitleFiller& f) { + const std::uint64_t span = rt::xg_xs::mip_chain_bytes(layout, from); f.tiled.resize(std::size_t(span)); const bool copied = copy_guarded(f.tiled.data(), reinterpret_cast(cpu), std::size_t(span), title_memory_write_combined(cpu)); @@ -12456,7 +12493,7 @@ class Device final hash_guarded(f.tiled.data(), f.tiled.size(), hash); full_hashed = every_byte && hash_guarded(f.tiled.data(), f.tiled.size(), full, true); const auto start = std::chrono::steady_clock::now(); - ok = r.upload_staged_title(layout, f.tiled.data(), f.columns, false, nonzero); + ok = r.upload_staged_title(layout, f.tiled.data(), f.columns, false, nonzero, from); staged_ns = std::chrono::duration_cast(std::chrono::steady_clock::now() - start) .count(); } @@ -12479,7 +12516,7 @@ class Device final } ++title_stats_.staged_fills; if (t.fills != fills) return true; // another fill recorded itself in between: its hash is as good - if (t.owned && !t.fills) r.publish_streamed_texture(); + note_filled_from(t, from); t.hash = hash; t.hashed = true; t.full_hash = full; @@ -12534,6 +12571,7 @@ class Device final std::chrono::steady_clock::time_point title_retry_all_{}; // likewise leonida::TitleWriteRanges title_map_changes_; // likewise, scratch VkDeviceSize retired_backing_ = 0; + VkDeviceSize title_partial_bytes_ = 0; // likewise: image memory of the textures filled in part, as of this pass std::vector> retired_title_textures_; // likewise std::vector title_tiled_, title_linear_; // scratch, under title_texture_mutex std::vector title_columns_; @@ -12599,6 +12637,7 @@ class Device final return written; }; auto& textures = state_.title_textures; + const unsigned view_mip = srv.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D ? srv.Texture2D.MostDetailedMip : 0; const auto it = textures.find(address); // An entry without a resource is one destroyed inside the registry, waiting for drain_titles_gone. TitleTexture* t = it == textures.end() || !it->second->resource ? nullptr : it->second.get(); @@ -12644,12 +12683,16 @@ class Device final }(); retire_title_texture(*t); textures.erase(address); - t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector{}); + t = make_title_texture(d, words, srv, address, view_mip, same_shape ? formats : std::vector{}); } else if (t) { ++title_stats_.of_cache; + if (t->view_mip != view_mip) { + t->view_mip = view_mip; + if (!t->fills) t->memory.retry(); // what is readable may do for this view + } refresh_title_texture(*t); } else { - t = make_title_texture(d, words, srv, address, {}); + t = make_title_texture(d, words, srv, address, view_mip, {}); } return t && write(*t); } @@ -12663,7 +12706,7 @@ class Device final TitleTexture* make_title_texture(const rt::xg_xs::ResourceDesc& d, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint64_t address, - std::vector formats) { + unsigned view_mip, std::vector formats) { namespace xg = rt::xg_xs; if (d.flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) @@ -12673,11 +12716,10 @@ class Device final auto entry = std::make_shared(); const char* why = nullptr; if (!title_layout(d, entry->layout, why)) return refuse_title_view(why, d, address), nullptr; - const std::uint64_t span = entry->layout.layout.size; entry->cpu = leonida::title_gpu_views::to_cpu(address); // A streamed texture can have views before its pages arrive. Keep the descriptor stable across its first fill. entry->memory.check(0, check_pages_before_read(), - [&] { return probe_title_memory(entry->cpu, span, false); }); + [&] { return probe_title_texture(*entry, false); }); title_stats_.unreadable += entry->memory.pending(); // The image takes the view's format too when the element is the same size (five-star-recomp does the same); // views in other formats of the same description add theirs (place_title_view). @@ -12735,15 +12777,19 @@ class Device final entry->set_resource(r); entry->owned = true; entry->formats = std::move(formats); + entry->view_mip = view_mip; + if (entry->memory.pending() && entry->readable_from <= fill_limit(*entry)) + entry->memory.retry(); // some mips do for this view + const bool readable = title_texture_readable(*entry); if (title_fill_async()) { entry->stale = true; // filled by the fill worker (queued below, once it is in the registry) - } else if (!entry->memory.pending()) { + } else if (readable) { fill_title_texture(*entry, true); } ++title_stats_.made; TitleTexture* t = entry.get(); state_.title_textures[address] = std::move(entry); - if (title_fill_async() && !t->memory.pending()) queue_title_fill(address); + if (title_fill_async() && readable) queue_title_fill(address); return t; } @@ -12758,6 +12804,49 @@ class Device final ++title_stats_.retired; } + // LEONIDA_TITLE_PARTIAL_MIPS=1 (off by default). A slot-70 2D texture whose larger mips are not readable is filled from the + // first mip that is, with every smaller one, when its last view starts there or later. The T#s of views that start + // above stay on the fallback (PendingImage::first_mip), so no shader samples a mip that was not filled. Larger + // mips come with a later fill; one whose filled mips are gone keeps them. + // shortcut: the image has memory for every mip, LEONIDA_TITLE_PARTIAL_MIPS_MB in all; make it without the missing + // mips when that limit is what keeps textures on the fallback. + static bool partial_mips() { + static const bool enabled = [] { + const char* v = std::getenv("LEONIDA_TITLE_PARTIAL_MIPS"); + return v && std::strcmp(v, "1") == 0; + }(); + return enabled; + } + static VkDeviceSize partial_mips_budget() { + static const VkDeviceSize bytes = [] { + const char* v = std::getenv("LEONIDA_TITLE_PARTIAL_MIPS_MB"); + return VkDeviceSize(v && *v ? std::strtoull(v, nullptr, 10) : 2048) << 20; + }(); + return bytes; + } + // Only an image whose T#s are published with its fills (deferred_stream) may hold a part of its mips. + static bool partial_texture(const TitleTexture& t) { + return partial_mips() && t.owned && t.resource && t.resource->deferred_stream() && + t.layout.layout.dimension == rt::xg_xs::kTexture2D && t.layout.array == 1; + } + // The largest first mip a fill may start at: what is filled already is never left half old. + static unsigned fill_limit(const TitleTexture& t) { + if (!partial_texture(t)) return 0; + return t.fills ? t.filled_from : std::min(t.view_mip, t.layout.layout.mips - 1); + } + static unsigned fill_from(const TitleTexture& t) { return std::min(t.readable_from, fill_limit(t)); } + static std::uint64_t fill_bytes(const TitleTexture& t) { return rt::xg_xs::mip_chain_bytes(t.layout, fill_from(t)); } + + // After an upload of the mips from `from` on, before ++t.fills. + void note_filled_from(TitleTexture& t, unsigned from) { + if (t.owned && (!t.fills || from < t.filled_from)) t.resource->publish_streamed_texture(from); + title_stats_.partial_fills += from != 0; + title_stats_.partial_textures += from && !t.fills; + title_stats_.partial_upgrades += t.fills && from < t.filled_from; + if (from && !t.fills) title_partial_bytes_ += t.backing_bytes; + t.filled_from = from; + } + static bool texture_probe() { static const bool enabled = [] { const char* v = std::getenv("LEONIDA_TEXTURE_PROBE"); @@ -12782,11 +12871,13 @@ class Device final return enabled; } - // texture_memory_readable, timed and counted (TitleTextureStats::probes). - bool probe_title_memory(std::uint64_t cpu, std::uint64_t span, bool waited, - leonida::TexturePageCommitter commit = nullptr) { + // texture_memory_readable_bytes, timed and counted (TitleTextureStats::probes). + // True when a fill can use what is readable; t.readable_from says what that is. + bool probe_title_texture(TitleTexture& t, bool waited, leonida::TexturePageCommitter commit = nullptr) { const auto start = std::chrono::steady_clock::now(); - const bool readable = leonida::texture_memory_readable(cpu, span, commit); + t.readable_from = rt::xg_xs::first_mip_within( + t.layout, leonida::texture_memory_readable_bytes(std::uintptr_t(t.cpu), t.layout.layout.size, commit)); + const bool readable = t.readable_from <= fill_limit(t); const std::size_t where = title_pass_ ? 0 : 1; TitleTextureStats& s = title_stats_; s.probe_ns[where] += std::chrono::duration_cast( @@ -12807,7 +12898,7 @@ class Device final // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic // retry of refresh_title_textures asks again. return t.memory.check(0, guard && !mapped, - [&] { return probe_title_memory(t.cpu, t.layout.layout.size, waited, commit); }, + [&] { return probe_title_texture(t, waited, commit); }, guard && !mapped); } @@ -12834,14 +12925,15 @@ class Device final std::uint64_t hash = 0; if (!title_texture_readable(t)) return; if (!hash_guarded(reinterpret_cast(static_cast(t.cpu)), - std::size_t(t.layout.layout.size), hash)) { + std::size_t(fill_bytes(t)), hash)) { t.memory.defer(); return; } if (!t.hashed || hash != t.hash || t.stale) fill_title_texture(t, true); } - // Snapshot the whole footprint before uploading any subresource. A concurrent unmap defers the fill. + // Snapshot the footprint (that of the mips the fill is for) before uploading any subresource. A concurrent unmap + // defers the fill. // Private title staging bypasses the D3D12 submit callbacks. Generic staged copies require an outer fill. std::uint64_t fill_title_texture(TitleTexture& t, bool staged) { const rt::xg_xs::Texture& layout = t.layout; @@ -12852,8 +12944,14 @@ class Device final t.stale = true; return 0; } - const std::uint64_t span = layout.layout.size; if (!title_texture_readable(t)) return 0; + const unsigned from = fill_from(t); + const std::uint64_t span = fill_bytes(t); + if (from && t.unbound_bytes && title_partial_bytes_ + t.unbound_bytes > partial_mips_budget()) { + ++title_stats_.partial_refused; + t.stale = false; // the sweep and its views ask again + return 0; + } title_tiled_.resize(std::size_t(span)); if (!copy_guarded(title_tiled_.data(), reinterpret_cast(t.cpu), std::size_t(span), title_memory_write_combined(t.cpu))) { @@ -12885,14 +12983,14 @@ class Device final bool ok = true; if (t.resource->staged_title()) { const auto start = std::chrono::steady_clock::now(); - ok = t.resource->upload_staged_title(layout, title_tiled_.data(), title_columns_, trace_pool, nonzero); + ok = t.resource->upload_staged_title(layout, title_tiled_.data(), title_columns_, trace_pool, nonzero, from); title_stats_.staged_ns += std::chrono::duration_cast( std::chrono::steady_clock::now() - start).count(); if (ok) ++title_stats_.staged_fills; if (!ok) log_once("staged title texture upload failed, format", int(t.resource->format())); } else { for (std::uint32_t slice = 0; slice < slices && ok; ++slice) { - for (std::uint32_t level = 0; level < mips && ok; ++level) { + for (std::uint32_t level = from; level < mips && ok; ++level) { const auto& mip = layout.layout.plane[0].mips[level]; const std::uint32_t row_pitch = mip.width_elements * layout.format.bytes; const std::uint32_t slice_pitch = row_pitch * mip.height_elements; @@ -12920,7 +13018,7 @@ class Device final std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=%d nonzero=%d\n", static_cast(t.cpu), static_cast(span), int(staged), int(nonzero)); - if (t.owned && !t.fills) t.resource->publish_streamed_texture(); + note_filled_from(t, from); t.hash = hash; t.hashed = true; t.stale = false; @@ -13015,6 +13113,24 @@ class Device final static_cast(s.registered), mapped, filled, static_cast(s.fills), double(s.fill_bytes) / 1048576.0, static_cast(s.fill_failures)); + if (s.partial_fills || s.partial_refused) { + std::size_t now = 0; + VkDeviceSize held = 0, used = 0; + for (const auto& [address, t] : state_.title_textures) + if (t->fills && t->filled_from) { + ++now; + held += t->backing_bytes; + used += rt::xg_xs::mip_chain_bytes(t->layout, t->filled_from); + } + std::fprintf(stderr, "[rt] d3d12: title textures filled in part: %zu now (%.1f MiB of image memory, %.1f MiB " + "filled), %llu in all, %llu partial fills, %llu got larger mips later, %llu refused by " + "LEONIDA_TITLE_PARTIAL_MIPS_MB\n", + now, double(held) / 1048576.0, double(used) / 1048576.0, + static_cast(s.partial_textures), + static_cast(s.partial_fills), + static_cast(s.partial_upgrades), + static_cast(s.partial_refused)); + } const auto host = state_.context->host_texture_stats(); std::fprintf(stderr, "[rt] d3d12: ordered title host copies %llu, GPU waits %llu; " "slot-70 views awaiting readable memory: %llu\n", diff --git a/runtime/shims/xg_xs_layout.h b/runtime/shims/xg_xs_layout.h index 36d6c0db30..155822c862 100644 --- a/runtime/shims/xg_xs_layout.h +++ b/runtime/shims/xg_xs_layout.h @@ -269,6 +269,22 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) { return true; } +// The bytes from the texture's base that hold the mips from `first` on (the whole texture for 0). Only a 2D texture of +// one slice stores its chain from the smallest mips to the largest, so only there is a part of it a prefix. +inline uint64_t mip_chain_bytes(const Texture& t, unsigned first) { + const auto& plane = t.layout.plane[0]; + if (!first || first >= t.layout.mips || t.layout.dimension != kTexture2D || t.array != 1) return t.layout.size; + if (first >= plane.standard_mips) return t.layout.alignment; // the tail is one block + return plane.mips[first].offset + plane.mips[first].size; +} + +// The first mip that is held, with every smaller one, by the `bytes` readable bytes from the texture's base; the mip +// count when not even the smallest is. +inline unsigned first_mip_within(const Texture& t, uint64_t bytes) { + for (unsigned m = 0; m < t.layout.mips; ++m) + if (mip_chain_bytes(t, m) <= bytes) return m; + return t.layout.mips; +} // These RB+ equation rows come directly from AMD addrlib. The other two // non-XOR modes already have equations in Leonida's GFX10 detiler. diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index a97e5bed66..e01ec4dfd8 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h @@ -31,32 +31,38 @@ class TextureReadability { using TexturePageCommitter = bool (*)(const void*, std::size_t); -// Check the whole footprint. A committed first page says nothing about a streamed mip farther on. -inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, TexturePageCommitter commit = nullptr) { - if (!base || !size || size > (std::numeric_limits::max)() - base) return false; +// How many of the bytes from `base` are readable, up to the first page that is not (at most `size`). +inline std::uint64_t texture_memory_readable_bytes(std::uintptr_t base, std::uint64_t size, + TexturePageCommitter commit = nullptr) { + if (!base || !size || size > (std::numeric_limits::max)() - base) return 0; const auto end = base + size; for (auto at = base; at < end;) { MEMORY_BASIC_INFORMATION region{}; const auto* address = reinterpret_cast(at); - if (!VirtualQuery(address, ®ion, sizeof(region))) return false; + if (!VirtualQuery(address, ®ion, sizeof(region))) return at - base; // A persistent Map can name an xmem section whose physical pages commit on first touch. // Only xmem may commit them. A bare reservation or an inaccessible page must still defer. if (commit && region.State == MEM_RESERVE && region.Type == MEM_MAPPED) { - if (!commit(address, end - at) || !VirtualQuery(address, ®ion, sizeof(region))) return false; + if (!commit(address, end - at) || !VirtualQuery(address, ®ion, sizeof(region))) return at - base; } - if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return false; + if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return at - base; switch (region.Protect & 0xff) { case PAGE_READONLY: case PAGE_READWRITE: case PAGE_WRITECOPY: case PAGE_EXECUTE_READ: case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: break; - default: return false; + default: return at - base; } const auto start = reinterpret_cast(region.BaseAddress); - if (at < start || at - start >= region.RegionSize) return false; + if (at < start || at - start >= region.RegionSize) return at - base; const auto available = region.RegionSize - (at - start); - if (available >= end - at) return true; + if (available >= end - at) return size; at += available; } - return true; + return size; +} + +// Check the whole footprint. A committed first page says nothing about a streamed mip farther on. +inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, TexturePageCommitter commit = nullptr) { + return size && texture_memory_readable_bytes(base, size, commit) == size; } } // namespace leonida diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index 18356cb416..ea5965bccd 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp @@ -81,6 +81,51 @@ void check_addresses(const Texture& t) { check(true, "every mip/array element has a distinct aligned address inside the resource"); } +// A fill of the smaller mips only (d3d12_vulkan_device.cpp, partial_mips) reads mip_chain_bytes(t, first) bytes from the +// base: those hold every element of the mips from `first` on, and the next larger mip is not among them. +void check_mip_prefix(uint32_t format, uint32_t layout, uint64_t width, uint32_t height, uint16_t mips) { + ResourceDesc d{}; + d.dimension = kTexture2D; + d.width = width; + d.height = height; + d.depth_or_array = 1; + d.mips = mips; + d.format = format; + d.samples = 1; + d.layout = layout; + Texture t; + check(build_texture(d, t), "mip prefix case lays out"); + const auto& plane = t.layout.plane[0]; + std::vector whole(size_t(t.layout.size)); + for (size_t i = 0; i < whole.size(); ++i) whole[i] = uint8_t(i * 31 + (i >> 8) * 7); + std::vector columns; + bool same = true, ordered = true, found = true; + for (unsigned first = 0; first < t.layout.mips; ++first) { + const uint64_t bytes = mip_chain_bytes(t, first); + // Exactly the prefix, so that a read past it is a heap error under a checked allocator and a difference here. + std::vector part(whole.size(), 0xee); + std::copy_n(whole.begin(), size_t(bytes), part.begin()); + for (unsigned level = first; level < t.layout.mips; ++level) { + const auto& mip = plane.mips[level]; + const uint32_t pitch = mip.width_elements * t.format.bytes; + std::vector a(size_t(pitch) * mip.height_elements), b(a.size()); + copy_elements(t, level, 0, whole.data(), a.data(), pitch, pitch * mip.height_elements, columns); + copy_elements(t, level, 0, part.data(), b.data(), pitch, pitch * mip.height_elements, columns); + same &= a == b; + } + const bool in_tail = first > plane.standard_mips; + found &= first_mip_within(t, bytes) == (in_tail ? plane.standard_mips : first); + found &= first_mip_within(t, bytes - 1) == (first >= plane.standard_mips ? t.layout.mips + : first + 1 < t.layout.mips ? first + 1 + : t.layout.mips); + if (first && first <= plane.standard_mips) ordered &= bytes < mip_chain_bytes(t, first - 1); + } + check(same, "the prefix of a mip holds it and every smaller one"); + check(ordered && mip_chain_bytes(t, 0) == t.layout.size, "a larger mip needs a longer prefix, mip 0 the whole texture"); + check(found, "the first mip within a readable prefix is the largest one it holds"); + check(first_mip_within(t, 0) == t.layout.mips, "nothing readable: no mip"); +} + // copy_elements (row + column addressing) reads every element where offset() says it is. void check_detile(const Texture& t) { const ElementAddress address(t); @@ -389,6 +434,19 @@ void test_models_agree() { } // namespace int main() { + check_mip_prefix(DXGI_FORMAT_BC7_UNORM, 0x109, 1024, 1024, 11); // 64 KiB blocks and a tail + check_mip_prefix(DXGI_FORMAT_BC1_UNORM, 0x105, 512, 256, 10); // 4 KiB blocks and a tail + check_mip_prefix(DXGI_FORMAT_BC7_UNORM, 0x109, 300, 700, 10); // extents that are no power of two + check_mip_prefix(DXGI_FORMAT_R8G8B8A8_UNORM, 0x10a, 256, 256, 1); // one mip + check_mip_prefix(DXGI_FORMAT_R8G8B8A8_UNORM, 0x105, 512, 512, 2); // a chain too short for a tail + check_mip_prefix(DXGI_FORMAT_R8G8B8A8_UNORM, 1, 256, 128, 9); // linear + { + ResourceDesc d{kTexture2D, 0, 256, 256, 6, 9, DXGI_FORMAT_BC7_UNORM, 1, 0, 0x109, 0}; + Texture cube; + check(build_texture(d, cube) && mip_chain_bytes(cube, 4) == cube.layout.size && + first_mip_within(cube, cube.layout.size - 1) == cube.layout.mips, + "an array is readable as a whole or not at all"); + } { struct Entry { bool mapped, stale; int id; }; Entry first{false, false, 1}, mapped{true, false, 2}, stale{false, true, 3}; @@ -502,6 +560,7 @@ int main() { DWORD previous = 0; if (!VirtualProtect(reservation, page, PAGE_READWRITE | PAGE_GUARD, &previous)) return 1; check(!leonida::texture_memory_readable(address, 2 * page), "guarded texture page remains untouched"); + check(leonida::texture_memory_readable_bytes(address, 2 * page) == 0, "the readable prefix ends at a guarded first page"); VirtualFree(reservation, page, MEM_DECOMMIT); check(!leonida::texture_memory_readable(address, page), "previously readable page is rechecked after decommit"); VirtualFree(reservation, 0, MEM_RELEASE);